1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
/*! HTTP client, requests and responses. This module contains the HTTP client, as well as request and response types. # The gist `elastic` provides two clients: - [`SyncClient`][SyncClient] for making synchronous requests - [`AsyncClient`][AsyncClient] for making asynchronous requests using the [`tokio`][tokio] stack. ## Building a synchronous client Use a [`SyncClientBuilder`][SyncClientBuilder] to configure a synchronous client. ``` # extern crate elastic; # use elastic::prelude::*; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { let client = SyncClientBuilder::new().build()?; # Ok(()) # } ``` Requests on the synchronous client will block the current thread until a response is received. The response is returned as a `Result`. ## Building an asynchronous client Use an [`AsyncClientBuilder`][AsyncClientBuilder] to configure an asynchronous client. The asynchronous client requires a handle to a `tokio::reactor::Core`: ``` # extern crate tokio_core; # extern crate elastic; # use elastic::prelude::*; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { # let core = tokio_core::reactor::Core::new()?; let client = AsyncClientBuilder::new().build(&core.handle())?; # Ok(()) # } ``` Requests on the asynchronous client won't block the current thread. Instead a `Future` will be returned immediately that will resolve to a response at a later point. ## Sending requests Requests can be sent with an instance of a client using a builder API: ```no_run # #[macro_use] extern crate serde_json; # extern crate elastic; # use serde_json::Value; # use elastic::prelude::*; # use elastic::Error; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { # let client = SyncClientBuilder::new().build()?; let response = client.search::<Value>() .index("myindex") .ty(Some("myty")) .body(json!({ "query": { "query_string": { "query": "*" } } })) .send(); match response { Ok(response) => { // Iterate through the response hits for hit in response.hits() { println!("{:?}", hit); } }, Err(Error::Api(e)) => { // handle a REST API error }, Err(e) => { // handle a HTTP or JSON error } } # Ok(()) # } ``` `SyncClient` and `AsyncClient` offer the same request methods. The details are explained below. # 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`][Client.search] | [Search][docs-search] | [`SearchRequest`][SearchRequest] | [`SearchResponse`][SearchResponse] [`document_get`][Client.document_get] | [Get Document][docs-get] | [`GetRequest`][GetRequest] | [`GetResponse`][GetResponse] [`document_index`][Client.document_index] | [Index Document][docs-index] | [`IndexRequest`][IndexRequest] | [`IndexResponse`][IndexResponse] [`document_update`][Client.document_update] | [Update Document][docs-update] | [`UpdateRequest`][UpdateRequest] | [`UpdateResponse`][UpdateResponse] [`document_delete`][Client.document_delete] | [Delete Document][docs-delete] | [`DeleteRequest`][DeleteRequest] | [`DeleteResponse`][DeleteResponse] [`document_put_mapping`][Client.document_put_mapping] | [Put Mapping][docs-mapping] | [`IndicesPutMappingRequest`][IndicesPutMappingRequest] | [`CommandResponse`][CommandResponse] [`index_create`][Client.index_create] | [Create Index][docs-create-index] | [`IndicesCreateRequest`][IndicesCreateRequest] | [`CommandResponse`][CommandResponse] [`index_open`][Client.index_open] | [Open Index][docs-open-index] | [`IndicesOpenRequest`][IndicesOpenRequest] | [`CommandResponse`][CommandResponse] [`index_close`][Client.index_close] | [Close Index][docs-close-index] | [`IndicesCloseRequest`][IndicesCloseRequest] | [`CommandResponse`][CommandResponse] [`index_delete`][Client.index_delete] | [Delete Index][docs-delete-index] | [`IndicesDeleteRequest`][IndicesDeleteRequest] | [`CommandResponse`][CommandResponse] [`index_exists`][Client.index_exists] | [Index Exists][docs-index-exists] | [`IndicesExistsRequest`][IndicesExistsRequest] | [`IndicesExistsResponse`][IndicesExistsResponse] [`ping`][Client.ping] | - | [`PingRequest`][PingRequest] | [`PingResponse`][PingResponse] All builders follow a standard pattern: - The `Client` method takes all required parameters without type inference - Optional or inferred parameters can be overridden in builder methods with type inference - `send` will return a specific response type The high-level request builders are wrappers around the [`Client.request`][Client.request] method, taking a [raw request type][endpoints-mod]. For example, a `document_get` request for a value: ```no_run # extern crate serde_json; # extern crate elastic; # use serde_json::Value; # use elastic::prelude::*; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { # let client = SyncClientBuilder::new().build()?; let response = client.document_get::<Value>(index("values"), id(1)).send()?; # Ok(()) # } ``` is equivalent to: ```no_run # extern crate serde_json; # extern crate elastic; # use serde_json::Value; # use elastic::prelude::*; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { # let client = SyncClientBuilder::new().build()?; let response = client.request(GetRequest::for_index_ty_id("values", "value", 1)) .send()? .into_response::<GetResponse<Value>>()?; # Ok(()) # } ``` # Raw request types Not all endpoints have strongly-typed builders, but all Elasticsearch API endpoints have a specific [raw request type][endpoints-mod] that can be used to build a request manually and send with the [`Client.request`][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`][endpoints-mod] 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][endpoints-mod] into a [`RawRequestBuilder`][RawRequestBuilder]: ```text [RequestType] ---> [Client.request()] ---> [RawRequestBuilder] ``` **2)** Send the [`RawRequestBuilder`][RawRequestBuilder] and get a response builder: ```text [RawRequestBuilder.send()] ---> [ResponseBuilder] ``` **3)** Parse the response builder to a [response type][response-types]: ```text [ResponseBuilder.into_response()] ---> [ResponseType] ``` The example below shows how these pieces fit together in code by sending a simple synchronous `SearchRequest`, with the steps in the above process labelled: ```no_run # extern crate elastic; # #[macro_use] # extern crate json_str; # extern crate serde_json; # use elastic::prelude::*; # use serde_json::Value; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { # let client = SyncClientBuilder::new().build()?; let req = SearchRequest::for_index("_all", empty_body()); let response = client.request(req) // 1 .send()? // 2 .into_response::<SearchResponse<Value>>()?; // 3 # Ok(()) # } ``` ### 1. Building raw requests The [`endpoints`][endpoints-mod] 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: ```no_run # #[macro_use] extern crate serde_json; # extern crate elastic; # use elastic::prelude::*; # fn main() { let req = { let body = json!({ "query": { "query_string": { "query": "*" } } }); SearchRequest::for_index_ty("myindex", "myty", body) }; # } ``` A raw request to index a document: ```no_run # extern crate serde_json; # extern crate elastic; # use elastic::prelude::*; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { # let doc = true; let req = { let body = serde_json::to_string(&doc)?; IndexRequest::for_index_ty_id("myindex", "myty", 1, body) }; # Ok(()) # } ``` ### 2. Sending requests Both high-level request builders and raw requests have some common builder methods: - [`params`][RequestBuilder.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 response builder. If the request was sent synchronously, the response is returned as a `Result`. If the request was sent asynchronously, the response is returned as a `Future`. ```no_run # extern crate elastic; # use elastic::prelude::*; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { # let client = SyncClientBuilder::new().build()?; # let req = PingRequest::new(); 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(); # Ok(()) # } ``` ### 3. Parsing responses synchronously Call [`SyncResponseBuilder.into_response`][SyncResponseBuilder.into_response] on a sent request to get a [strongly typed response][response-types]: ```no_run # extern crate serde; # extern crate serde_json; # #[macro_use] extern crate serde_derive; # #[macro_use] extern crate elastic_derive; # extern crate elastic; # use serde_json::Value; # use elastic::prelude::*; # use elastic::Error; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { # #[derive(Serialize, Deserialize, ElasticType)] # struct MyType { # pub id: i32, # pub title: String, # pub timestamp: Date<DefaultDateMapping> # } # let client = SyncClientBuilder::new().build()?; # let req = PingRequest::new(); let response = client.request(req) .send()? .into_response::<SearchResponse<Value>>(); match response { Ok(response) => { // Iterate through the response hits for hit in response.hits() { println!("{:?}", hit); } }, Err(Error::Api(e)) => { // handle a REST API error }, Err(e) => { // handle a HTTP or JSON error } } # Ok(()) # } ``` Alternatively, call [`SyncResponseBuilder.into_raw`][SyncResponseBuilder.into_raw] on a sent request to get a raw [`SyncHttpResponse`][SyncHttpResponse]: ```no_run # extern crate serde; # #[macro_use] extern crate serde_derive; # #[macro_use] extern crate elastic_derive; # extern crate elastic; # use std::io::Read; # use elastic::prelude::*; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { # let client = SyncClientBuilder::new().build()?; # let req = PingRequest::new(); let mut response = client.request(req) .send()? .into_raw(); let mut body = String::new(); response.read_to_string(&mut body)?; println!("{}", body); # Ok(()) # } ``` `SyncHttpResponse` implements the standard `Read` trait so you can buffer out the raw response data. For more details see the [`responses`][responses-mod] module. ### 3. Parsing responses asynchronously Call [`AsyncResponseBuilder.into_response`][AsyncResponseBuilder.into_response] on a sent request to get a [strongly typed response][response-types]: ```no_run # extern crate futures; # extern crate tokio_core; # extern crate serde; # extern crate serde_json; # #[macro_use] extern crate serde_derive; # #[macro_use] extern crate elastic_derive; # extern crate elastic; # use futures::Future; # use serde_json::Value; # use elastic::prelude::*; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { # #[derive(Serialize, Deserialize, ElasticType)] # struct MyType { # pub id: i32, # pub title: String, # pub timestamp: Date<DefaultDateMapping> # } # let core = tokio_core::reactor::Core::new()?; # let client = AsyncClientBuilder::new().build(&core.handle())?; # let req = PingRequest::new(); let future = client.request(req) .send() .and_then(|response| response.into_response::<SearchResponse<Value>>()); future.and_then(|response| { // Iterate through the response hits for hit in response.hits() { println!("{:?}", hit); } Ok(()) }); # Ok(()) # } ``` Alternatively, call [`AsyncResponseBuilder.into_raw`][AsyncResponseBuilder.into_raw] on a sent request to get a raw [`AsyncHttpResponse`][AsyncHttpResponse]: ```no_run # extern crate futures; # extern crate tokio_core; # extern crate serde; # #[macro_use] extern crate serde_derive; # #[macro_use] extern crate elastic_derive; # extern crate elastic; # use std::str; # use std::io::Read; # use futures::{Future, Stream}; # use elastic::prelude::*; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { # let core = tokio_core::reactor::Core::new()?; # let client = AsyncClientBuilder::new().build(&core.handle())?; # let req = PingRequest::new(); let future = client.request(req) .send() .and_then(|response| Ok(response.into_raw())) .and_then(|raw| raw.concat2()) .map_err(|e| Box::new(e) as Box<::std::error::Error>); future.and_then(|body| { let body = str::from_utf8(body.as_ref())?; println!("{}", body); Ok(()) }); # Ok(()) # } ``` `AsyncHttpResponse` implements the async `Stream` trait so you can buffer out the raw response data. For more details see the [`responses`][responses-mod] module. [docs-search]: http://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html [docs-get]: http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html [docs-update]: http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html [docs-delete]: http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html [docs-index]: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html [docs-mapping]: https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping.html [docs-create-index]: https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html [docs-close-index]: https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-open-close.html [docs-open-index]: https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-open-close.html [docs-index-exists]: https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-exists.html [docs-delete-index]: https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-delete-index.html [tokio]: https://tokio.rs [endpoints-mod]: requests/endpoints/index.html [RequestParams]: struct.RequestParams.html [SyncClient]: type.SyncClient.html [SyncClientBuilder]: struct.SyncClientBuilder.html [AsyncClient]: type.AsyncClient.html [AsyncClientBuilder]: struct.AsyncClientBuilder.html [Client.request]: struct.Client.html#method.request [Client.search]: struct.Client.html#search-request [Client.document_get]: struct.Client.html#get-document-request [Client.document_update]: struct.Client.html#update-document-request [Client.document_delete]: struct.Client.html#delete-document-request [Client.document_index]: struct.Client.html#index-document-request [Client.document_put_mapping]: struct.Client.html#method.document_put_mapping [Client.index_create]: struct.Client.html#create-index-request [Client.index_open]: struct.Client.html#open-index-request [Client.index_close]: struct.Client.html#close-index-request [Client.index_delete]: struct.Client.html#delete-index-request [Client.index_exists]: struct.Client.html#index-exists-request [Client.ping]: struct.Client.html#ping-request [RequestBuilder]: requests/struct.RequestBuilder.html [RequestBuilder.params]: requests/struct.RequestBuilder.html#method.params [RawRequestBuilder]: requests/type.RawRequestBuilder.html [SearchRequest]: requests/endpoints/struct.SearchRequest.html [GetRequest]: requests/endpoints/struct.GetRequest.html [UpdateRequest]: requests/endpoints/struct.UpdateRequest.html [DeleteRequest]: requests/endpoints/struct.DeleteRequest.html [IndexRequest]: requests/endpoints/struct.IndexRequest.html [IndicesPutMappingRequest]: requests/endpoints/struct.IndicesPutMappingRequest.html [IndicesCreateRequest]: requests/endpoints/struct.IndicesCreateRequest.html [IndicesOpenRequest]: requests/endpoints/struct.IndicesOpenRequest.html [IndicesCloseRequest]: requests/endpoints/struct.IndicesCloseRequest.html [IndicesDeleteRequest]: requests/endpoints/struct.IndicesDeleteRequest.html [IndicesExistsRequest]: requests/endpoints/struct.IndicesExistsRequest.html [PingRequest]: requests/endpoints/struct.PingRequest.html [responses-mod]: responses/index.html [SyncResponseBuilder]: responses/struct.SyncResponseBuilder.html [SyncResponseBuilder.into_response]: responses/struct.SyncResponseBuilder.html#method.into_response [SyncResponseBuilder.into_raw]: responses/struct.SyncResponseBuilder.html#method.into_raw [AsyncResponseBuilder]: responses/struct.AsyncResponseBuilder.html [AsyncResponseBuilder.into_response]: responses/struct.AsyncResponseBuilder.html#method.into_response [AsyncResponseBuilder.into_raw]: responses/struct.AsyncResponseBuilder.html#method.into_raw [SearchResponse]: responses/type.SearchResponse.html [GetResponse]: responses/type.GetResponse.html [UpdateResponse]: responses/type.UpdateResponse.html [DeleteResponse]: responses/type.DeleteResponse.html [IndexResponse]: responses/struct.IndexResponse.html [IndicesExistsResponse]: responses/struct.IndicesExistsResponse.html [PingResponse]: responses/struct.PingResponse.html [CommandResponse]: responses/struct.CommandResponse.html [SyncHttpResponse]: responses/struct.SyncHttpResponse.html [AsyncHttpResponse]: responses/struct.AsyncHttpResponse.html [response-types]: responses/parse/trait.IsOk.html#implementors */ pub mod requests; pub mod responses; use self::requests::HttpRequest; mod sync; mod async; pub use self::sync::*; pub use self::async::*; pub use elastic_reqwest::RequestParams; mod private { pub trait Sealed {} } /** Represents a type that can send a request. You probably don't need to touch this trait directly. See the [`Client`][Client] type for making requests. [Client]: struct.Client.html */ pub trait Sender: private::Sealed + Clone { /// The kind of request body this sender accepts. type Body; /// The kind of response this sender produces. type Response; /// Send a request. fn send<TRequest, TBody>(&self, req: TRequest, params: &RequestParams) -> Self::Response where TRequest: Into<HttpRequest<'static, TBody>>, TBody: Into<Self::Body>; } /** A HTTP client for the Elasticsearch REST API. The `Client` is a structure that lets you create and send request builders. `Client` is generic over a `Sender`, but rather than use `Client` directly, use one of: - [`SyncClient`][SyncClient] - [`AsyncClient`][AsyncClient] # Examples Create a synchronous `Client` and send a ping request: ```no_run # extern crate elastic; # use elastic::prelude::*; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { let client = SyncClientBuilder::new().build()?; let response = client.request(PingRequest::new()) .send()? .into_response::<PingResponse>()?; # Ok(()) # } ``` Create an asynchronous `Client` and send a ping request: ```no_run # extern crate futures; # extern crate tokio_core; # extern crate elastic; # use futures::Future; # use tokio_core::reactor::Core; # use elastic::prelude::*; # fn main() { run().unwrap() } # fn run() -> Result<(), Box<::std::error::Error>> { let mut core = Core::new()?; let client = AsyncClientBuilder::new().build(&core.handle())?; let response_future = client.request(PingRequest::new()) .send() .and_then(|res| res.into_response::<PingResponse>()); core.run(response_future)?; # Ok(()) # } ``` [SyncClient]: type.SyncClient.html [AsyncClient]: type.AsyncClient.html */ #[derive(Clone)] pub struct Client<TSender> { sender: TSender, params: RequestParams, } pub mod prelude { /*! A glob import for convenience. */ pub use super::{AsyncClient, AsyncClientBuilder, RequestParams, SyncClient, SyncClientBuilder}; pub use super::requests::prelude::*; pub use super::responses::prelude::*; } #[cfg(test)] mod tests { use super::*; use tests::*; #[test] fn client_is_send_sync() { assert_send::<SyncClient>(); assert_sync::<SyncClient>(); } }