Module elastic::client [] [src]

HTTP client, requests and responses.

This module contains the HTTP client, as well as request and response types.

Request builders

Some commonly used endpoints have high-level builder methods you can use to configure requests easily. They're exposed as methods on the Client:

Client method Elasticsearch API Raw request type Response type
search Search SearchRequest SearchResponse
get_document Get Document GetRequest GetResponse
index_document Index Document IndexRequest IndexResponse
put_mapping Put Mapping IndicesPutMappingRequest CommandResponse
create_index Create Index IndicesCreateRequest CommandResponse

All builders follow a standard pattern:

  • The Client method that takes all required parameters without inference
  • Optional or inferred parameters can be overridden in builder methods with inference
  • send will return a specific response type

A search request for a value, where the response is matched for an ApiError:

let response = client.search::<Value>()
                     .index("myindex")
                     .ty(Some("myty"))
                     .body(json_str!({
                         query: {
                             query_string: {
                                 query: "*"
                             }
                         }
                     }))
                     .send();

match response {
    Ok(response) => {
        // Iterate through the response hits
        for hit in response.hits() {
            println!("{:?}", hit);
        }
    },
    Err(e) => {
        match *e.kind() {
            ErrorKind::Api(ref e) => {
                // handle a REST API error
            },
            ref e => {
                // handle a HTTP or JSON error
            }
        }
    }
}

The request builders are wrappers around the Client.request method, taking a raw request type. A get request for a value:

let response = client.get_document::<Value>(index("values"), id(1)).send();

Is equivalent to:

let response = client.request(GetRequest::for_index_ty_id("values", "value", 1))
                     .send()
                     .and_then(into_response::<GetResponse<Value>>);

Raw request types

Not all endpoints have strongly-typed builders, but all Elasticsearch API endpoints have a specific raw request type that can be used to build a request manually and send with the Client.request method. The builders described above are just wrappers around these request types, but that doesn't mean raw requests are a second-class API. You have more control over how requests are serialised, sent and deserialised using the raw requests API. All request endpoints live in the endpoints module.

The process of sending raw requests is described in more detail below.

The raw request process

The pieces involved in sending an Elasticsearch API request and parsing the response are modular. Each one exposes Rust traits you can implement to support your own logic but if you just want to send a search/get request and parse a search/get response then you won't need to worry about this so much.

The basic flow from request to response is:

1) Turn a concrete request type into a RequestBuilder:

[RequestType] ---> [Client.request()] ---> [RequestBuilder]

2) Send the RequestBuilder and get a ResponseBuilder:

[RequestBuilder.send()] ---> [ResponseBuilder]

3) Parse the ResponseBuilder to a response type:

[ResponseBuilder.response()] ---> [ResponseType]

The example below shows how these pieces fit together in code by sending a simple SearchRequest, with the steps in the above process labelled:

let req = SearchRequest::for_index("_all", empty_body());

let response = client.request(req) // 1
                     .send() // 2
                     .and_then(into_response::<SearchResponse<Value>>); // 3

1. Building raw requests

The endpoints module contains code-generated request types for the Elasticsearch REST API. Each request type expects its parameters upfront and is generic over the request body.

A raw search request:

let req = {
    let body = json_str!({
        query: {
            query_string: {
                query: "*"
            }
        }
    });

    SearchRequest::for_index_ty("myindex", "myty", body)
};

A raw request to index a document:

let req = {
    let body = serde_json::to_string(&doc).unwrap();

    IndexRequest::for_index_ty_id("myindex", "myty", 1, body)
};

2. Sending requests

Both high-level request builders and raw requests have some common builder methods:

  • params for setting url query parameters
  • a send method for sending the request. For high-level requests this returns a strongly-typed response. For raw requests this returns a ResponseBuilder.
let request_builder = client.request(req);

// Set additional url parameters
let request_builder = request_builder.params(|p| p
    .url_param("pretty", true)
    .url_param("refresh", true)
);

// Send the request
let response = request_builder.send();

3. Parsing responses

Call ResponseBuilder.into_response on a sent request to get a strongly typed response:

let response = client.request(req)
                     .send()
                     .and_then(into_response::<SearchResponse<Value>>);

match response {
    Ok(response) => {
        // Iterate through the response hits
        for hit in response.hits() {
            println!("{:?}", hit);
        }
    },
    Err(e) => {
        match *e.kind() {
            ErrorKind::Api(ref e) => {
                // handle a REST API error
            },
            ref e => {
                // handle a HTTP or JSON error
            }
        }
    }
}

Alternatively, call ResponseBuilder.into_raw on a sent request to get a raw HttpResponse:

let mut response = client.request(req)
                         .send()
                         .and_then(into_raw)
                         .unwrap();

let mut body = String::new();
response.read_to_string(&mut body).unwrap();

HttpResponse implements the standard Read trait so you can buffer out the raw response data. For more details see the responses module.

Modules

requests

Request types for the Elasticsearch REST API.

responses

Response types for the Elasticsearch REST API.

Structs

Client

A HTTP client for the Elasticsearch REST API.

ClientBuilder

A builder for a client.

RequestParams

Misc parameters for any request.

Functions

into_raw

Try convert a ResponseBuilder into a raw http response.

into_response

Try convert a ResponseBuilder into a concrete response type.