MCPcopy Index your code
hub / github.com/elastic/elasticsearch-rs

github.com/elastic/elasticsearch-rs @main

Chat with this repo
repository ↗ · DeepWiki ↗ · + Follow
3,304 symbols 4,883 edges 88 files 160 documented · 5%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

elasticsearch   Latest Version Docs Apache-2 licensed

Official Rust Client for Elasticsearch.

Full documentation is available at https://docs.rs/elasticsearch

The project is still very much a work in progress and in an alpha state; input and contributions welcome!

Compatibility

The Elasticsearch Rust client is forward compatible; meaning that the client supports communicating with greater minor versions of Elasticsearch. Elasticsearch language clients are also backwards compatible with lesser supported minor Elasticsearch versions.

Features

The following are a list of Cargo features that can be enabled or disabled:

  • native-tls (enabled by default): Enables TLS functionality provided by native-tls.
  • rustls-tls: Enables TLS functionality provided by rustls.
  • beta-apis: Enables beta APIs. Beta APIs are on track to become stable and permanent features. Use them with caution because it is possible that breaking changes are made to these APIs in a minor version.
  • experimental-apis: Enables experimental APIs. Experimental APIs are just that - an experiment. An experimental API might have breaking changes in any future version, or it might even be removed entirely. This feature also enables beta-apis.

Additionally, this library also runs in Web Assembly runtimes that provide the Fetch API, like node.js and web browsers.

Getting started

The client exposes all Elasticsearch APIs as associated functions, either on the root client, Elasticsearch, or on one of the namespaced clients, such as Cat, Indices, etc. The namespaced clients are based on the grouping of APIs within the Elasticsearch REST API specs from which much of the client is generated. All API functions are async only, and can be awaited.

Installing

Add elasticsearch crate and version to Cargo.toml. Choose the version that is compatible with the version of Elasticsearch you're using

[dependencies]
elasticsearch = "9.1.0-alpha.1"

The following optional dependencies may also be useful to create requests and read responses

serde = "~1"
serde_json = "~1"

Async support with tokio

The client uses reqwest to make HTTP calls, which internally uses the tokio runtime for async support. As such, you may require to take a dependency on tokio in order to use the client. For example, in Cargo.toml, you may need the following dependency,

tokio = { version = "*", features = ["full"] }

and to attribute async main function with #[tokio::main]

```rust,no_run

[tokio::main]

async fn main() -> Result<(), Box> { // your code ... Ok(()) }


and attribute test functions with `#[tokio::test]`

```rust,no_run
#[tokio::test]
async fn my_test() -> Result<(), Box<dyn std::error::Error>> {
    // your code ...
    Ok(())
}

Create a client

Build a transport to make API requests to Elasticsearch using the TransportBuilder, which allows setting of proxies, authentication schemes, certificate validation, and other transport related settings.

To create a client to make API calls to Elasticsearch running on https://localhost:9200

```rust,no_run use elasticsearch::Elasticsearch;

fn main() { let client = Elasticsearch::default(); }

Alternatively, you can create a client to make API calls against Elasticsearch running on a specific url

```rust,no_run
use elasticsearch::{
    Elasticsearch, Error,
    http::transport::Transport
};

fn main() -> Result<(), Error> {
    let transport = Transport::single_node("https://example.com")?;
    let client = Elasticsearch::new(transport);
    Ok(())
}

If you're running against an Elasticsearch deployment in Elastic Cloud, a client can be created using a Cloud ID and credentials retrieved from the Cloud web console

```rust,no_run use elasticsearch::{ auth::Credentials, Elasticsearch, Error, http::transport::Transport, };

fn main() -> Result<(), Error> { let cloud_id = "cluster_name:Y2xvdWQtZW5kcG9pbnQuZXhhbXBsZSQzZGFkZjgyM2YwNTM4ODQ5N2VhNjg0MjM2ZDkxOGExYQ=="; // can use other types of Credentials too, like Bearer or ApiKey let credentials = Credentials::Basic("".into(), "".into()); let transport = Transport::cloud(cloud_id, credentials)?; let client = Elasticsearch::new(transport); Ok(()) }


 More control over how a `Transport` is built can be
 achieved using `TransportBuilder` to build a transport, and
 passing it to `Elasticsearch::new()` create a new instance of `Elasticsearch`

```rust,no_run
use url::Url;
use elasticsearch::{
    Error, Elasticsearch,
    http::transport::{TransportBuilder,SingleNodeConnectionPool},
};

fn main() -> Result<(), Error> {
    let url = Url::parse("https://example.com")?;
    let conn_pool = SingleNodeConnectionPool::new(url);
    let transport = TransportBuilder::new(conn_pool).disable_proxy().build()?;
    let client = Elasticsearch::new(transport);
    Ok(())
}

You can also configure the list of nodes of an Elasticsearch cluster using the MultiNodeConnectionPool, and the client will do a round-robin load balancing among those nodes. It can also periodically re-seed the list of nodes by querying the cluster.

Making API calls

The following will execute a POST request to /_search?allow_no_indices=true with a JSON body of {"query":{"match_all":{}}}

```rust,no_run use elasticsearch::{Elasticsearch, Error, SearchParts}; use serde_json::{json, Value};

[tokio::main]

async fn main() -> Result<(), Box> { let client = Elasticsearch::default();

// make a search API call
let search_response = client
    .search(SearchParts::None)
    .body(json!({
        "query": {
            "match_all": {}
        }
    }))
    .allow_no_indices(true)
    .send()
    .await?;

// get the HTTP response status code
let status_code = search_response.status_code();

// read the response body. Consumes search_response
let response_body = search_response.json::<Value>().await?;

// read fields from the response body
let took = response_body["took"].as_i64().unwrap();

Ok(())

}


The client provides functions on each API builder struct
for all query string parameters available for that API. APIs with multiple
URI path variants, where some can contain parts parameters, are modelled as enums.

`Elasticsearch` also has an async `send` function on the root that allows sending an
API call to an endpoint not represented as an API function, for example, experimental
and beta APIs

```rust,no_run
use elasticsearch::{http::Method, Elasticsearch, Error, SearchParts};
use http::HeaderMap;
use serde_json::Value;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Elasticsearch::default();
    let body = b"{\"query\":{\"match_all\":{}}}";
    let response = client
        .send(
            Method::Post,
            SearchParts::Index(&["tweets"]).url().as_ref(),
            HeaderMap::new(),
            Option::<&Value>::None,
            Some(body.as_ref()),
            None,
        )
        .await?;
    Ok(())
}

License

This is free software, licensed under The Apache License Version 2.0..

Extension points exported contracts — how you extend this code

Body (Interface)
Body of an API call. Some Elasticsearch APIs accept a body as part of the API call. Most APIs expect JSON, however, the [13 …
elasticsearch/src/http/request.rs
IntoExpr (Interface)
Helper for wrapping a value as a quotable expression. [4 implementers]
api_generator/src/generator/code_gen/url/url_builder.rs
ConnectionPool (Interface)
A pool of [Connection]s, used to make API calls to Elasticsearch. A [ConnectionPool] manages the connections, with diff [3 …
elasticsearch/src/http/transport.rs
IntoStmt (Interface)
Helper for wrapping a value as a quotable statement. [2 implementers]
api_generator/src/generator/code_gen/mod.rs
ConnectionSelector (Interface)
The strategy selects an address from a given collection. */ [1 implementers]
elasticsearch/src/http/transport.rs
GetPath (Interface)
(no doc) [2 implementers]
api_generator/src/generator/code_gen/mod.rs
GetIdent (Interface)
(no doc) [1 implementers]
api_generator/src/generator/code_gen/mod.rs
HasLifetime (Interface)
(no doc) [1 implementers]
api_generator/src/generator/code_gen/mod.rs

Core symbols most depended-on inside this repo

push
called by 201
elasticsearch/src/root/bulk.rs
transport
called by 118
elasticsearch/src/ml.rs
url
called by 77
elasticsearch/src/ml.rs
transport
called by 70
elasticsearch/src/indices.rs
url
called by 69
elasticsearch/src/indices.rs
transport
called by 65
elasticsearch/src/security.rs
url
called by 64
elasticsearch/src/security.rs
send
called by 50
elasticsearch/src/ml.rs

Shape

Method 1,824
Class 708
Enum 597
Function 166
Interface 9

Languages

Rust100%

Modules by API surface

elasticsearch/src/ml.rs286 symbols
elasticsearch/src/indices.rs272 symbols
elasticsearch/src/root/mod.rs237 symbols
elasticsearch/src/security.rs223 symbols
elasticsearch/src/connector.rs129 symbols
elasticsearch/src/cat.rs118 symbols
elasticsearch/src/inference.rs106 symbols
elasticsearch/src/cluster.rs93 symbols
elasticsearch/src/snapshot.rs91 symbols
elasticsearch/src/http/transport.rs76 symbols
elasticsearch/src/async_search.rs70 symbols
elasticsearch/src/watcher.rs63 symbols

For agents

$ claude mcp add elasticsearch-rs \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact