opensearch_client/
lib.rs

1pub extern crate url;
2
3mod client;
4mod credentials;
5mod auth_middleware;
6pub mod bulker;
7
8#[cfg(feature = "cat")]
9mod cat;
10#[cfg(feature = "cluster")]
11mod cluster;
12#[cfg(feature = "indices")]
13pub mod indices;
14#[cfg(feature = "ingest")]
15mod ingest;
16#[cfg(feature = "nodes")]
17mod nodes;
18#[cfg(feature = "ml")]
19mod ml;
20#[cfg(feature = "mtermvectors")]
21mod mtermvectors;
22#[cfg(feature = "remote")]
23mod remote;
24#[cfg(feature = "security")]
25mod security;
26#[cfg(feature = "snapshot")]
27mod snapshot;
28#[cfg(feature = "tasks")]
29mod tasks;
30#[cfg(feature = "tools")]
31mod tools;
32
33use std::sync::{Arc, Mutex};
34
35use bulker::{Bulker, BulkerBuilder};
36#[cfg(feature = "search")]
37pub use opensearch_dsl as dsl;
38#[cfg(feature = "search")]
39use opensearch_dsl::{Query, Search, SortCollection, Terms};
40#[cfg(feature = "search")]
41mod builder_search;
42
43#[allow(unused_imports)]
44use client::{encode_path, encode_path_option_vec_string, RequestBuilderExt};
45pub use client::{ByteStream, Error, ResponseValue};
46#[allow(unused_imports)]
47use reqwest::header::{HeaderMap, HeaderValue};
48use serde::{de::DeserializeOwned, Serialize};
49use tokio::task::JoinHandle;
50use tracing::info;
51use types::bulk::{BulkAction, BulkResponse, CreateAction, IndexAction, UpdateAction, UpdateActionBody};
52use futures::{
53  stream::{self, StreamExt},
54  Stream,
55};
56pub mod types;
57pub mod builder;
58
59#[cfg(not(target_arch = "wasm32"))]
60use std::path::{Path, PathBuf};
61use std::collections::HashMap;
62
63#[cfg(not(target_arch = "wasm32"))]
64use http_cache_reqwest::{CACacheManager, Cache, CacheMode, HttpCache, HttpCacheOptions};
65#[cfg(target_arch = "wasm32")]
66use reqwest::Client;
67#[cfg(not(target_arch = "wasm32"))]
68use reqwest::ClientBuilder;
69#[cfg(not(target_arch = "wasm32"))]
70use reqwest::{NoProxy, Proxy};
71use reqwest_middleware::ClientWithMiddleware;
72use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
73use url::Url;
74use client::ReqwestResponse;
75
76#[cfg(not(target_arch = "wasm32"))]
77use crate::{auth_middleware::AuthMiddleware, credentials::Credentials};
78
79#[derive(Clone, Debug)]
80pub struct OsClientBuilder {
81  baseurl: Url,
82  retries: u32,
83  credentials: HashMap<String, Credentials>,
84  accept_invalid_certificates: bool,
85  max_bulk_size: u32,
86  #[cfg(not(target_arch = "wasm32"))]
87  cache: Option<PathBuf>,
88  #[cfg(not(target_arch = "wasm32"))]
89  proxy: bool,
90  #[cfg(not(target_arch = "wasm32"))]
91  proxy_url: Option<Proxy>,
92  #[cfg(not(target_arch = "wasm32"))]
93  no_proxy_domain: Option<String>,
94}
95
96impl Default for OsClientBuilder {
97  fn default() -> Self {
98    Self {
99      baseurl: Url::parse("http://localhost:9200").unwrap(),
100      credentials: HashMap::new(),
101      accept_invalid_certificates: false,
102      max_bulk_size: 200,
103      #[cfg(not(target_arch = "wasm32"))]
104      cache: None,
105      #[cfg(not(target_arch = "wasm32"))]
106      proxy: false,
107      #[cfg(not(target_arch = "wasm32"))]
108      proxy_url: None,
109      #[cfg(not(target_arch = "wasm32"))]
110      no_proxy_domain: None,
111      #[cfg(not(test))]
112      retries: 2,
113      #[cfg(test)]
114      retries: 0,
115    }
116  }
117}
118
119impl OsClientBuilder {
120  pub fn new() -> Self {
121    Default::default()
122  }
123
124  pub fn base_url(mut self, baseurl: Url) -> Self {
125    self.baseurl = baseurl;
126    self
127  }
128
129  pub fn accept_invalid_certificates(mut self, accept_invalid_certificates: bool) -> Self {
130    self.accept_invalid_certificates = accept_invalid_certificates;
131    self
132  }
133
134  pub fn max_bulk_size(mut self, max_bulk_size: u32) -> Self {
135    self.max_bulk_size = max_bulk_size;
136    self
137  }
138
139  pub fn basic_auth(mut self, username: impl Into<String>, password: impl Into<String>) -> Self {
140    self.credentials.insert(
141      auth_middleware::nerf_dart(&self.baseurl),
142      Credentials::Basic {
143        username: username.into(),
144        password: Some(password.into()),
145      },
146    );
147    self
148  }
149
150  pub fn token_auth(mut self, token: impl Into<String>) -> Self {
151    self.credentials.insert(
152      auth_middleware::nerf_dart(&self.baseurl),
153      Credentials::Token(token.into()),
154    );
155    self
156  }
157
158  pub fn legacy_auth(mut self, legacy_auth_token: impl Into<String>) -> Self {
159    self.credentials.insert(
160      auth_middleware::nerf_dart(&self.baseurl),
161      Credentials::EncodedBasic(legacy_auth_token.into()),
162    );
163    self
164  }
165
166  pub fn retries(mut self, retries: u32) -> Self {
167    self.retries = retries;
168    self
169  }
170
171  #[cfg(not(target_arch = "wasm32"))]
172  pub fn cache(mut self, cache: impl AsRef<Path>) -> Self {
173    self.cache = Some(PathBuf::from(cache.as_ref()));
174    self
175  }
176
177  #[cfg(not(target_arch = "wasm32"))]
178  pub fn proxy(mut self, proxy: bool) -> Self {
179    self.proxy = proxy;
180    self
181  }
182
183  #[cfg(not(target_arch = "wasm32"))]
184  pub fn proxy_url(mut self, proxy_url: impl AsRef<str>) -> Result<Self, Error> {
185    match Url::parse(proxy_url.as_ref()) {
186      Ok(url_info) => {
187        let username = url_info.username();
188        let password = url_info.password();
189        let mut proxy = Proxy::all(url_info.as_ref())?;
190
191        if let Some(password_str) = password {
192          proxy = proxy.basic_auth(username, password_str);
193        }
194
195        proxy = proxy.no_proxy(self.get_no_proxy_domain());
196        self.proxy_url = Some(proxy);
197        self.proxy = true;
198        Ok(self)
199      }
200      Err(e) => Err(Error::UrlParseError(e)),
201    }
202  }
203
204  #[cfg(not(target_arch = "wasm32"))]
205  pub fn no_proxy_domain(mut self, no_proxy_domain: impl AsRef<str>) -> Self {
206    self.no_proxy_domain = Some(no_proxy_domain.as_ref().into());
207    self
208  }
209
210  pub fn build(self) -> OsClient {
211    #[cfg(target_arch = "wasm32")]
212    let client_raw = {
213      let mut client_core = ClientBuilder::new();
214      if self.accept_invalid_certificates {
215        let mut builder = client_raw.clone().builder();
216        builder = builder.danger_accept_invalid_certs(true);
217        builder = builder.danger_accept_invalid_hostnames(true);
218        client_raw = builder.build().unwrap();
219      }
220      client_core.build().expect("Fail to build HTTP client.")
221    };
222
223    #[cfg(not(target_arch = "wasm32"))]
224    let client_raw = {
225      let mut client_core = ClientBuilder::new()
226        .user_agent("opensearch-client/0.1.0")
227        .pool_max_idle_per_host(20)
228        .timeout(std::time::Duration::from_secs(60 * 5));
229
230      if let Some(url) = self.proxy_url {
231        client_core = client_core.proxy(url);
232      }
233
234      if !self.proxy {
235        client_core = client_core.no_proxy();
236      }
237      if self.accept_invalid_certificates {
238        client_core = client_core.danger_accept_invalid_certs(true);
239        client_core = client_core.danger_accept_invalid_hostnames(true);
240      }
241
242      client_core.build().expect("Fail to build HTTP client.")
243    };
244
245    let retry_policy = ExponentialBackoff::builder().build_with_max_retries(self.retries);
246    let retry_strategy = RetryTransientMiddleware::new_with_policy(retry_policy);
247    let credentials = Arc::new(self.credentials);
248
249    #[allow(unused_mut)]
250    let mut client_builder = reqwest_middleware::ClientBuilder::new(client_raw.clone())
251      .with(retry_strategy)
252      .with(AuthMiddleware(credentials.clone()));
253
254    #[cfg(not(target_arch = "wasm32"))]
255    if let Some(cache_loc) = self.cache {
256      client_builder = client_builder.with(Cache(HttpCache {
257        mode: CacheMode::Default,
258        manager: CACacheManager { path: cache_loc },
259        options: HttpCacheOptions::default(),
260      }));
261    }
262
263    let retry_policy = ExponentialBackoff::builder().build_with_max_retries(self.retries);
264    let retry_strategy = RetryTransientMiddleware::new_with_policy(retry_policy);
265
266    let client_uncached_builder = reqwest_middleware::ClientBuilder::new(client_raw)
267      .with(retry_strategy)
268      .with(AuthMiddleware(credentials));
269
270    OsClient {
271      baseurl: Arc::new(self.baseurl),
272      client: client_builder.build(),
273      client_uncached: client_uncached_builder.build(),
274      bulker: Arc::new(Mutex::new(String::new())),
275      bulker_size: Arc::new(Mutex::new(0)),
276      max_bulk_size: self.max_bulk_size,
277    }
278  }
279
280  #[cfg(not(target_arch = "wasm32"))]
281  fn get_no_proxy_domain(&self) -> Option<NoProxy> {
282    if let Some(ref no_proxy_conf) = self.no_proxy_domain {
283      if !no_proxy_conf.is_empty() {
284        return NoProxy::from_string(no_proxy_conf);
285      }
286    }
287
288    NoProxy::from_env().or(None)
289  }
290}
291
292#[derive(Clone, Debug)]
293///Client for OpenSearch
294///
295///Version: 2021-11-23
296pub struct OsClient {
297  pub(crate) baseurl: Arc<Url>,
298  pub(crate) client: ClientWithMiddleware,
299  pub(crate) client_uncached: ClientWithMiddleware,
300  pub(crate) bulker: Arc<Mutex<String>>,
301  pub(crate) bulker_size: Arc<Mutex<u32>>,
302  pub(crate) max_bulk_size: u32,
303}
304
305pub trait Request {
306  type Response: DeserializeOwned + Send + Sync;
307  fn method(&self) -> reqwest::Method;
308  fn path(&self) -> Result<String, Error>;
309  fn body(&self) -> Result<Option<String>, Error>;
310  fn query_args(&self) -> Result<Option<HashMap<String, String>>, Error>;
311  fn url(&self, base_url: &Url) -> Result<Url, Error> {
312    let mut url = base_url.clone();
313    url.set_path(&self.path()?);
314    if let Some(query_args) = self.query_args()? {
315      url.query_pairs_mut().clear().extend_pairs(query_args.iter());
316    }
317    Ok(url)
318  }
319}
320
321impl OsClient {
322  /// Create a new client.
323  ///
324  /// `baseurl` is the base URL provided to the internal
325  /// `reqwest::Client`, and should include a scheme and hostname,
326  /// as well as port and a path stem if applicable.
327  pub fn new(baseurl: Url) -> Self {
328    let builder = OsClientBuilder::new().base_url(baseurl);
329    builder.build()
330  }
331
332  pub fn from_environment() -> Result<OsClient, Error> {
333    let accept_invalid_certificates: bool = match std::env::var("OPENSEARCH_SSL_VERIFY") {
334      Ok(value) => value.eq_ignore_ascii_case("false"),
335      Err(_) => false,
336    };
337    let user: String = match std::env::var("OPENSEARCH_USER") {
338      Ok(user) => user,
339      Err(_) => "admin".into(),
340    };
341    let password: String = match std::env::var("OPENSEARCH_PASSWORD") {
342      Ok(password) => password,
343      Err(_) => "admin".into(),
344    };
345
346    let server = match std::env::var("OPENSEARCH_URL") {
347      Ok(server) => server,
348      Err(_) => "https://localhost:9200".into(),
349    };
350
351    let mut builder = OsClientBuilder::new().base_url(Url::parse(&server)?);
352    if accept_invalid_certificates {
353      builder = builder.accept_invalid_certificates(true);
354    }
355    builder = builder.basic_auth(user, password);
356
357    if let Ok(max_bulk_size) = std::env::var("OPENSEARCH_MAX_BULK_SIZE") {
358      match max_bulk_size.parse::<u32>() {
359        Ok(max_bulk_size) => builder = builder.max_bulk_size(max_bulk_size),
360        Err(_) => info!("Invalid value for OPENSEARCH_MAX_BULK_SIZE, using default"),
361      }
362    };
363
364    Ok(builder.build())
365  }
366
367  #[cfg(feature = "quickwit")]
368  pub fn from_quickwit_environment() -> Result<OsClient, Error> {
369    let accept_invalid_certificates: bool = match std::env::var("QUICKWIT_SSL_VERIFY") {
370      Ok(value) => value.eq_ignore_ascii_case("false"),
371      Err(_) => false,
372    };
373
374    let mut server = match std::env::var("QUICKWIT_URL") {
375      Ok(server) => server,
376      Err(_) => "http://localhost:7280".into(),
377    };
378    // api/v1/_elastic
379    if !server.ends_with("/api/v1/_elastic") {
380      server.push_str("/api/v1/_elastic");
381    }
382
383    let mut builder = OsClientBuilder::new().base_url(Url::parse(&server)?);
384    if accept_invalid_certificates {
385      builder = builder.accept_invalid_certificates(true);
386    }
387
388    if let Ok(max_bulk_size) = std::env::var("QUICKWIT_MAX_BULK_SIZE") {
389      match max_bulk_size.parse::<u32>() {
390        Ok(max_bulk_size) => builder = builder.max_bulk_size(max_bulk_size),
391        Err(_) => info!("Invalid value for QUICKWIT_MAX_BULK_SIZE, using default"),
392      }
393    };
394
395    Ok(builder.build())
396  }
397
398  #[cfg(feature = "cat")]
399  pub fn cat(&self) -> cat::Cat {
400    cat::Cat::new(&self)
401  }
402
403  #[cfg(feature = "cluster")]
404  pub fn cluster(&self) -> cluster::Cluster {
405    cluster::Cluster::new(&self)
406  }
407
408  #[cfg(feature = "indices")]
409  pub fn indices(&self) -> indices::Indices {
410    indices::Indices::new(&self)
411  }
412
413  #[cfg(feature = "ingest")]
414  pub fn ingest(&self) -> ingest::Ingest {
415    ingest::Ingest::new(&self)
416  }
417
418  #[cfg(feature = "mtermvectors")]
419  pub fn mtermvectors(&self) -> mtermvectors::Mtermvectors {
420    mtermvectors::Mtermvectors::new(&self)
421  }
422
423  #[cfg(feature = "ml")]
424  pub fn ml(&self) -> ml::ML {
425    ml::ML::new(&self)
426  }
427
428  #[cfg(feature = "nodes")]
429  pub fn nodes(&self) -> nodes::Nodes {
430    nodes::Nodes::new(&self)
431  }
432
433  #[cfg(feature = "remote")]
434  pub fn remote(&self) -> remote::Remote {
435    remote::Remote::new(&self)
436  }
437
438  #[cfg(feature = "security")]
439  pub fn security(&self) -> security::Security {
440    security::Security::new(&self)
441  }
442
443  #[cfg(feature = "snapshot")]
444  pub fn snapshot(&self) -> snapshot::Snapshot {
445    snapshot::Snapshot::new(&self)
446  }
447
448  #[cfg(feature = "tasks")]
449  pub fn tasks(&self) -> tasks::Tasks {
450    tasks::Tasks::new(&self)
451  }
452
453  #[cfg(feature = "tools")]
454  pub fn tools(&self) -> tools::Tools {
455    tools::Tools::new(&self)
456  }
457
458  /// Get the base URL to which requests are made.
459  pub fn baseurl(&self) -> &Url {
460    &self.baseurl
461  }
462
463  /// Get the internal `reqwest_middleware::ClientWithMiddleware` used to make
464  /// requests.
465  pub fn client(&self) -> &reqwest_middleware::ClientWithMiddleware {
466    &self.client
467  }
468
469  /// Get the version of this API.
470  ///
471  /// This string is pulled directly from the source OpenAPI
472  /// document and may be in any format the API selects.
473  pub fn api_version(&self) -> &'static str {
474    "2021-11-23"
475  }
476
477  pub async fn send<T: Request + Serialize>(&self, request: T) -> Result<ResponseValue<T::Response>, Error> {
478    let body = request.body()?;
479    let url = request.url(self.baseurl.clone().as_ref())?;
480    let mut request_builder = self.client.request(request.method(), url);
481    if let Some(body) = body {
482      request_builder = request_builder.body(body);
483    }
484    let response = request_builder.send().await?;
485    match response.status().as_u16() {
486      200u16 => ResponseValue::from_response(response).await,
487      _ => {
488        Err(Error::UnexpectedResponse(
489          ReqwestResponse::from_response(response).await,
490        ))
491      }
492    }
493  }
494}
495
496impl OsClient {
497  ///Returns basic information about the cluster.
498  ///
499  ///Sends a `GET` request to `/`
500  ///
501  ///```ignore
502  /// let response = client.info()
503  ///    .send()
504  ///    .await;
505  /// ```
506  pub fn info(&self) -> builder::Info {
507    builder::Info::new(self)
508  }
509
510  ///Returns whether the cluster is running.
511  ///
512  ///Sends a `HEAD` request to `/`
513  ///
514  ///```ignore
515  /// let response = client.ping()
516  ///    .send()
517  ///    .await;
518  /// ```
519  pub fn ping(&self) -> builder::Ping {
520    builder::Ping::new(self)
521  }
522
523  ///Allows to perform multiple index/update/delete operations in a single
524  /// request.
525  ///
526  ///Sends a `POST` request to `/_bulk`
527  ///
528  ///Arguments:
529  /// - `source`: True or false to return the _source field or not, or default
530  ///   list of fields to return, can be overridden on each sub-request.
531  /// - `source_excludes`: Default list of fields to exclude from the returned
532  ///   _source field, can be overridden on each sub-request.
533  /// - `source_includes`: Default list of fields to extract and return from the
534  ///   _source field, can be overridden on each sub-request.
535  /// - `pipeline`: The pipeline id to preprocess incoming documents with.
536  /// - `refresh`: If `true` then refresh the affected shards to make this
537  ///   operation visible to search, if `wait_for` then wait for a refresh to
538  ///   make this operation visible to search, if `false` (the default) then do
539  ///   nothing with refreshes.
540  /// - `require_alias`: Sets require_alias for all incoming documents.
541  /// - `routing`: Routing value.
542  /// - `timeout`: Operation timeout.
543  /// - `type_`: Default document type for items which don't provide one.
544  /// - `wait_for_active_shards`: Sets the number of shard copies that must be
545  ///   active before proceeding with the operation. Defaults to 1, meaning the
546  ///   primary shard only. Set to `all` for all shard copies, otherwise set to
547  ///   any non-negative value less than or equal to the total number of copies
548  ///   for the shard (number of replicas + 1).
549  /// - `body`
550  ///```ignore
551  /// let response = client.bulk_post()
552  ///    .source(source)
553  ///    .source_excludes(source_excludes)
554  ///    .source_includes(source_includes)
555  ///    .pipeline(pipeline)
556  ///    .refresh(refresh)
557  ///    .require_alias(require_alias)
558  ///    .routing(routing)
559  ///    .timeout(timeout)
560  ///    .type_(type_)
561  ///    .wait_for_active_shards(wait_for_active_shards)
562  ///    .body(body)
563  ///    .send()
564  ///    .await;
565  /// ```
566  pub fn bulk(&self) -> builder::BulkPost {
567    builder::BulkPost::new(self)
568  }
569
570  ///Returns all dangling indices.
571  ///
572  ///Sends a `GET` request to `/_dangling`
573  ///
574  ///```ignore
575  /// let response = client.dangling_indices_list_dangling_indices()
576  ///    .send()
577  ///    .await;
578  /// ```
579  pub fn dangling_indices_list_dangling_indices(&self) -> builder::DanglingIndicesListDanglingIndices {
580    builder::DanglingIndicesListDanglingIndices::new(self)
581  }
582
583  ///Imports the specified dangling index.
584  ///
585  ///Sends a `POST` request to `/_dangling/{index_uuid}`
586  ///
587  ///Arguments:
588  /// - `index_uuid`: The UUID of the dangling index.
589  /// - `accept_data_loss`: Must be set to true in order to import the dangling
590  ///   index.
591  /// - `cluster_manager_timeout`: Operation timeout for connection to
592  ///   cluster-manager node.
593  /// - `master_timeout`: Operation timeout for connection to master node.
594  /// - `timeout`: Operation timeout.
595  ///```ignore
596  /// let response = client.dangling_indices_import_dangling_index()
597  ///    .index_uuid(index_uuid)
598  ///    .accept_data_loss(accept_data_loss)
599  ///    .cluster_manager_timeout(cluster_manager_timeout)
600  ///    .master_timeout(master_timeout)
601  ///    .timeout(timeout)
602  ///    .send()
603  ///    .await;
604  /// ```
605  pub fn dangling_indices_import_dangling_index(&self) -> builder::DanglingIndicesImportDanglingIndex {
606    builder::DanglingIndicesImportDanglingIndex::new(self)
607  }
608
609  ///Deletes the specified dangling index.
610  ///
611  ///Sends a `DELETE` request to `/_dangling/{index_uuid}`
612  ///
613  ///Arguments:
614  /// - `index_uuid`: The UUID of the dangling index.
615  /// - `accept_data_loss`: Must be set to true in order to delete the dangling
616  ///   index.
617  /// - `cluster_manager_timeout`: Operation timeout for connection to
618  ///   cluster-manager node.
619  /// - `master_timeout`: Operation timeout for connection to master node.
620  /// - `timeout`: Operation timeout.
621  ///```ignore
622  /// let response = client.dangling_indices_delete_dangling_index()
623  ///    .index_uuid(index_uuid)
624  ///    .accept_data_loss(accept_data_loss)
625  ///    .cluster_manager_timeout(cluster_manager_timeout)
626  ///    .master_timeout(master_timeout)
627  ///    .timeout(timeout)
628  ///    .send()
629  ///    .await;
630  /// ```
631  pub fn dangling_indices_delete_dangling_index(&self) -> builder::DanglingIndicesDeleteDanglingIndex {
632    builder::DanglingIndicesDeleteDanglingIndex::new(self)
633  }
634
635  ///Changes the number of requests per second for a particular Delete By
636  /// Query operation.
637  ///
638  ///Sends a `POST` request to `/_delete_by_query/{task_id}/_rethrottle`
639  ///
640  ///Arguments:
641  /// - `task_id`: The task id to rethrottle.
642  /// - `requests_per_second`: The throttle for this request in sub-requests per
643  ///   second. -1 means no throttle.
644  ///```ignore
645  /// let response = client.delete_by_query_rethrottle()
646  ///    .task_id(task_id)
647  ///    .requests_per_second(requests_per_second)
648  ///    .send()
649  ///    .await;
650  /// ```
651  pub fn delete_by_query_rethrottle(&self) -> builder::DeleteByQueryRethrottle {
652    builder::DeleteByQueryRethrottle::new(self)
653  }
654
655  ///Returns the information about the capabilities of fields among multiple
656  /// indices.
657  ///
658  ///Sends a `GET` request to `/_field_caps`
659  ///
660  ///Arguments:
661  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
662  ///   resolves into no concrete indices. (This includes `_all` string or when
663  ///   no indices have been specified).
664  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
665  ///   indices that are open, closed or both.
666  /// - `fields`: Comma-separated list of field names.
667  /// - `ignore_unavailable`: Whether specified concrete indices should be
668  ///   ignored when unavailable (missing or closed).
669  /// - `include_unmapped`: Indicates whether unmapped fields should be included
670  ///   in the response.
671  ///```ignore
672  /// let response = client.field_caps_get()
673  ///    .allow_no_indices(allow_no_indices)
674  ///    .expand_wildcards(expand_wildcards)
675  ///    .fields(fields)
676  ///    .ignore_unavailable(ignore_unavailable)
677  ///    .include_unmapped(include_unmapped)
678  ///    .send()
679  ///    .await;
680  /// ```
681  pub fn field_caps_get(&self) -> builder::FieldCapsGet {
682    builder::FieldCapsGet::new(self)
683  }
684
685  ///Returns the information about the capabilities of fields among multiple
686  /// indices.
687  ///
688  ///Sends a `POST` request to `/_field_caps`
689  ///
690  ///Arguments:
691  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
692  ///   resolves into no concrete indices. (This includes `_all` string or when
693  ///   no indices have been specified).
694  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
695  ///   indices that are open, closed or both.
696  /// - `fields`: Comma-separated list of field names.
697  /// - `ignore_unavailable`: Whether specified concrete indices should be
698  ///   ignored when unavailable (missing or closed).
699  /// - `include_unmapped`: Indicates whether unmapped fields should be included
700  ///   in the response.
701  /// - `body`
702  ///```ignore
703  /// let response = client.field_caps_post()
704  ///    .allow_no_indices(allow_no_indices)
705  ///    .expand_wildcards(expand_wildcards)
706  ///    .fields(fields)
707  ///    .ignore_unavailable(ignore_unavailable)
708  ///    .include_unmapped(include_unmapped)
709  ///    .body(body)
710  ///    .send()
711  ///    .await;
712  /// ```
713  pub fn field_caps_post(&self) -> builder::FieldCapsPost {
714    builder::FieldCapsPost::new(self)
715  }
716
717  ///Allows to get multiple documents in one request.
718  ///
719  ///Sends a `GET` request to `/_mget`
720  ///
721  ///Arguments:
722  /// - `source`: True or false to return the _source field or not, or a list of
723  ///   fields to return.
724  /// - `source_excludes`: List of fields to exclude from the returned _source
725  ///   field.
726  /// - `source_includes`: List of fields to extract and return from the _source
727  ///   field.
728  /// - `preference`: Specify the node or shard the operation should be
729  ///   performed on.
730  /// - `realtime`: Specify whether to perform the operation in realtime or
731  ///   search mode.
732  /// - `refresh`: Refresh the shard containing the document before performing
733  ///   the operation.
734  /// - `routing`: Routing value.
735  /// - `stored_fields`: Comma-separated list of stored fields to return.
736  ///```ignore
737  /// let response = client.mget_get()
738  ///    .source(source)
739  ///    .source_excludes(source_excludes)
740  ///    .source_includes(source_includes)
741  ///    .preference(preference)
742  ///    .realtime(realtime)
743  ///    .refresh(refresh)
744  ///    .routing(routing)
745  ///    .stored_fields(stored_fields)
746  ///    .send()
747  ///    .await;
748  /// ```
749  pub fn mget_get(&self) -> builder::MgetGet {
750    builder::MgetGet::new(self)
751  }
752
753  ///Allows to get multiple documents in one request.
754  ///
755  ///Sends a `POST` request to `/_mget`
756  ///
757  ///Arguments:
758  /// - `source`: True or false to return the _source field or not, or a list of
759  ///   fields to return.
760  /// - `source_excludes`: List of fields to exclude from the returned _source
761  ///   field.
762  /// - `source_includes`: List of fields to extract and return from the _source
763  ///   field.
764  /// - `preference`: Specify the node or shard the operation should be
765  ///   performed on.
766  /// - `realtime`: Specify whether to perform the operation in realtime or
767  ///   search mode.
768  /// - `refresh`: Refresh the shard containing the document before performing
769  ///   the operation.
770  /// - `routing`: Routing value.
771  /// - `stored_fields`: Comma-separated list of stored fields to return.
772  /// - `body`
773  ///```ignore
774  /// let response = client.mget_post()
775  ///    .source(source)
776  ///    .source_excludes(source_excludes)
777  ///    .source_includes(source_includes)
778  ///    .preference(preference)
779  ///    .realtime(realtime)
780  ///    .refresh(refresh)
781  ///    .routing(routing)
782  ///    .stored_fields(stored_fields)
783  ///    .body(body)
784  ///    .send()
785  ///    .await;
786  /// ```
787  pub fn mget_post(&self) -> builder::MgetPost {
788    builder::MgetPost::new(self)
789  }
790
791  ///Allows to execute several search operations in one request.
792  ///
793  ///Sends a `GET` request to `/_msearch`
794  ///
795  ///Arguments:
796  /// - `ccs_minimize_roundtrips`: Indicates whether network round-trips should
797  ///   be minimized as part of cross-cluster search requests execution.
798  /// - `max_concurrent_searches`: Controls the maximum number of concurrent
799  ///   searches the multi search api will execute.
800  /// - `max_concurrent_shard_requests`: The number of concurrent shard requests
801  ///   each sub search executes concurrently per node. This value should be
802  ///   used to limit the impact of the search on the cluster in order to limit
803  ///   the number of concurrent shard requests.
804  /// - `pre_filter_shard_size`: Threshold that enforces a pre-filter round-trip
805  ///   to prefilter search shards based on query rewriting if the number of
806  ///   shards the search request expands to exceeds the threshold. This filter
807  ///   round-trip can limit the number of shards significantly if for instance
808  ///   a shard can not match any documents based on its rewrite method ie. if
809  ///   date filters are mandatory to match but the shard bounds and the query
810  ///   are disjoint.
811  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
812  ///   rendered as an integer or an object in the rest search response.
813  /// - `search_type`: Search operation type.
814  /// - `typed_keys`: Specify whether aggregation and suggester names should be
815  ///   prefixed by their respective types in the response.
816  ///```ignore
817  /// let response = client.msearch_get()
818  ///    .ccs_minimize_roundtrips(ccs_minimize_roundtrips)
819  ///    .max_concurrent_searches(max_concurrent_searches)
820  ///    .max_concurrent_shard_requests(max_concurrent_shard_requests)
821  ///    .pre_filter_shard_size(pre_filter_shard_size)
822  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
823  ///    .search_type(search_type)
824  ///    .typed_keys(typed_keys)
825  ///    .send()
826  ///    .await;
827  /// ```
828  pub fn msearch_get(&self) -> builder::MsearchGet {
829    builder::MsearchGet::new(self)
830  }
831
832  ///Allows to execute several search operations in one request.
833  ///
834  ///Sends a `POST` request to `/_msearch`
835  ///
836  ///Arguments:
837  /// - `ccs_minimize_roundtrips`: Indicates whether network round-trips should
838  ///   be minimized as part of cross-cluster search requests execution.
839  /// - `max_concurrent_searches`: Controls the maximum number of concurrent
840  ///   searches the multi search api will execute.
841  /// - `max_concurrent_shard_requests`: The number of concurrent shard requests
842  ///   each sub search executes concurrently per node. This value should be
843  ///   used to limit the impact of the search on the cluster in order to limit
844  ///   the number of concurrent shard requests.
845  /// - `pre_filter_shard_size`: Threshold that enforces a pre-filter round-trip
846  ///   to prefilter search shards based on query rewriting if the number of
847  ///   shards the search request expands to exceeds the threshold. This filter
848  ///   round-trip can limit the number of shards significantly if for instance
849  ///   a shard can not match any documents based on its rewrite method ie. if
850  ///   date filters are mandatory to match but the shard bounds and the query
851  ///   are disjoint.
852  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
853  ///   rendered as an integer or an object in the rest search response.
854  /// - `search_type`: Search operation type.
855  /// - `typed_keys`: Specify whether aggregation and suggester names should be
856  ///   prefixed by their respective types in the response.
857  /// - `body`
858  ///```ignore
859  /// let response = client.msearch_post()
860  ///    .ccs_minimize_roundtrips(ccs_minimize_roundtrips)
861  ///    .max_concurrent_searches(max_concurrent_searches)
862  ///    .max_concurrent_shard_requests(max_concurrent_shard_requests)
863  ///    .pre_filter_shard_size(pre_filter_shard_size)
864  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
865  ///    .search_type(search_type)
866  ///    .typed_keys(typed_keys)
867  ///    .body(body)
868  ///    .send()
869  ///    .await;
870  /// ```
871  pub fn msearch_post(&self) -> builder::MsearchPost {
872    builder::MsearchPost::new(self)
873  }
874
875  ///Allows to execute several search template operations in one request.
876  ///
877  ///Sends a `GET` request to `/_msearch/template`
878  ///
879  ///Arguments:
880  /// - `ccs_minimize_roundtrips`: Indicates whether network round-trips should
881  ///   be minimized as part of cross-cluster search requests execution.
882  /// - `max_concurrent_searches`: Controls the maximum number of concurrent
883  ///   searches the multi search api will execute.
884  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
885  ///   rendered as an integer or an object in the rest search response.
886  /// - `search_type`: Search operation type.
887  /// - `typed_keys`: Specify whether aggregation and suggester names should be
888  ///   prefixed by their respective types in the response.
889  ///```ignore
890  /// let response = client.msearch_template_get()
891  ///    .ccs_minimize_roundtrips(ccs_minimize_roundtrips)
892  ///    .max_concurrent_searches(max_concurrent_searches)
893  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
894  ///    .search_type(search_type)
895  ///    .typed_keys(typed_keys)
896  ///    .send()
897  ///    .await;
898  /// ```
899  pub fn msearch_template_get(&self) -> builder::MsearchTemplateGet {
900    builder::MsearchTemplateGet::new(self)
901  }
902
903  ///Allows to execute several search template operations in one request.
904  ///
905  ///Sends a `POST` request to `/_msearch/template`
906  ///
907  ///Arguments:
908  /// - `ccs_minimize_roundtrips`: Indicates whether network round-trips should
909  ///   be minimized as part of cross-cluster search requests execution.
910  /// - `max_concurrent_searches`: Controls the maximum number of concurrent
911  ///   searches the multi search api will execute.
912  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
913  ///   rendered as an integer or an object in the rest search response.
914  /// - `search_type`: Search operation type.
915  /// - `typed_keys`: Specify whether aggregation and suggester names should be
916  ///   prefixed by their respective types in the response.
917  /// - `body`
918  ///```ignore
919  /// let response = client.msearch_template_post()
920  ///    .ccs_minimize_roundtrips(ccs_minimize_roundtrips)
921  ///    .max_concurrent_searches(max_concurrent_searches)
922  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
923  ///    .search_type(search_type)
924  ///    .typed_keys(typed_keys)
925  ///    .body(body)
926  ///    .send()
927  ///    .await;
928  /// ```
929  pub fn msearch_template_post(&self) -> builder::MsearchTemplatePost {
930    builder::MsearchTemplatePost::new(self)
931  }
932
933  ///Allows to evaluate the quality of ranked search results over a set of
934  /// typical search queries.
935  ///
936  ///Sends a `GET` request to `/_rank_eval`
937  ///
938  ///Arguments:
939  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
940  ///   resolves into no concrete indices. (This includes `_all` string or when
941  ///   no indices have been specified).
942  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
943  ///   indices that are open, closed or both.
944  /// - `ignore_unavailable`: Whether specified concrete indices should be
945  ///   ignored when unavailable (missing or closed).
946  /// - `search_type`: Search operation type.
947  ///```ignore
948  /// let response = client.rank_eval_get()
949  ///    .allow_no_indices(allow_no_indices)
950  ///    .expand_wildcards(expand_wildcards)
951  ///    .ignore_unavailable(ignore_unavailable)
952  ///    .search_type(search_type)
953  ///    .send()
954  ///    .await;
955  /// ```
956  pub fn rank_eval_get(&self) -> builder::RankEvalGet {
957    builder::RankEvalGet::new(self)
958  }
959
960  ///Allows to evaluate the quality of ranked search results over a set of
961  /// typical search queries.
962  ///
963  ///Sends a `POST` request to `/_rank_eval`
964  ///
965  ///Arguments:
966  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
967  ///   resolves into no concrete indices. (This includes `_all` string or when
968  ///   no indices have been specified).
969  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
970  ///   indices that are open, closed or both.
971  /// - `ignore_unavailable`: Whether specified concrete indices should be
972  ///   ignored when unavailable (missing or closed).
973  /// - `search_type`: Search operation type.
974  /// - `body`
975  ///```ignore
976  /// let response = client.rank_eval_post()
977  ///    .allow_no_indices(allow_no_indices)
978  ///    .expand_wildcards(expand_wildcards)
979  ///    .ignore_unavailable(ignore_unavailable)
980  ///    .search_type(search_type)
981  ///    .body(body)
982  ///    .send()
983  ///    .await;
984  /// ```
985  pub fn rank_eval_post(&self) -> builder::RankEvalPost {
986    builder::RankEvalPost::new(self)
987  }
988
989  ///Allows to copy documents from one index to another, optionally filtering
990  /// the source documents by a query, changing the destination index
991  /// settings, or fetching the documents from a remote cluster.
992  ///
993  ///Sends a `POST` request to `/_reindex`
994  ///
995  ///Arguments:
996  /// - `max_docs`: Maximum number of documents to process (default: all
997  ///   documents).
998  /// - `refresh`: Should the affected indexes be refreshed?.
999  /// - `requests_per_second`: The throttle for this request in sub-requests per
1000  ///   second. -1 means no throttle.
1001  /// - `scroll`: Specify how long a consistent view of the index should be
1002  ///   maintained for scrolled search.
1003  /// - `slices`: The number of slices this task should be divided into.
1004  ///   Defaults to 1, meaning the task isn't sliced into subtasks. Can be set
1005  ///   to `auto`.
1006  /// - `timeout`: Time each individual bulk request should wait for shards that
1007  ///   are unavailable.
1008  /// - `wait_for_active_shards`: Sets the number of shard copies that must be
1009  ///   active before proceeding with the operation. Defaults to 1, meaning the
1010  ///   primary shard only. Set to `all` for all shard copies, otherwise set to
1011  ///   any non-negative value less than or equal to the total number of copies
1012  ///   for the shard (number of replicas + 1).
1013  /// - `wait_for_completion`: Should this request wait until the operation has
1014  ///   completed before returning.
1015  /// - `body`
1016  ///```ignore
1017  /// let response = client.reindex()
1018  ///    .max_docs(max_docs)
1019  ///    .refresh(refresh)
1020  ///    .requests_per_second(requests_per_second)
1021  ///    .scroll(scroll)
1022  ///    .slices(slices)
1023  ///    .timeout(timeout)
1024  ///    .wait_for_active_shards(wait_for_active_shards)
1025  ///    .wait_for_completion(wait_for_completion)
1026  ///    .body(body)
1027  ///    .send()
1028  ///    .await;
1029  /// ```
1030  pub fn reindex(&self) -> builder::Reindex {
1031    builder::Reindex::new(self)
1032  }
1033
1034  ///Changes the number of requests per second for a particular Reindex
1035  /// operation.
1036  ///
1037  ///Sends a `POST` request to `/_reindex/{task_id}/_rethrottle`
1038  ///
1039  ///Arguments:
1040  /// - `task_id`: The task id to rethrottle.
1041  /// - `requests_per_second`: The throttle for this request in sub-requests per
1042  ///   second. -1 means no throttle.
1043  ///```ignore
1044  /// let response = client.reindex_rethrottle()
1045  ///    .task_id(task_id)
1046  ///    .requests_per_second(requests_per_second)
1047  ///    .send()
1048  ///    .await;
1049  /// ```
1050  pub fn reindex_rethrottle(&self) -> builder::ReindexRethrottle {
1051    builder::ReindexRethrottle::new(self)
1052  }
1053
1054  ///Allows to use the Mustache language to pre-render a search definition.
1055  ///
1056  ///Sends a `GET` request to `/_render/template`
1057  ///
1058  ///```ignore
1059  /// let response = client.render_search_template_get()
1060  ///    .send()
1061  ///    .await;
1062  /// ```
1063  pub fn render_search_template_get(&self) -> builder::RenderSearchTemplateGet {
1064    builder::RenderSearchTemplateGet::new(self)
1065  }
1066
1067  ///Allows to use the Mustache language to pre-render a search definition.
1068  ///
1069  ///Sends a `POST` request to `/_render/template`
1070  ///
1071  ///```ignore
1072  /// let response = client.render_search_template_post()
1073  ///    .body(body)
1074  ///    .send()
1075  ///    .await;
1076  /// ```
1077  pub fn render_search_template_post(&self) -> builder::RenderSearchTemplatePost {
1078    builder::RenderSearchTemplatePost::new(self)
1079  }
1080
1081  ///Allows to use the Mustache language to pre-render a search definition.
1082  ///
1083  ///Sends a `GET` request to `/_render/template/{id}`
1084  ///
1085  ///Arguments:
1086  /// - `id`: The id of the stored search template.
1087  ///```ignore
1088  /// let response = client.render_search_template_get_with_id()
1089  ///    .id(id)
1090  ///    .send()
1091  ///    .await;
1092  /// ```
1093  pub fn render_search_template_get_with_id(&self) -> builder::RenderSearchTemplateGetWithId {
1094    builder::RenderSearchTemplateGetWithId::new(self)
1095  }
1096
1097  ///Allows to use the Mustache language to pre-render a search definition.
1098  ///
1099  ///Sends a `POST` request to `/_render/template/{id}`
1100  ///
1101  ///Arguments:
1102  /// - `id`: The id of the stored search template.
1103  /// - `body`
1104  ///```ignore
1105  /// let response = client.render_search_template_post_with_id()
1106  ///    .id(id)
1107  ///    .body(body)
1108  ///    .send()
1109  ///    .await;
1110  /// ```
1111  pub fn render_search_template_post_with_id(&self) -> builder::RenderSearchTemplatePostWithId {
1112    builder::RenderSearchTemplatePostWithId::new(self)
1113  }
1114
1115  ///Returns all script contexts.
1116  ///
1117  ///Sends a `GET` request to `/_script_context`
1118  ///
1119  ///```ignore
1120  /// let response = client.get_script_context()
1121  ///    .send()
1122  ///    .await;
1123  /// ```
1124  pub fn get_script_context(&self) -> builder::GetScriptContext {
1125    builder::GetScriptContext::new(self)
1126  }
1127
1128  ///Returns available script types, languages and contexts.
1129  ///
1130  ///Sends a `GET` request to `/_script_language`
1131  ///
1132  ///```ignore
1133  /// let response = client.get_script_languages()
1134  ///    .send()
1135  ///    .await;
1136  /// ```
1137  pub fn get_script_languages(&self) -> builder::GetScriptLanguages {
1138    builder::GetScriptLanguages::new(self)
1139  }
1140
1141  ///Allows an arbitrary script to be executed and a result to be returned.
1142  ///
1143  ///Sends a `GET` request to `/_scripts/painless/_execute`
1144  ///
1145  ///```ignore
1146  /// let response = client.scripts_painless_execute_get()
1147  ///    .send()
1148  ///    .await;
1149  /// ```
1150  pub fn scripts_painless_execute_get(&self) -> builder::ScriptsPainlessExecuteGet {
1151    builder::ScriptsPainlessExecuteGet::new(self)
1152  }
1153
1154  ///Allows an arbitrary script to be executed and a result to be returned.
1155  ///
1156  ///Sends a `POST` request to `/_scripts/painless/_execute`
1157  ///
1158  ///```ignore
1159  /// let response = client.scripts_painless_execute_post()
1160  ///    .body(body)
1161  ///    .send()
1162  ///    .await;
1163  /// ```
1164  pub fn scripts_painless_execute_post(&self) -> builder::ScriptsPainlessExecutePost {
1165    builder::ScriptsPainlessExecutePost::new(self)
1166  }
1167
1168  ///Returns a script.
1169  ///
1170  ///Sends a `GET` request to `/_scripts/{id}`
1171  ///
1172  ///Arguments:
1173  /// - `id`: Script ID.
1174  /// - `cluster_manager_timeout`: Operation timeout for connection to
1175  ///   cluster-manager node.
1176  /// - `master_timeout`: Operation timeout for connection to master node.
1177  ///```ignore
1178  /// let response = client.get_script()
1179  ///    .id(id)
1180  ///    .cluster_manager_timeout(cluster_manager_timeout)
1181  ///    .master_timeout(master_timeout)
1182  ///    .send()
1183  ///    .await;
1184  /// ```
1185  pub fn get_script(&self) -> builder::GetScript {
1186    builder::GetScript::new(self)
1187  }
1188
1189  ///Creates or updates a script.
1190  ///
1191  ///Sends a `PUT` request to `/_scripts/{id}`
1192  ///
1193  ///Arguments:
1194  /// - `id`: Script ID.
1195  /// - `cluster_manager_timeout`: Operation timeout for connection to
1196  ///   cluster-manager node.
1197  /// - `master_timeout`: Operation timeout for connection to master node.
1198  /// - `timeout`: Operation timeout.
1199  /// - `body`
1200  ///```ignore
1201  /// let response = client.put_script_put()
1202  ///    .id(id)
1203  ///    .cluster_manager_timeout(cluster_manager_timeout)
1204  ///    .master_timeout(master_timeout)
1205  ///    .timeout(timeout)
1206  ///    .body(body)
1207  ///    .send()
1208  ///    .await;
1209  /// ```
1210  pub fn put_script_put(&self) -> builder::PutScriptPut {
1211    builder::PutScriptPut::new(self)
1212  }
1213
1214  ///Creates or updates a script.
1215  ///
1216  ///Sends a `POST` request to `/_scripts/{id}`
1217  ///
1218  ///Arguments:
1219  /// - `id`: Script ID.
1220  /// - `cluster_manager_timeout`: Operation timeout for connection to
1221  ///   cluster-manager node.
1222  /// - `master_timeout`: Operation timeout for connection to master node.
1223  /// - `timeout`: Operation timeout.
1224  /// - `body`
1225  ///```ignore
1226  /// let response = client.put_script_post()
1227  ///    .id(id)
1228  ///    .cluster_manager_timeout(cluster_manager_timeout)
1229  ///    .master_timeout(master_timeout)
1230  ///    .timeout(timeout)
1231  ///    .body(body)
1232  ///    .send()
1233  ///    .await;
1234  /// ```
1235  pub fn put_script_post(&self) -> builder::PutScriptPost {
1236    builder::PutScriptPost::new(self)
1237  }
1238
1239  ///Deletes a script.
1240  ///
1241  ///Sends a `DELETE` request to `/_scripts/{id}`
1242  ///
1243  ///Arguments:
1244  /// - `id`: Script ID.
1245  /// - `cluster_manager_timeout`: Operation timeout for connection to
1246  ///   cluster-manager node.
1247  /// - `master_timeout`: Operation timeout for connection to master node.
1248  /// - `timeout`: Operation timeout.
1249  ///```ignore
1250  /// let response = client.delete_script()
1251  ///    .id(id)
1252  ///    .cluster_manager_timeout(cluster_manager_timeout)
1253  ///    .master_timeout(master_timeout)
1254  ///    .timeout(timeout)
1255  ///    .send()
1256  ///    .await;
1257  /// ```
1258  pub fn delete_script(&self) -> builder::DeleteScript {
1259    builder::DeleteScript::new(self)
1260  }
1261
1262  ///Creates or updates a script.
1263  ///
1264  ///Sends a `PUT` request to `/_scripts/{id}/{context}`
1265  ///
1266  ///Arguments:
1267  /// - `id`: Script ID.
1268  /// - `context`: Script context.
1269  /// - `cluster_manager_timeout`: Operation timeout for connection to
1270  ///   cluster-manager node.
1271  /// - `master_timeout`: Operation timeout for connection to master node.
1272  /// - `timeout`: Operation timeout.
1273  /// - `body`
1274  ///```ignore
1275  /// let response = client.put_script_put_with_context()
1276  ///    .id(id)
1277  ///    .context(context)
1278  ///    .cluster_manager_timeout(cluster_manager_timeout)
1279  ///    .master_timeout(master_timeout)
1280  ///    .timeout(timeout)
1281  ///    .body(body)
1282  ///    .send()
1283  ///    .await;
1284  /// ```
1285  pub fn put_script_put_with_context(&self) -> builder::PutScriptPutWithContext {
1286    builder::PutScriptPutWithContext::new(self)
1287  }
1288
1289  ///Creates or updates a script.
1290  ///
1291  ///Sends a `POST` request to `/_scripts/{id}/{context}`
1292  ///
1293  ///Arguments:
1294  /// - `id`: Script ID.
1295  /// - `context`: Script context.
1296  /// - `cluster_manager_timeout`: Operation timeout for connection to
1297  ///   cluster-manager node.
1298  /// - `master_timeout`: Operation timeout for connection to master node.
1299  /// - `timeout`: Operation timeout.
1300  /// - `body`
1301  ///```ignore
1302  /// let response = client.put_script_post_with_context()
1303  ///    .id(id)
1304  ///    .context(context)
1305  ///    .cluster_manager_timeout(cluster_manager_timeout)
1306  ///    .master_timeout(master_timeout)
1307  ///    .timeout(timeout)
1308  ///    .body(body)
1309  ///    .send()
1310  ///    .await;
1311  /// ```
1312  pub fn put_script_post_with_context(&self) -> builder::PutScriptPostWithContext {
1313    builder::PutScriptPostWithContext::new(self)
1314  }
1315
1316  ///Returns results matching a query.
1317  ///
1318  ///Sends a `POST` request to `/_search`
1319  ///
1320  ///Arguments:
1321  /// - `source`: True or false to return the _source field or not, or a list of
1322  ///   fields to return.
1323  /// - `source_excludes`: List of fields to exclude from the returned _source
1324  ///   field.
1325  /// - `source_includes`: List of fields to extract and return from the _source
1326  ///   field.
1327  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
1328  ///   resolves into no concrete indices. (This includes `_all` string or when
1329  ///   no indices have been specified).
1330  /// - `allow_partial_search_results`: Indicate if an error should be returned
1331  ///   if there is a partial search failure or timeout.
1332  /// - `analyze_wildcard`: Specify whether wildcard and prefix queries should
1333  ///   be analyzed.
1334  /// - `analyzer`: The analyzer to use for the query string.
1335  /// - `batched_reduce_size`: The number of shard results that should be
1336  ///   reduced at once on the coordinating node. This value should be used as a
1337  ///   protection mechanism to reduce the memory overhead per search request if
1338  ///   the potential number of shards in the request can be large.
1339  /// - `ccs_minimize_roundtrips`: Indicates whether network round-trips should
1340  ///   be minimized as part of cross-cluster search requests execution.
1341  /// - `default_operator`: The default operator for query string query (AND or
1342  ///   OR).
1343  /// - `df`: The field to use as default where no field prefix is given in the
1344  ///   query string.
1345  /// - `docvalue_fields`: Comma-separated list of fields to return as the
1346  ///   docvalue representation of a field for each hit.
1347  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
1348  ///   indices that are open, closed or both.
1349  /// - `explain`: Specify whether to return detailed information about score
1350  ///   computation as part of a hit.
1351  /// - `from`: Starting offset.
1352  /// - `ignore_throttled`: Whether specified concrete, expanded or aliased
1353  ///   indices should be ignored when throttled.
1354  /// - `ignore_unavailable`: Whether specified concrete indices should be
1355  ///   ignored when unavailable (missing or closed).
1356  /// - `lenient`: Specify whether format-based query failures (such as
1357  ///   providing text to a numeric field) should be ignored.
1358  /// - `max_concurrent_shard_requests`: The number of concurrent shard requests
1359  ///   per node this search executes concurrently. This value should be used to
1360  ///   limit the impact of the search on the cluster in order to limit the
1361  ///   number of concurrent shard requests.
1362  /// - `pre_filter_shard_size`: Threshold that enforces a pre-filter round-trip
1363  ///   to prefilter search shards based on query rewriting if the number of
1364  ///   shards the search request expands to exceeds the threshold. This filter
1365  ///   round-trip can limit the number of shards significantly if for instance
1366  ///   a shard can not match any documents based on its rewrite method ie. if
1367  ///   date filters are mandatory to match but the shard bounds and the query
1368  ///   are disjoint.
1369  /// - `preference`: Specify the node or shard the operation should be
1370  ///   performed on.
1371  /// - `q`: Query in the Lucene query string syntax.
1372  /// - `request_cache`: Specify if request cache should be used for this
1373  ///   request or not, defaults to index level setting.
1374  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
1375  ///   rendered as an integer or an object in the rest search response.
1376  /// - `routing`: Comma-separated list of specific routing values.
1377  /// - `scroll`: Specify how long a consistent view of the index should be
1378  ///   maintained for scrolled search.
1379  /// - `search_type`: Search operation type.
1380  /// - `seq_no_primary_term`: Specify whether to return sequence number and
1381  ///   primary term of the last modification of each hit.
1382  /// - `size`: Number of hits to return.
1383  /// - `sort`: Comma-separated list of <field>:<direction> pairs.
1384  /// - `stats`: Specific 'tag' of the request for logging and statistical
1385  ///   purposes.
1386  /// - `stored_fields`: Comma-separated list of stored fields to return.
1387  /// - `suggest_field`: Specify which field to use for suggestions.
1388  /// - `suggest_mode`: Specify suggest mode.
1389  /// - `suggest_size`: How many suggestions to return in response.
1390  /// - `suggest_text`: The source text for which the suggestions should be
1391  ///   returned.
1392  /// - `terminate_after`: The maximum number of documents to collect for each
1393  ///   shard, upon reaching which the query execution will terminate early.
1394  /// - `timeout`: Operation timeout.
1395  /// - `track_scores`: Whether to calculate and return scores even if they are
1396  ///   not used for sorting.
1397  /// - `track_total_hits`: Indicate if the number of documents that match the
1398  ///   query should be tracked.
1399  /// - `typed_keys`: Specify whether aggregation and suggester names should be
1400  ///   prefixed by their respective types in the response.
1401  /// - `version`: Whether to return document version as part of a hit.
1402  /// - `body`
1403  ///```ignore
1404  /// let response = client.search_post()
1405  ///    .source(source)
1406  ///    .source_excludes(source_excludes)
1407  ///    .source_includes(source_includes)
1408  ///    .allow_no_indices(allow_no_indices)
1409  ///    .allow_partial_search_results(allow_partial_search_results)
1410  ///    .analyze_wildcard(analyze_wildcard)
1411  ///    .analyzer(analyzer)
1412  ///    .batched_reduce_size(batched_reduce_size)
1413  ///    .ccs_minimize_roundtrips(ccs_minimize_roundtrips)
1414  ///    .default_operator(default_operator)
1415  ///    .df(df)
1416  ///    .docvalue_fields(docvalue_fields)
1417  ///    .expand_wildcards(expand_wildcards)
1418  ///    .explain(explain)
1419  ///    .from(from)
1420  ///    .ignore_throttled(ignore_throttled)
1421  ///    .ignore_unavailable(ignore_unavailable)
1422  ///    .lenient(lenient)
1423  ///    .max_concurrent_shard_requests(max_concurrent_shard_requests)
1424  ///    .pre_filter_shard_size(pre_filter_shard_size)
1425  ///    .preference(preference)
1426  ///    .q(q)
1427  ///    .request_cache(request_cache)
1428  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
1429  ///    .routing(routing)
1430  ///    .scroll(scroll)
1431  ///    .search_type(search_type)
1432  ///    .seq_no_primary_term(seq_no_primary_term)
1433  ///    .size(size)
1434  ///    .sort(sort)
1435  ///    .stats(stats)
1436  ///    .stored_fields(stored_fields)
1437  ///    .suggest_field(suggest_field)
1438  ///    .suggest_mode(suggest_mode)
1439  ///    .suggest_size(suggest_size)
1440  ///    .suggest_text(suggest_text)
1441  ///    .terminate_after(terminate_after)
1442  ///    .timeout(timeout)
1443  ///    .track_scores(track_scores)
1444  ///    .track_total_hits(track_total_hits)
1445  ///    .typed_keys(typed_keys)
1446  ///    .version(version)
1447  ///    .body(body)
1448  ///    .send()
1449  ///    .await;
1450  /// ```
1451  #[cfg(feature = "search")]
1452  pub fn search_post(&self) -> builder::SearchPost {
1453    builder::SearchPost::new(self)
1454  }
1455
1456  ///Deletes one or more point in time searches based on the IDs passed.
1457  ///
1458  ///Sends a `DELETE` request to `/_search/point_in_time`
1459  ///
1460  ///```ignore
1461  /// let response = client.delete_pit()
1462  ///    .body(body)
1463  ///    .send()
1464  ///    .await;
1465  /// ```
1466  pub fn delete_pit(&self) -> builder::DeletePit {
1467    builder::DeletePit::new(self)
1468  }
1469
1470  ///Lists all active point in time searches.
1471  ///
1472  ///Sends a `GET` request to `/_search/point_in_time/_all`
1473  ///
1474  ///```ignore
1475  /// let response = client.get_all_pits()
1476  ///    .send()
1477  ///    .await;
1478  /// ```
1479  pub fn get_all_pits(&self) -> builder::GetAllPits {
1480    builder::GetAllPits::new(self)
1481  }
1482
1483  ///Deletes all active point in time searches.
1484  ///
1485  ///Sends a `DELETE` request to `/_search/point_in_time/_all`
1486  ///
1487  ///```ignore
1488  /// let response = client.delete_all_pits()
1489  ///    .send()
1490  ///    .await;
1491  /// ```
1492  pub fn delete_all_pits(&self) -> builder::DeleteAllPits {
1493    builder::DeleteAllPits::new(self)
1494  }
1495
1496  ///Allows to retrieve a large numbers of results from a single search
1497  /// request.
1498  ///
1499  ///Sends a `GET` request to `/_search/scroll`
1500  ///
1501  ///Arguments:
1502  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
1503  ///   rendered as an integer or an object in the rest search response.
1504  /// - `scroll`: Specify how long a consistent view of the index should be
1505  ///   maintained for scrolled search.
1506  /// - `scroll_id`: Scroll ID.
1507  ///```ignore
1508  /// let response = client.scroll_get()
1509  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
1510  ///    .scroll(scroll)
1511  ///    .scroll_id(scroll_id)
1512  ///    .send()
1513  ///    .await;
1514  /// ```
1515  pub fn scroll_get(&self) -> builder::ScrollGet {
1516    builder::ScrollGet::new(self)
1517  }
1518
1519  ///Allows to retrieve a large numbers of results from a single search
1520  /// request.
1521  ///
1522  ///Sends a `POST` request to `/_search/scroll`
1523  ///
1524  ///Arguments:
1525  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
1526  ///   rendered as an integer or an object in the rest search response.
1527  /// - `scroll`: Specify how long a consistent view of the index should be
1528  ///   maintained for scrolled search.
1529  /// - `scroll_id`: Scroll ID.
1530  /// - `body`
1531  ///```ignore
1532  /// let response = client.scroll_post()
1533  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
1534  ///    .scroll(scroll)
1535  ///    .scroll_id(scroll_id)
1536  ///    .body(body)
1537  ///    .send()
1538  ///    .await;
1539  /// ```
1540  pub fn scroll_post(&self) -> builder::ScrollPost {
1541    builder::ScrollPost::new(self)
1542  }
1543
1544  ///Explicitly clears the search context for a scroll.
1545  ///
1546  ///Sends a `DELETE` request to `/_search/scroll`
1547  ///
1548  ///```ignore
1549  /// let response = client.clear_scroll()
1550  ///    .body(body)
1551  ///    .send()
1552  ///    .await;
1553  /// ```
1554  pub fn clear_scroll(&self) -> builder::ClearScroll {
1555    builder::ClearScroll::new(self)
1556  }
1557
1558  ///Allows to retrieve a large numbers of results from a single search
1559  /// request.
1560  ///
1561  ///Sends a `GET` request to `/_search/scroll/{scroll_id}`
1562  ///
1563  ///Arguments:
1564  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
1565  ///   rendered as an integer or an object in the rest search response.
1566  /// - `scroll`: Specify how long a consistent view of the index should be
1567  ///   maintained for scrolled search.
1568  /// - `scroll_id`: Scroll ID.
1569  ///```ignore
1570  /// let response = client.scroll_get_with_scroll_id()
1571  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
1572  ///    .scroll(scroll)
1573  ///    .scroll_id(scroll_id)
1574  ///    .send()
1575  ///    .await;
1576  /// ```
1577  pub fn scroll_get_with_scroll_id(&self) -> builder::ScrollGetWithScrollId {
1578    builder::ScrollGetWithScrollId::new(self)
1579  }
1580
1581  ///Allows to retrieve a large numbers of results from a single search
1582  /// request.
1583  ///
1584  ///Sends a `POST` request to `/_search/scroll/{scroll_id}`
1585  ///
1586  ///Arguments:
1587  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
1588  ///   rendered as an integer or an object in the rest search response.
1589  /// - `scroll`: Specify how long a consistent view of the index should be
1590  ///   maintained for scrolled search.
1591  /// - `scroll_id`: Scroll ID.
1592  /// - `body`
1593  ///```ignore
1594  /// let response = client.scroll_post_with_scroll_id()
1595  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
1596  ///    .scroll(scroll)
1597  ///    .scroll_id(scroll_id)
1598  ///    .body(body)
1599  ///    .send()
1600  ///    .await;
1601  /// ```
1602  pub fn scroll_post_with_scroll_id(&self) -> builder::ScrollPostWithScrollId {
1603    builder::ScrollPostWithScrollId::new(self)
1604  }
1605
1606  ///Explicitly clears the search context for a scroll.
1607  ///
1608  ///Sends a `DELETE` request to `/_search/scroll/{scroll_id}`
1609  ///
1610  ///Arguments:
1611  /// - `scroll_id`: Comma-separated list of scroll IDs to clear.
1612  /// - `body`
1613  ///```ignore
1614  /// let response = client.clear_scroll_with_scroll_id()
1615  ///    .scroll_id(scroll_id)
1616  ///    .body(body)
1617  ///    .send()
1618  ///    .await;
1619  /// ```
1620  pub fn clear_scroll_with_scroll_id(&self) -> builder::ClearScrollWithScrollId {
1621    builder::ClearScrollWithScrollId::new(self)
1622  }
1623
1624  ///Allows to use the Mustache language to pre-render a search definition.
1625  ///
1626  ///Sends a `GET` request to `/_search/template`
1627  ///
1628  ///Arguments:
1629  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
1630  ///   resolves into no concrete indices. (This includes `_all` string or when
1631  ///   no indices have been specified).
1632  /// - `ccs_minimize_roundtrips`: Indicates whether network round-trips should
1633  ///   be minimized as part of cross-cluster search requests execution.
1634  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
1635  ///   indices that are open, closed or both.
1636  /// - `explain`: Specify whether to return detailed information about score
1637  ///   computation as part of a hit.
1638  /// - `ignore_throttled`: Whether specified concrete, expanded or aliased
1639  ///   indices should be ignored when throttled.
1640  /// - `ignore_unavailable`: Whether specified concrete indices should be
1641  ///   ignored when unavailable (missing or closed).
1642  /// - `preference`: Specify the node or shard the operation should be
1643  ///   performed on.
1644  /// - `profile`: Specify whether to profile the query execution.
1645  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
1646  ///   rendered as an integer or an object in the rest search response.
1647  /// - `routing`: Comma-separated list of specific routing values.
1648  /// - `scroll`: Specify how long a consistent view of the index should be
1649  ///   maintained for scrolled search.
1650  /// - `search_type`: Search operation type.
1651  /// - `typed_keys`: Specify whether aggregation and suggester names should be
1652  ///   prefixed by their respective types in the response.
1653  ///```ignore
1654  /// let response = client.search_template_get()
1655  ///    .allow_no_indices(allow_no_indices)
1656  ///    .ccs_minimize_roundtrips(ccs_minimize_roundtrips)
1657  ///    .expand_wildcards(expand_wildcards)
1658  ///    .explain(explain)
1659  ///    .ignore_throttled(ignore_throttled)
1660  ///    .ignore_unavailable(ignore_unavailable)
1661  ///    .preference(preference)
1662  ///    .profile(profile)
1663  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
1664  ///    .routing(routing)
1665  ///    .scroll(scroll)
1666  ///    .search_type(search_type)
1667  ///    .typed_keys(typed_keys)
1668  ///    .send()
1669  ///    .await;
1670  /// ```
1671  #[cfg(feature = "search")]
1672  pub fn search_template_get(&self) -> builder::SearchTemplateGet {
1673    builder::SearchTemplateGet::new(self)
1674  }
1675
1676  ///Allows to use the Mustache language to pre-render a search definition.
1677  ///
1678  ///Sends a `POST` request to `/_search/template`
1679  ///
1680  ///Arguments:
1681  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
1682  ///   resolves into no concrete indices. (This includes `_all` string or when
1683  ///   no indices have been specified).
1684  /// - `ccs_minimize_roundtrips`: Indicates whether network round-trips should
1685  ///   be minimized as part of cross-cluster search requests execution.
1686  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
1687  ///   indices that are open, closed or both.
1688  /// - `explain`: Specify whether to return detailed information about score
1689  ///   computation as part of a hit.
1690  /// - `ignore_throttled`: Whether specified concrete, expanded or aliased
1691  ///   indices should be ignored when throttled.
1692  /// - `ignore_unavailable`: Whether specified concrete indices should be
1693  ///   ignored when unavailable (missing or closed).
1694  /// - `preference`: Specify the node or shard the operation should be
1695  ///   performed on.
1696  /// - `profile`: Specify whether to profile the query execution.
1697  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
1698  ///   rendered as an integer or an object in the rest search response.
1699  /// - `routing`: Comma-separated list of specific routing values.
1700  /// - `scroll`: Specify how long a consistent view of the index should be
1701  ///   maintained for scrolled search.
1702  /// - `search_type`: Search operation type.
1703  /// - `typed_keys`: Specify whether aggregation and suggester names should be
1704  ///   prefixed by their respective types in the response.
1705  /// - `body`
1706  ///```ignore
1707  /// let response = client.search_template_post()
1708  ///    .allow_no_indices(allow_no_indices)
1709  ///    .ccs_minimize_roundtrips(ccs_minimize_roundtrips)
1710  ///    .expand_wildcards(expand_wildcards)
1711  ///    .explain(explain)
1712  ///    .ignore_throttled(ignore_throttled)
1713  ///    .ignore_unavailable(ignore_unavailable)
1714  ///    .preference(preference)
1715  ///    .profile(profile)
1716  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
1717  ///    .routing(routing)
1718  ///    .scroll(scroll)
1719  ///    .search_type(search_type)
1720  ///    .typed_keys(typed_keys)
1721  ///    .body(body)
1722  ///    .send()
1723  ///    .await;
1724  /// ```
1725  #[cfg(feature = "search")]
1726  pub fn search_template_post(&self) -> builder::SearchTemplatePost {
1727    builder::SearchTemplatePost::new(self)
1728  }
1729
1730  ///Returns information about the indices and shards that a search request
1731  /// would be executed against.
1732  ///
1733  ///Sends a `GET` request to `/_search_shards`
1734  ///
1735  ///Arguments:
1736  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
1737  ///   resolves into no concrete indices. (This includes `_all` string or when
1738  ///   no indices have been specified).
1739  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
1740  ///   indices that are open, closed or both.
1741  /// - `ignore_unavailable`: Whether specified concrete indices should be
1742  ///   ignored when unavailable (missing or closed).
1743  /// - `local`: Return local information, do not retrieve the state from
1744  ///   cluster-manager node.
1745  /// - `preference`: Specify the node or shard the operation should be
1746  ///   performed on.
1747  /// - `routing`: Routing value.
1748  ///```ignore
1749  /// let response = client.search_shards_get()
1750  ///    .allow_no_indices(allow_no_indices)
1751  ///    .expand_wildcards(expand_wildcards)
1752  ///    .ignore_unavailable(ignore_unavailable)
1753  ///    .local(local)
1754  ///    .preference(preference)
1755  ///    .routing(routing)
1756  ///    .send()
1757  ///    .await;
1758  /// ```
1759  #[cfg(feature = "search")]
1760  pub fn search_shards_get(&self) -> builder::SearchShardsGet {
1761    builder::SearchShardsGet::new(self)
1762  }
1763
1764  ///Returns information about the indices and shards that a search request
1765  /// would be executed against.
1766  ///
1767  ///Sends a `POST` request to `/_search_shards`
1768  ///
1769  ///Arguments:
1770  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
1771  ///   resolves into no concrete indices. (This includes `_all` string or when
1772  ///   no indices have been specified).
1773  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
1774  ///   indices that are open, closed or both.
1775  /// - `ignore_unavailable`: Whether specified concrete indices should be
1776  ///   ignored when unavailable (missing or closed).
1777  /// - `local`: Return local information, do not retrieve the state from
1778  ///   cluster-manager node.
1779  /// - `preference`: Specify the node or shard the operation should be
1780  ///   performed on.
1781  /// - `routing`: Routing value.
1782  ///```ignore
1783  /// let response = client.search_shards_post()
1784  ///    .allow_no_indices(allow_no_indices)
1785  ///    .expand_wildcards(expand_wildcards)
1786  ///    .ignore_unavailable(ignore_unavailable)
1787  ///    .local(local)
1788  ///    .preference(preference)
1789  ///    .routing(routing)
1790  ///    .send()
1791  ///    .await;
1792  /// ```
1793  #[cfg(feature = "search")]
1794  pub fn search_shards_post(&self) -> builder::SearchShardsPost {
1795    builder::SearchShardsPost::new(self)
1796  }
1797
1798  ///Changes the number of requests per second for a particular Update By
1799  /// Query operation.
1800  ///
1801  ///Sends a `POST` request to `/_update_by_query/{task_id}/_rethrottle`
1802  ///
1803  ///Arguments:
1804  /// - `task_id`: The task id to rethrottle.
1805  /// - `requests_per_second`: The throttle for this request in sub-requests per
1806  ///   second. -1 means no throttle.
1807  ///```ignore
1808  /// let response = client.update_by_query_rethrottle()
1809  ///    .task_id(task_id)
1810  ///    .requests_per_second(requests_per_second)
1811  ///    .send()
1812  ///    .await;
1813  /// ```
1814  pub fn update_by_query_rethrottle(&self) -> builder::UpdateByQueryRethrottle {
1815    builder::UpdateByQueryRethrottle::new(self)
1816  }
1817
1818  ///Returns number of documents matching a query.
1819  ///
1820  ///Sends a `POST` request to `/{index}/_count`
1821  ///
1822  ///Arguments:
1823  /// - `index`: Comma-separated list of indices to restrict the results.
1824  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
1825  ///   resolves into no concrete indices. (This includes `_all` string or when
1826  ///   no indices have been specified).
1827  /// - `analyze_wildcard`: Specify whether wildcard and prefix queries should
1828  ///   be analyzed.
1829  /// - `analyzer`: The analyzer to use for the query string.
1830  /// - `default_operator`: The default operator for query string query (AND or
1831  ///   OR).
1832  /// - `df`: The field to use as default where no field prefix is given in the
1833  ///   query string.
1834  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
1835  ///   indices that are open, closed or both.
1836  /// - `ignore_throttled`: Whether specified concrete, expanded or aliased
1837  ///   indices should be ignored when throttled.
1838  /// - `ignore_unavailable`: Whether specified concrete indices should be
1839  ///   ignored when unavailable (missing or closed).
1840  /// - `lenient`: Specify whether format-based query failures (such as
1841  ///   providing text to a numeric field) should be ignored.
1842  /// - `min_score`: Include only documents with a specific `_score` value in
1843  ///   the result.
1844  /// - `preference`: Specify the node or shard the operation should be
1845  ///   performed on.
1846  /// - `q`: Query in the Lucene query string syntax.
1847  /// - `routing`: Comma-separated list of specific routing values.
1848  /// - `terminate_after`: The maximum number of documents to collect for each
1849  ///   shard, upon reaching which the query execution will terminate early.
1850  /// - `body`
1851  ///```ignore
1852  /// let response = client.count()
1853  ///    .index(index)
1854  ///    .allow_no_indices(allow_no_indices)
1855  ///    .analyze_wildcard(analyze_wildcard)
1856  ///    .analyzer(analyzer)
1857  ///    .default_operator(default_operator)
1858  ///    .df(df)
1859  ///    .expand_wildcards(expand_wildcards)
1860  ///    .ignore_throttled(ignore_throttled)
1861  ///    .ignore_unavailable(ignore_unavailable)
1862  ///    .lenient(lenient)
1863  ///    .min_score(min_score)
1864  ///    .preference(preference)
1865  ///    .q(q)
1866  ///    .routing(routing)
1867  ///    .terminate_after(terminate_after)
1868  ///    .body(body)
1869  ///    .send()
1870  ///    .await;
1871  /// ```
1872  #[cfg(feature = "search")]
1873  pub fn count(&self) -> builder_search::Count {
1874    builder_search::Count::new(self)
1875  }
1876
1877  ///Creates a new document in the index.
1878  ///
1879  ///Returns a 409 response when a document with a same ID already exists in
1880  /// the index.
1881  ///
1882  ///Sends a `PUT` request to `/{index}/_create/{id}`
1883  ///
1884  ///Arguments:
1885  /// - `index`: Index name.
1886  /// - `id`: Document ID.
1887  /// - `pipeline`: The pipeline id to preprocess incoming documents with.
1888  /// - `refresh`: If `true` then refresh the affected shards to make this
1889  ///   operation visible to search, if `wait_for` then wait for a refresh to
1890  ///   make this operation visible to search, if `false` (the default) then do
1891  ///   nothing with refreshes.
1892  /// - `routing`: Routing value.
1893  /// - `timeout`: Operation timeout.
1894  /// - `version`: Explicit version number for concurrency control.
1895  /// - `version_type`: Specific version type.
1896  /// - `wait_for_active_shards`: Sets the number of shard copies that must be
1897  ///   active before proceeding with the operation. Defaults to 1, meaning the
1898  ///   primary shard only. Set to `all` for all shard copies, otherwise set to
1899  ///   any non-negative value less than or equal to the total number of copies
1900  ///   for the shard (number of replicas + 1).
1901  /// - `body`
1902  ///```ignore
1903  /// let response = client.create_put()
1904  ///    .index(index)
1905  ///    .id(id)
1906  ///    .pipeline(pipeline)
1907  ///    .refresh(refresh)
1908  ///    .routing(routing)
1909  ///    .timeout(timeout)
1910  ///    .version(version)
1911  ///    .version_type(version_type)
1912  ///    .wait_for_active_shards(wait_for_active_shards)
1913  ///    .body(body)
1914  ///    .send()
1915  ///    .await;
1916  /// ```
1917  pub fn create_put(&self) -> builder::CreatePut {
1918    builder::CreatePut::new(self)
1919  }
1920
1921  ///Deletes documents matching the provided query.
1922  ///
1923  ///Sends a `POST` request to `/{index}/_delete_by_query`
1924  ///
1925  ///Arguments:
1926  /// - `index`: Comma-separated list of indices; use `_all` or empty string to
1927  ///   perform the operation on all indices.
1928  /// - `source`: True or false to return the _source field or not, or a list of
1929  ///   fields to return.
1930  /// - `source_excludes`: List of fields to exclude from the returned _source
1931  ///   field.
1932  /// - `source_includes`: List of fields to extract and return from the _source
1933  ///   field.
1934  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
1935  ///   resolves into no concrete indices. (This includes `_all` string or when
1936  ///   no indices have been specified).
1937  /// - `analyze_wildcard`: Specify whether wildcard and prefix queries should
1938  ///   be analyzed.
1939  /// - `analyzer`: The analyzer to use for the query string.
1940  /// - `conflicts`: What to do when the operation encounters version
1941  ///   conflicts?.
1942  /// - `default_operator`: The default operator for query string query (AND or
1943  ///   OR).
1944  /// - `df`: The field to use as default where no field prefix is given in the
1945  ///   query string.
1946  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
1947  ///   indices that are open, closed or both.
1948  /// - `from`: Starting offset.
1949  /// - `ignore_unavailable`: Whether specified concrete indices should be
1950  ///   ignored when unavailable (missing or closed).
1951  /// - `lenient`: Specify whether format-based query failures (such as
1952  ///   providing text to a numeric field) should be ignored.
1953  /// - `max_docs`: Maximum number of documents to process (default: all
1954  ///   documents).
1955  /// - `preference`: Specify the node or shard the operation should be
1956  ///   performed on.
1957  /// - `q`: Query in the Lucene query string syntax.
1958  /// - `refresh`: Refresh the shard containing the document before performing
1959  ///   the operation.
1960  /// - `request_cache`: Specify if request cache should be used for this
1961  ///   request or not, defaults to index level setting.
1962  /// - `requests_per_second`: The throttle for this request in sub-requests per
1963  ///   second. -1 means no throttle.
1964  /// - `routing`: Comma-separated list of specific routing values.
1965  /// - `scroll`: Specify how long a consistent view of the index should be
1966  ///   maintained for scrolled search.
1967  /// - `scroll_size`: Size on the scroll request powering the operation.
1968  /// - `search_timeout`: Explicit timeout for each search request. Defaults to
1969  ///   no timeout.
1970  /// - `search_type`: Search operation type.
1971  /// - `size`: Deprecated, please use `max_docs` instead.
1972  /// - `slices`: The number of slices this task should be divided into.
1973  ///   Defaults to 1, meaning the task isn't sliced into subtasks. Can be set
1974  ///   to `auto`.
1975  /// - `sort`: Comma-separated list of <field>:<direction> pairs.
1976  /// - `stats`: Specific 'tag' of the request for logging and statistical
1977  ///   purposes.
1978  /// - `terminate_after`: The maximum number of documents to collect for each
1979  ///   shard, upon reaching which the query execution will terminate early.
1980  /// - `timeout`: Time each individual bulk request should wait for shards that
1981  ///   are unavailable.
1982  /// - `version`: Whether to return document version as part of a hit.
1983  /// - `wait_for_active_shards`: Sets the number of shard copies that must be
1984  ///   active before proceeding with the operation. Defaults to 1, meaning the
1985  ///   primary shard only. Set to `all` for all shard copies, otherwise set to
1986  ///   any non-negative value less than or equal to the total number of copies
1987  ///   for the shard (number of replicas + 1).
1988  /// - `wait_for_completion`: Should this request wait until the operation has
1989  ///   completed before returning.
1990  /// - `body`
1991  ///```ignore
1992  /// let response = client.delete_by_query()
1993  ///    .index(index)
1994  ///    .source(source)
1995  ///    .source_excludes(source_excludes)
1996  ///    .source_includes(source_includes)
1997  ///    .allow_no_indices(allow_no_indices)
1998  ///    .analyze_wildcard(analyze_wildcard)
1999  ///    .analyzer(analyzer)
2000  ///    .conflicts(conflicts)
2001  ///    .default_operator(default_operator)
2002  ///    .df(df)
2003  ///    .expand_wildcards(expand_wildcards)
2004  ///    .from(from)
2005  ///    .ignore_unavailable(ignore_unavailable)
2006  ///    .lenient(lenient)
2007  ///    .max_docs(max_docs)
2008  ///    .preference(preference)
2009  ///    .q(q)
2010  ///    .refresh(refresh)
2011  ///    .request_cache(request_cache)
2012  ///    .requests_per_second(requests_per_second)
2013  ///    .routing(routing)
2014  ///    .scroll(scroll)
2015  ///    .scroll_size(scroll_size)
2016  ///    .search_timeout(search_timeout)
2017  ///    .search_type(search_type)
2018  ///    .size(size)
2019  ///    .slices(slices)
2020  ///    .sort(sort)
2021  ///    .stats(stats)
2022  ///    .terminate_after(terminate_after)
2023  ///    .timeout(timeout)
2024  ///    .version(version)
2025  ///    .wait_for_active_shards(wait_for_active_shards)
2026  ///    .wait_for_completion(wait_for_completion)
2027  ///    .body(body)
2028  ///    .send()
2029  ///    .await;
2030  /// ```
2031  pub fn delete_by_query(&self) -> builder::DeleteByQuery {
2032    builder::DeleteByQuery::new(self)
2033  }
2034
2035  ///Returns a document.
2036  ///
2037  ///Sends a `GET` request to `/{index}/_doc/{id}`
2038  ///
2039  ///Arguments:
2040  /// - `index`: Index name.
2041  /// - `id`: Document ID.
2042  /// - `source`: True or false to return the _source field or not, or a list of
2043  ///   fields to return.
2044  /// - `source_excludes`: List of fields to exclude from the returned _source
2045  ///   field.
2046  /// - `source_includes`: List of fields to extract and return from the _source
2047  ///   field.
2048  /// - `preference`: Specify the node or shard the operation should be
2049  ///   performed on.
2050  /// - `realtime`: Specify whether to perform the operation in realtime or
2051  ///   search mode.
2052  /// - `refresh`: Refresh the shard containing the document before performing
2053  ///   the operation.
2054  /// - `routing`: Routing value.
2055  /// - `stored_fields`: Comma-separated list of stored fields to return.
2056  /// - `version`: Explicit version number for concurrency control.
2057  /// - `version_type`: Specific version type.
2058  ///```ignore
2059  /// let response = client.get()
2060  ///    .index(index)
2061  ///    .id(id)
2062  ///    .source(source)
2063  ///    .source_excludes(source_excludes)
2064  ///    .source_includes(source_includes)
2065  ///    .preference(preference)
2066  ///    .realtime(realtime)
2067  ///    .refresh(refresh)
2068  ///    .routing(routing)
2069  ///    .stored_fields(stored_fields)
2070  ///    .version(version)
2071  ///    .version_type(version_type)
2072  ///    .send()
2073  ///    .await;
2074  /// ```
2075  pub fn get(&self) -> builder::Get {
2076    builder::Get::new(self)
2077  }
2078
2079  ///Creates or updates a document in an index.
2080  ///
2081  ///Sends a `PUT` request to `/{index}/_doc/{id}`
2082  ///
2083  ///Arguments:
2084  /// - `index`: Index name.
2085  /// - `id`: Document ID.
2086  /// - `if_primary_term`: only perform the operation if the last operation that
2087  ///   has changed the document has the specified primary term.
2088  /// - `if_seq_no`: only perform the operation if the last operation that has
2089  ///   changed the document has the specified sequence number.
2090  /// - `op_type`: Explicit operation type. Defaults to `index` for requests
2091  ///   with an explicit document ID, and to `create`for requests without an
2092  ///   explicit document ID.
2093  /// - `pipeline`: The pipeline id to preprocess incoming documents with.
2094  /// - `refresh`: If `true` then refresh the affected shards to make this
2095  ///   operation visible to search, if `wait_for` then wait for a refresh to
2096  ///   make this operation visible to search, if `false` (the default) then do
2097  ///   nothing with refreshes.
2098  /// - `require_alias`: When true, requires destination to be an alias.
2099  /// - `routing`: Routing value.
2100  /// - `timeout`: Operation timeout.
2101  /// - `version`: Explicit version number for concurrency control.
2102  /// - `version_type`: Specific version type.
2103  /// - `wait_for_active_shards`: Sets the number of shard copies that must be
2104  ///   active before proceeding with the operation. Defaults to 1, meaning the
2105  ///   primary shard only. Set to `all` for all shard copies, otherwise set to
2106  ///   any non-negative value less than or equal to the total number of copies
2107  ///   for the shard (number of replicas + 1).
2108  /// - `body`
2109  ///```ignore
2110  /// let response = client.index_put_with_id()
2111  ///    .index(index)
2112  ///    .id(id)
2113  ///    .if_primary_term(if_primary_term)
2114  ///    .if_seq_no(if_seq_no)
2115  ///    .op_type(op_type)
2116  ///    .pipeline(pipeline)
2117  ///    .refresh(refresh)
2118  ///    .require_alias(require_alias)
2119  ///    .routing(routing)
2120  ///    .timeout(timeout)
2121  ///    .version(version)
2122  ///    .version_type(version_type)
2123  ///    .wait_for_active_shards(wait_for_active_shards)
2124  ///    .body(body)
2125  ///    .send()
2126  ///    .await;
2127  /// ```
2128  pub fn index_put_with_id(&self) -> builder::IndexPutWithId {
2129    builder::IndexPutWithId::new(self)
2130  }
2131
2132  ///Creates or updates a document in an index.
2133  ///
2134  ///Sends a `POST` request to `/{index}/_doc/{id}`
2135  ///
2136  ///Arguments:
2137  /// - `index`: Index name.
2138  /// - `id`: Document ID.
2139  /// - `if_primary_term`: only perform the operation if the last operation that
2140  ///   has changed the document has the specified primary term.
2141  /// - `if_seq_no`: only perform the operation if the last operation that has
2142  ///   changed the document has the specified sequence number.
2143  /// - `op_type`: Explicit operation type. Defaults to `index` for requests
2144  ///   with an explicit document ID, and to `create`for requests without an
2145  ///   explicit document ID.
2146  /// - `pipeline`: The pipeline id to preprocess incoming documents with.
2147  /// - `refresh`: If `true` then refresh the affected shards to make this
2148  ///   operation visible to search, if `wait_for` then wait for a refresh to
2149  ///   make this operation visible to search, if `false` (the default) then do
2150  ///   nothing with refreshes.
2151  /// - `require_alias`: When true, requires destination to be an alias.
2152  /// - `routing`: Routing value.
2153  /// - `timeout`: Operation timeout.
2154  /// - `version`: Explicit version number for concurrency control.
2155  /// - `version_type`: Specific version type.
2156  /// - `wait_for_active_shards`: Sets the number of shard copies that must be
2157  ///   active before proceeding with the operation. Defaults to 1, meaning the
2158  ///   primary shard only. Set to `all` for all shard copies, otherwise set to
2159  ///   any non-negative value less than or equal to the total number of copies
2160  ///   for the shard (number of replicas + 1).
2161  /// - `body`
2162  ///```ignore
2163  /// let response = client.index_post_with_id()
2164  ///    .index(index)
2165  ///    .id(id)
2166  ///    .if_primary_term(if_primary_term)
2167  ///    .if_seq_no(if_seq_no)
2168  ///    .op_type(op_type)
2169  ///    .pipeline(pipeline)
2170  ///    .refresh(refresh)
2171  ///    .require_alias(require_alias)
2172  ///    .routing(routing)
2173  ///    .timeout(timeout)
2174  ///    .version(version)
2175  ///    .version_type(version_type)
2176  ///    .wait_for_active_shards(wait_for_active_shards)
2177  ///    .body(body)
2178  ///    .send()
2179  ///    .await;
2180  /// ```
2181  pub fn index_post(&self) -> builder::IndexPost {
2182    builder::IndexPost::new(self)
2183  }
2184
2185  ///Removes a document from the index.
2186  ///
2187  ///Sends a `DELETE` request to `/{index}/_doc/{id}`
2188  ///
2189  ///Arguments:
2190  /// - `index`: Index name.
2191  /// - `id`: Document ID.
2192  /// - `if_primary_term`: only perform the operation if the last operation that
2193  ///   has changed the document has the specified primary term.
2194  /// - `if_seq_no`: only perform the operation if the last operation that has
2195  ///   changed the document has the specified sequence number.
2196  /// - `refresh`: If `true` then refresh the affected shards to make this
2197  ///   operation visible to search, if `wait_for` then wait for a refresh to
2198  ///   make this operation visible to search, if `false` (the default) then do
2199  ///   nothing with refreshes.
2200  /// - `routing`: Routing value.
2201  /// - `timeout`: Operation timeout.
2202  /// - `version`: Explicit version number for concurrency control.
2203  /// - `version_type`: Specific version type.
2204  /// - `wait_for_active_shards`: Sets the number of shard copies that must be
2205  ///   active before proceeding with the operation. Defaults to 1, meaning the
2206  ///   primary shard only. Set to `all` for all shard copies, otherwise set to
2207  ///   any non-negative value less than or equal to the total number of copies
2208  ///   for the shard (number of replicas + 1).
2209  ///```ignore
2210  /// let response = client.delete()
2211  ///    .index(index)
2212  ///    .id(id)
2213  ///    .if_primary_term(if_primary_term)
2214  ///    .if_seq_no(if_seq_no)
2215  ///    .refresh(refresh)
2216  ///    .routing(routing)
2217  ///    .timeout(timeout)
2218  ///    .version(version)
2219  ///    .version_type(version_type)
2220  ///    .wait_for_active_shards(wait_for_active_shards)
2221  ///    .send()
2222  ///    .await;
2223  /// ```
2224  pub fn delete(&self) -> builder::Delete {
2225    builder::Delete::new(self)
2226  }
2227
2228  ///Returns information about whether a document exists in an index.
2229  ///
2230  ///Sends a `HEAD` request to `/{index}/_doc/{id}`
2231  ///
2232  ///Arguments:
2233  /// - `index`: Index name.
2234  /// - `id`: Document ID.
2235  /// - `source`: True or false to return the _source field or not, or a list of
2236  ///   fields to return.
2237  /// - `source_excludes`: List of fields to exclude from the returned _source
2238  ///   field.
2239  /// - `source_includes`: List of fields to extract and return from the _source
2240  ///   field.
2241  /// - `preference`: Specify the node or shard the operation should be
2242  ///   performed on.
2243  /// - `realtime`: Specify whether to perform the operation in realtime or
2244  ///   search mode.
2245  /// - `refresh`: Refresh the shard containing the document before performing
2246  ///   the operation.
2247  /// - `routing`: Routing value.
2248  /// - `stored_fields`: Comma-separated list of stored fields to return.
2249  /// - `version`: Explicit version number for concurrency control.
2250  /// - `version_type`: Specific version type.
2251  ///```ignore
2252  /// let response = client.exists()
2253  ///    .index(index)
2254  ///    .id(id)
2255  ///    .source(source)
2256  ///    .source_excludes(source_excludes)
2257  ///    .source_includes(source_includes)
2258  ///    .preference(preference)
2259  ///    .realtime(realtime)
2260  ///    .refresh(refresh)
2261  ///    .routing(routing)
2262  ///    .stored_fields(stored_fields)
2263  ///    .version(version)
2264  ///    .version_type(version_type)
2265  ///    .send()
2266  ///    .await;
2267  /// ```
2268  pub fn exists(&self) -> builder::Exists {
2269    builder::Exists::new(self)
2270  }
2271
2272  ///Returns information about why a specific matches (or doesn't match) a
2273  /// query.
2274  ///
2275  ///Sends a `POST` request to `/{index}/_explain/{id}`
2276  ///
2277  ///Arguments:
2278  /// - `index`: Index name.
2279  /// - `id`: Document ID.
2280  /// - `source`: True or false to return the _source field or not, or a list of
2281  ///   fields to return.
2282  /// - `source_excludes`: List of fields to exclude from the returned _source
2283  ///   field.
2284  /// - `source_includes`: List of fields to extract and return from the _source
2285  ///   field.
2286  /// - `analyze_wildcard`: Specify whether wildcards and prefix queries in the
2287  ///   query string query should be analyzed.
2288  /// - `analyzer`: The analyzer to use for the query string.
2289  /// - `default_operator`: The default operator for query string query (AND or
2290  ///   OR).
2291  /// - `df`: The default field for query string query.
2292  /// - `lenient`: Specify whether format-based query failures (such as
2293  ///   providing text to a numeric field) should be ignored.
2294  /// - `preference`: Specify the node or shard the operation should be
2295  ///   performed on.
2296  /// - `q`: Query in the Lucene query string syntax.
2297  /// - `routing`: Routing value.
2298  /// - `stored_fields`: Comma-separated list of stored fields to return.
2299  /// - `body`
2300  ///```ignore
2301  /// let response = client.explain()
2302  ///    .index(index)
2303  ///    .id(id)
2304  ///    .source(source)
2305  ///    .source_excludes(source_excludes)
2306  ///    .source_includes(source_includes)
2307  ///    .analyze_wildcard(analyze_wildcard)
2308  ///    .analyzer(analyzer)
2309  ///    .default_operator(default_operator)
2310  ///    .df(df)
2311  ///    .lenient(lenient)
2312  ///    .preference(preference)
2313  ///    .q(q)
2314  ///    .routing(routing)
2315  ///    .stored_fields(stored_fields)
2316  ///    .body(body)
2317  ///    .send()
2318  ///    .await;
2319  /// ```
2320  pub fn explain(&self) -> builder::ExplainPost {
2321    builder::ExplainPost::new(self)
2322  }
2323
2324  ///Returns the information about the capabilities of fields among multiple
2325  /// indices.
2326  ///
2327  ///Sends a `GET` request to `/{index}/_field_caps`
2328  ///
2329  ///Arguments:
2330  /// - `index`: Comma-separated list of indices; use `_all` or empty string to
2331  ///   perform the operation on all indices.
2332  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
2333  ///   resolves into no concrete indices. (This includes `_all` string or when
2334  ///   no indices have been specified).
2335  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
2336  ///   indices that are open, closed or both.
2337  /// - `fields`: Comma-separated list of field names.
2338  /// - `ignore_unavailable`: Whether specified concrete indices should be
2339  ///   ignored when unavailable (missing or closed).
2340  /// - `include_unmapped`: Indicates whether unmapped fields should be included
2341  ///   in the response.
2342  ///```ignore
2343  /// let response = client.field_caps_get_with_index()
2344  ///    .index(index)
2345  ///    .allow_no_indices(allow_no_indices)
2346  ///    .expand_wildcards(expand_wildcards)
2347  ///    .fields(fields)
2348  ///    .ignore_unavailable(ignore_unavailable)
2349  ///    .include_unmapped(include_unmapped)
2350  ///    .send()
2351  ///    .await;
2352  /// ```
2353  pub fn field_caps_get_with_index(&self) -> builder::FieldCapsGetWithIndex {
2354    builder::FieldCapsGetWithIndex::new(self)
2355  }
2356
2357  ///Returns the information about the capabilities of fields among multiple
2358  /// indices.
2359  ///
2360  ///Sends a `POST` request to `/{index}/_field_caps`
2361  ///
2362  ///Arguments:
2363  /// - `index`: Comma-separated list of indices; use `_all` or empty string to
2364  ///   perform the operation on all indices.
2365  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
2366  ///   resolves into no concrete indices. (This includes `_all` string or when
2367  ///   no indices have been specified).
2368  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
2369  ///   indices that are open, closed or both.
2370  /// - `fields`: Comma-separated list of field names.
2371  /// - `ignore_unavailable`: Whether specified concrete indices should be
2372  ///   ignored when unavailable (missing or closed).
2373  /// - `include_unmapped`: Indicates whether unmapped fields should be included
2374  ///   in the response.
2375  /// - `body`
2376  ///```ignore
2377  /// let response = client.field_caps_post_with_index()
2378  ///    .index(index)
2379  ///    .allow_no_indices(allow_no_indices)
2380  ///    .expand_wildcards(expand_wildcards)
2381  ///    .fields(fields)
2382  ///    .ignore_unavailable(ignore_unavailable)
2383  ///    .include_unmapped(include_unmapped)
2384  ///    .body(body)
2385  ///    .send()
2386  ///    .await;
2387  /// ```
2388  pub fn field_caps_post_with_index(&self) -> builder::FieldCapsPostWithIndex {
2389    builder::FieldCapsPostWithIndex::new(self)
2390  }
2391
2392  ///Allows to get multiple documents in one request.
2393  ///
2394  ///Sends a `GET` request to `/{index}/_mget`
2395  ///
2396  ///Arguments:
2397  /// - `index`: Index name.
2398  /// - `source`: True or false to return the _source field or not, or a list of
2399  ///   fields to return.
2400  /// - `source_excludes`: List of fields to exclude from the returned _source
2401  ///   field.
2402  /// - `source_includes`: List of fields to extract and return from the _source
2403  ///   field.
2404  /// - `preference`: Specify the node or shard the operation should be
2405  ///   performed on.
2406  /// - `realtime`: Specify whether to perform the operation in realtime or
2407  ///   search mode.
2408  /// - `refresh`: Refresh the shard containing the document before performing
2409  ///   the operation.
2410  /// - `routing`: Routing value.
2411  /// - `stored_fields`: Comma-separated list of stored fields to return.
2412  ///```ignore
2413  /// let response = client.mget_get_with_index()
2414  ///    .index(index)
2415  ///    .source(source)
2416  ///    .source_excludes(source_excludes)
2417  ///    .source_includes(source_includes)
2418  ///    .preference(preference)
2419  ///    .realtime(realtime)
2420  ///    .refresh(refresh)
2421  ///    .routing(routing)
2422  ///    .stored_fields(stored_fields)
2423  ///    .send()
2424  ///    .await;
2425  /// ```
2426  pub fn mget_get_with_index(&self) -> builder::MgetGetWithIndex {
2427    builder::MgetGetWithIndex::new(self)
2428  }
2429
2430  ///Allows to get multiple documents in one request.
2431  ///
2432  ///Sends a `POST` request to `/{index}/_mget`
2433  ///
2434  ///Arguments:
2435  /// - `index`: Index name.
2436  /// - `source`: True or false to return the _source field or not, or a list of
2437  ///   fields to return.
2438  /// - `source_excludes`: List of fields to exclude from the returned _source
2439  ///   field.
2440  /// - `source_includes`: List of fields to extract and return from the _source
2441  ///   field.
2442  /// - `preference`: Specify the node or shard the operation should be
2443  ///   performed on.
2444  /// - `realtime`: Specify whether to perform the operation in realtime or
2445  ///   search mode.
2446  /// - `refresh`: Refresh the shard containing the document before performing
2447  ///   the operation.
2448  /// - `routing`: Routing value.
2449  /// - `stored_fields`: Comma-separated list of stored fields to return.
2450  /// - `body`
2451  ///```ignore
2452  /// let response = client.mget_with_index()
2453  ///    .index(index)
2454  ///    .source(source)
2455  ///    .source_excludes(source_excludes)
2456  ///    .source_includes(source_includes)
2457  ///    .preference(preference)
2458  ///    .realtime(realtime)
2459  ///    .refresh(refresh)
2460  ///    .routing(routing)
2461  ///    .stored_fields(stored_fields)
2462  ///    .body(body)
2463  ///    .send()
2464  ///    .await;
2465  /// ```
2466  pub fn mget_with_index(&self) -> builder::MgetWithIndex {
2467    builder::MgetWithIndex::new(self)
2468  }
2469
2470  ///Allows to execute several search operations in one request.
2471  ///
2472  ///Sends a `POST` request to `/{index}/_msearch`
2473  ///
2474  ///Arguments:
2475  /// - `index`: Comma-separated list of indices to use as default.
2476  /// - `ccs_minimize_roundtrips`: Indicates whether network round-trips should
2477  ///   be minimized as part of cross-cluster search requests execution.
2478  /// - `max_concurrent_searches`: Controls the maximum number of concurrent
2479  ///   searches the multi search api will execute.
2480  /// - `max_concurrent_shard_requests`: The number of concurrent shard requests
2481  ///   each sub search executes concurrently per node. This value should be
2482  ///   used to limit the impact of the search on the cluster in order to limit
2483  ///   the number of concurrent shard requests.
2484  /// - `pre_filter_shard_size`: Threshold that enforces a pre-filter round-trip
2485  ///   to prefilter search shards based on query rewriting if the number of
2486  ///   shards the search request expands to exceeds the threshold. This filter
2487  ///   round-trip can limit the number of shards significantly if for instance
2488  ///   a shard can not match any documents based on its rewrite method ie. if
2489  ///   date filters are mandatory to match but the shard bounds and the query
2490  ///   are disjoint.
2491  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
2492  ///   rendered as an integer or an object in the rest search response.
2493  /// - `search_type`: Search operation type.
2494  /// - `typed_keys`: Specify whether aggregation and suggester names should be
2495  ///   prefixed by their respective types in the response.
2496  /// - `body`
2497  ///```ignore
2498  /// let response = client.msearch_post_with_index()
2499  ///    .index(index)
2500  ///    .ccs_minimize_roundtrips(ccs_minimize_roundtrips)
2501  ///    .max_concurrent_searches(max_concurrent_searches)
2502  ///    .max_concurrent_shard_requests(max_concurrent_shard_requests)
2503  ///    .pre_filter_shard_size(pre_filter_shard_size)
2504  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
2505  ///    .search_type(search_type)
2506  ///    .typed_keys(typed_keys)
2507  ///    .body(body)
2508  ///    .send()
2509  ///    .await;
2510  /// ```
2511  pub fn msearch_post_with_index(&self) -> builder::MsearchPostWithIndex {
2512    builder::MsearchPostWithIndex::new(self)
2513  }
2514
2515  ///Allows to execute several search template operations in one request.
2516  ///
2517  ///Sends a `POST` request to `/{index}/_msearch/template`
2518  ///
2519  ///Arguments:
2520  /// - `index`: Comma-separated list of indices to use as default.
2521  /// - `ccs_minimize_roundtrips`: Indicates whether network round-trips should
2522  ///   be minimized as part of cross-cluster search requests execution.
2523  /// - `max_concurrent_searches`: Controls the maximum number of concurrent
2524  ///   searches the multi search api will execute.
2525  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
2526  ///   rendered as an integer or an object in the rest search response.
2527  /// - `search_type`: Search operation type.
2528  /// - `typed_keys`: Specify whether aggregation and suggester names should be
2529  ///   prefixed by their respective types in the response.
2530  /// - `body`
2531  ///```ignore
2532  /// let response = client.msearch_template_with_index()
2533  ///    .index(index)
2534  ///    .ccs_minimize_roundtrips(ccs_minimize_roundtrips)
2535  ///    .max_concurrent_searches(max_concurrent_searches)
2536  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
2537  ///    .search_type(search_type)
2538  ///    .typed_keys(typed_keys)
2539  ///    .body(body)
2540  ///    .send()
2541  ///    .await;
2542  /// ```
2543  pub fn msearch_template_with_index(&self) -> builder::MsearchTemplatePostWithIndex {
2544    builder::MsearchTemplatePostWithIndex::new(self)
2545  }
2546
2547  ///Allows to evaluate the quality of ranked search results over a set of
2548  /// typical search queries.
2549  ///
2550  ///Sends a `POST` request to `/{index}/_rank_eval`
2551  ///
2552  ///Arguments:
2553  /// - `index`: Comma-separated list of indices; use `_all` or empty string to
2554  ///   perform the operation on all indices.
2555  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
2556  ///   resolves into no concrete indices. (This includes `_all` string or when
2557  ///   no indices have been specified).
2558  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
2559  ///   indices that are open, closed or both.
2560  /// - `ignore_unavailable`: Whether specified concrete indices should be
2561  ///   ignored when unavailable (missing or closed).
2562  /// - `search_type`: Search operation type.
2563  /// - `body`
2564  ///```ignore
2565  /// let response = client.rank_eval_post_with_index()
2566  ///    .index(index)
2567  ///    .allow_no_indices(allow_no_indices)
2568  ///    .expand_wildcards(expand_wildcards)
2569  ///    .ignore_unavailable(ignore_unavailable)
2570  ///    .search_type(search_type)
2571  ///    .body(body)
2572  ///    .send()
2573  ///    .await;
2574  /// ```
2575  pub fn rank_eval_post_with_index(&self) -> builder::RankEvalPostWithIndex {
2576    builder::RankEvalPostWithIndex::new(self)
2577  }
2578
2579  ///Returns results matching a query.
2580  ///
2581  ///Sends a `POST` request to `/{index}/_search`
2582  ///
2583  ///Arguments:
2584  /// - `index`: Comma-separated list of indices; use `_all` or empty string to
2585  ///   perform the operation on all indices.
2586  /// - `source`: True or false to return the _source field or not, or a list of
2587  ///   fields to return.
2588  /// - `source_excludes`: List of fields to exclude from the returned _source
2589  ///   field.
2590  /// - `source_includes`: List of fields to extract and return from the _source
2591  ///   field.
2592  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
2593  ///   resolves into no concrete indices. (This includes `_all` string or when
2594  ///   no indices have been specified).
2595  /// - `allow_partial_search_results`: Indicate if an error should be returned
2596  ///   if there is a partial search failure or timeout.
2597  /// - `analyze_wildcard`: Specify whether wildcard and prefix queries should
2598  ///   be analyzed.
2599  /// - `analyzer`: The analyzer to use for the query string.
2600  /// - `batched_reduce_size`: The number of shard results that should be
2601  ///   reduced at once on the coordinating node. This value should be used as a
2602  ///   protection mechanism to reduce the memory overhead per search request if
2603  ///   the potential number of shards in the request can be large.
2604  /// - `ccs_minimize_roundtrips`: Indicates whether network round-trips should
2605  ///   be minimized as part of cross-cluster search requests execution.
2606  /// - `default_operator`: The default operator for query string query (AND or
2607  ///   OR).
2608  /// - `df`: The field to use as default where no field prefix is given in the
2609  ///   query string.
2610  /// - `docvalue_fields`: Comma-separated list of fields to return as the
2611  ///   docvalue representation of a field for each hit.
2612  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
2613  ///   indices that are open, closed or both.
2614  /// - `explain`: Specify whether to return detailed information about score
2615  ///   computation as part of a hit.
2616  /// - `from`: Starting offset.
2617  /// - `ignore_throttled`: Whether specified concrete, expanded or aliased
2618  ///   indices should be ignored when throttled.
2619  /// - `ignore_unavailable`: Whether specified concrete indices should be
2620  ///   ignored when unavailable (missing or closed).
2621  /// - `lenient`: Specify whether format-based query failures (such as
2622  ///   providing text to a numeric field) should be ignored.
2623  /// - `max_concurrent_shard_requests`: The number of concurrent shard requests
2624  ///   per node this search executes concurrently. This value should be used to
2625  ///   limit the impact of the search on the cluster in order to limit the
2626  ///   number of concurrent shard requests.
2627  /// - `pre_filter_shard_size`: Threshold that enforces a pre-filter round-trip
2628  ///   to prefilter search shards based on query rewriting if the number of
2629  ///   shards the search request expands to exceeds the threshold. This filter
2630  ///   round-trip can limit the number of shards significantly if for instance
2631  ///   a shard can not match any documents based on its rewrite method ie. if
2632  ///   date filters are mandatory to match but the shard bounds and the query
2633  ///   are disjoint.
2634  /// - `preference`: Specify the node or shard the operation should be
2635  ///   performed on.
2636  /// - `q`: Query in the Lucene query string syntax.
2637  /// - `request_cache`: Specify if request cache should be used for this
2638  ///   request or not, defaults to index level setting.
2639  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
2640  ///   rendered as an integer or an object in the rest search response.
2641  /// - `routing`: Comma-separated list of specific routing values.
2642  /// - `scroll`: Specify how long a consistent view of the index should be
2643  ///   maintained for scrolled search.
2644  /// - `search_type`: Search operation type.
2645  /// - `seq_no_primary_term`: Specify whether to return sequence number and
2646  ///   primary term of the last modification of each hit.
2647  /// - `size`: Number of hits to return.
2648  /// - `sort`: Comma-separated list of <field>:<direction> pairs.
2649  /// - `stats`: Specific 'tag' of the request for logging and statistical
2650  ///   purposes.
2651  /// - `stored_fields`: Comma-separated list of stored fields to return.
2652  /// - `suggest_field`: Specify which field to use for suggestions.
2653  /// - `suggest_mode`: Specify suggest mode.
2654  /// - `suggest_size`: How many suggestions to return in response.
2655  /// - `suggest_text`: The source text for which the suggestions should be
2656  ///   returned.
2657  /// - `terminate_after`: The maximum number of documents to collect for each
2658  ///   shard, upon reaching which the query execution will terminate early.
2659  /// - `timeout`: Operation timeout.
2660  /// - `track_scores`: Whether to calculate and return scores even if they are
2661  ///   not used for sorting.
2662  /// - `track_total_hits`: Indicate if the number of documents that match the
2663  ///   query should be tracked.
2664  /// - `typed_keys`: Specify whether aggregation and suggester names should be
2665  ///   prefixed by their respective types in the response.
2666  /// - `version`: Whether to return document version as part of a hit.
2667  /// - `body`
2668  ///```ignore
2669  /// let response = client.search_post_with_index()
2670  ///    .index(index)
2671  ///    .source(source)
2672  ///    .source_excludes(source_excludes)
2673  ///    .source_includes(source_includes)
2674  ///    .allow_no_indices(allow_no_indices)
2675  ///    .allow_partial_search_results(allow_partial_search_results)
2676  ///    .analyze_wildcard(analyze_wildcard)
2677  ///    .analyzer(analyzer)
2678  ///    .batched_reduce_size(batched_reduce_size)
2679  ///    .ccs_minimize_roundtrips(ccs_minimize_roundtrips)
2680  ///    .default_operator(default_operator)
2681  ///    .df(df)
2682  ///    .docvalue_fields(docvalue_fields)
2683  ///    .expand_wildcards(expand_wildcards)
2684  ///    .explain(explain)
2685  ///    .from(from)
2686  ///    .ignore_throttled(ignore_throttled)
2687  ///    .ignore_unavailable(ignore_unavailable)
2688  ///    .lenient(lenient)
2689  ///    .max_concurrent_shard_requests(max_concurrent_shard_requests)
2690  ///    .pre_filter_shard_size(pre_filter_shard_size)
2691  ///    .preference(preference)
2692  ///    .q(q)
2693  ///    .request_cache(request_cache)
2694  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
2695  ///    .routing(routing)
2696  ///    .scroll(scroll)
2697  ///    .search_type(search_type)
2698  ///    .seq_no_primary_term(seq_no_primary_term)
2699  ///    .size(size)
2700  ///    .sort(sort)
2701  ///    .stats(stats)
2702  ///    .stored_fields(stored_fields)
2703  ///    .suggest_field(suggest_field)
2704  ///    .suggest_mode(suggest_mode)
2705  ///    .suggest_size(suggest_size)
2706  ///    .suggest_text(suggest_text)
2707  ///    .terminate_after(terminate_after)
2708  ///    .timeout(timeout)
2709  ///    .track_scores(track_scores)
2710  ///    .track_total_hits(track_total_hits)
2711  ///    .typed_keys(typed_keys)
2712  ///    .version(version)
2713  ///    .body(body)
2714  ///    .send()
2715  ///    .await;
2716  /// ```
2717  #[cfg(feature = "search")]
2718  pub fn search(&self) -> builder_search::SearchPostWithIndex {
2719    builder_search::SearchPostWithIndex::new(self)
2720  }
2721
2722  ///Creates point in time context.
2723  ///
2724  ///Sends a `POST` request to `/{index}/_search/point_in_time`
2725  ///
2726  ///Arguments:
2727  /// - `index`: Comma-separated list of indices; use `_all` or empty string to
2728  ///   perform the operation on all indices.
2729  /// - `allow_partial_pit_creation`: Allow if point in time can be created with
2730  ///   partial failures.
2731  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
2732  ///   indices that are open, closed or both.
2733  /// - `keep_alive`: Specify the keep alive for point in time.
2734  /// - `preference`: Specify the node or shard the operation should be
2735  ///   performed on.
2736  /// - `routing`: Comma-separated list of specific routing values.
2737  ///```ignore
2738  /// let response = client.create_pit()
2739  ///    .index(index)
2740  ///    .allow_partial_pit_creation(allow_partial_pit_creation)
2741  ///    .expand_wildcards(expand_wildcards)
2742  ///    .keep_alive(keep_alive)
2743  ///    .preference(preference)
2744  ///    .routing(routing)
2745  ///    .send()
2746  ///    .await;
2747  /// ```
2748  pub fn create_pit(&self) -> builder::CreatePit {
2749    builder::CreatePit::new(self)
2750  }
2751
2752  ///Allows to use the Mustache language to pre-render a search definition.
2753  ///
2754  ///Sends a `POST` request to `/{index}/_search/template`
2755  ///
2756  ///Arguments:
2757  /// - `index`: Comma-separated list of indices; use `_all` or empty string to
2758  ///   perform the operation on all indices.
2759  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
2760  ///   resolves into no concrete indices. (This includes `_all` string or when
2761  ///   no indices have been specified).
2762  /// - `ccs_minimize_roundtrips`: Indicates whether network round-trips should
2763  ///   be minimized as part of cross-cluster search requests execution.
2764  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
2765  ///   indices that are open, closed or both.
2766  /// - `explain`: Specify whether to return detailed information about score
2767  ///   computation as part of a hit.
2768  /// - `ignore_throttled`: Whether specified concrete, expanded or aliased
2769  ///   indices should be ignored when throttled.
2770  /// - `ignore_unavailable`: Whether specified concrete indices should be
2771  ///   ignored when unavailable (missing or closed).
2772  /// - `preference`: Specify the node or shard the operation should be
2773  ///   performed on.
2774  /// - `profile`: Specify whether to profile the query execution.
2775  /// - `rest_total_hits_as_int`: Indicates whether hits.total should be
2776  ///   rendered as an integer or an object in the rest search response.
2777  /// - `routing`: Comma-separated list of specific routing values.
2778  /// - `scroll`: Specify how long a consistent view of the index should be
2779  ///   maintained for scrolled search.
2780  /// - `search_type`: Search operation type.
2781  /// - `typed_keys`: Specify whether aggregation and suggester names should be
2782  ///   prefixed by their respective types in the response.
2783  /// - `body`
2784  ///```ignore
2785  /// let response = client.search_template_with_index()
2786  ///    .index(index)
2787  ///    .allow_no_indices(allow_no_indices)
2788  ///    .ccs_minimize_roundtrips(ccs_minimize_roundtrips)
2789  ///    .expand_wildcards(expand_wildcards)
2790  ///    .explain(explain)
2791  ///    .ignore_throttled(ignore_throttled)
2792  ///    .ignore_unavailable(ignore_unavailable)
2793  ///    .preference(preference)
2794  ///    .profile(profile)
2795  ///    .rest_total_hits_as_int(rest_total_hits_as_int)
2796  ///    .routing(routing)
2797  ///    .scroll(scroll)
2798  ///    .search_type(search_type)
2799  ///    .typed_keys(typed_keys)
2800  ///    .body(body)
2801  ///    .send()
2802  ///    .await;
2803  /// ```
2804  #[cfg(feature = "search")]
2805  pub fn search_template_with_index(&self) -> builder::SearchTemplatePostWithIndex {
2806    builder::SearchTemplatePostWithIndex::new(self)
2807  }
2808
2809  ///Returns information about the indices and shards that a search request
2810  /// would be executed against.
2811  ///
2812  ///Sends a `GET` request to `/{index}/_search_shards`
2813  ///
2814  ///Arguments:
2815  /// - `index`: Comma-separated list of indices; use `_all` or empty string to
2816  ///   perform the operation on all indices.
2817  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
2818  ///   resolves into no concrete indices. (This includes `_all` string or when
2819  ///   no indices have been specified).
2820  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
2821  ///   indices that are open, closed or both.
2822  /// - `ignore_unavailable`: Whether specified concrete indices should be
2823  ///   ignored when unavailable (missing or closed).
2824  /// - `local`: Return local information, do not retrieve the state from
2825  ///   cluster-manager node.
2826  /// - `preference`: Specify the node or shard the operation should be
2827  ///   performed on.
2828  /// - `routing`: Routing value.
2829  ///```ignore
2830  /// let response = client.search_shards_get_with_index()
2831  ///    .index(index)
2832  ///    .allow_no_indices(allow_no_indices)
2833  ///    .expand_wildcards(expand_wildcards)
2834  ///    .ignore_unavailable(ignore_unavailable)
2835  ///    .local(local)
2836  ///    .preference(preference)
2837  ///    .routing(routing)
2838  ///    .send()
2839  ///    .await;
2840  /// ```
2841  #[cfg(feature = "search")]
2842  pub fn search_shards_get_with_index(&self) -> builder::SearchShardsGetWithIndex {
2843    builder::SearchShardsGetWithIndex::new(self)
2844  }
2845
2846  ///Returns information about the indices and shards that a search request
2847  /// would be executed against.
2848  ///
2849  ///Sends a `POST` request to `/{index}/_search_shards`
2850  ///
2851  ///Arguments:
2852  /// - `index`: Comma-separated list of indices; use `_all` or empty string to
2853  ///   perform the operation on all indices.
2854  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
2855  ///   resolves into no concrete indices. (This includes `_all` string or when
2856  ///   no indices have been specified).
2857  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
2858  ///   indices that are open, closed or both.
2859  /// - `ignore_unavailable`: Whether specified concrete indices should be
2860  ///   ignored when unavailable (missing or closed).
2861  /// - `local`: Return local information, do not retrieve the state from
2862  ///   cluster-manager node.
2863  /// - `preference`: Specify the node or shard the operation should be
2864  ///   performed on.
2865  /// - `routing`: Routing value.
2866  ///```ignore
2867  /// let response = client.search_shards_post_with_index()
2868  ///    .index(index)
2869  ///    .allow_no_indices(allow_no_indices)
2870  ///    .expand_wildcards(expand_wildcards)
2871  ///    .ignore_unavailable(ignore_unavailable)
2872  ///    .local(local)
2873  ///    .preference(preference)
2874  ///    .routing(routing)
2875  ///    .send()
2876  ///    .await;
2877  /// ```
2878  #[cfg(feature = "search")]
2879  pub fn search_shards_post_with_index(&self) -> builder::SearchShardsPostWithIndex {
2880    builder::SearchShardsPostWithIndex::new(self)
2881  }
2882
2883  ///Returns the source of a document.
2884  ///
2885  ///Sends a `GET` request to `/{index}/_source/{id}`
2886  ///
2887  ///Arguments:
2888  /// - `index`: Index name.
2889  /// - `id`: Document ID.
2890  /// - `source`: True or false to return the _source field or not, or a list of
2891  ///   fields to return.
2892  /// - `source_excludes`: List of fields to exclude from the returned _source
2893  ///   field.
2894  /// - `source_includes`: List of fields to extract and return from the _source
2895  ///   field.
2896  /// - `preference`: Specify the node or shard the operation should be
2897  ///   performed on.
2898  /// - `realtime`: Specify whether to perform the operation in realtime or
2899  ///   search mode.
2900  /// - `refresh`: Refresh the shard containing the document before performing
2901  ///   the operation.
2902  /// - `routing`: Routing value.
2903  /// - `version`: Explicit version number for concurrency control.
2904  /// - `version_type`: Specific version type.
2905  ///```ignore
2906  /// let response = client.get_source()
2907  ///    .index(index)
2908  ///    .id(id)
2909  ///    .source(source)
2910  ///    .source_excludes(source_excludes)
2911  ///    .source_includes(source_includes)
2912  ///    .preference(preference)
2913  ///    .realtime(realtime)
2914  ///    .refresh(refresh)
2915  ///    .routing(routing)
2916  ///    .version(version)
2917  ///    .version_type(version_type)
2918  ///    .send()
2919  ///    .await;
2920  /// ```
2921  pub fn get_source(&self) -> builder::GetSource {
2922    builder::GetSource::new(self)
2923  }
2924
2925  ///Returns information about whether a document source exists in an index.
2926  ///
2927  ///Sends a `HEAD` request to `/{index}/_source/{id}`
2928  ///
2929  ///Arguments:
2930  /// - `index`: Index name.
2931  /// - `id`: Document ID.
2932  /// - `source`: True or false to return the _source field or not, or a list of
2933  ///   fields to return.
2934  /// - `source_excludes`: List of fields to exclude from the returned _source
2935  ///   field.
2936  /// - `source_includes`: List of fields to extract and return from the _source
2937  ///   field.
2938  /// - `preference`: Specify the node or shard the operation should be
2939  ///   performed on.
2940  /// - `realtime`: Specify whether to perform the operation in realtime or
2941  ///   search mode.
2942  /// - `refresh`: Refresh the shard containing the document before performing
2943  ///   the operation.
2944  /// - `routing`: Routing value.
2945  /// - `version`: Explicit version number for concurrency control.
2946  /// - `version_type`: Specific version type.
2947  ///```ignore
2948  /// let response = client.exists_source()
2949  ///    .index(index)
2950  ///    .id(id)
2951  ///    .source(source)
2952  ///    .source_excludes(source_excludes)
2953  ///    .source_includes(source_includes)
2954  ///    .preference(preference)
2955  ///    .realtime(realtime)
2956  ///    .refresh(refresh)
2957  ///    .routing(routing)
2958  ///    .version(version)
2959  ///    .version_type(version_type)
2960  ///    .send()
2961  ///    .await;
2962  /// ```
2963  pub fn exists_source(&self) -> builder::ExistsSource {
2964    builder::ExistsSource::new(self)
2965  }
2966
2967  ///Returns information and statistics about terms in the fields of a
2968  /// particular document.
2969  ///
2970  ///Sends a `GET` request to `/{index}/_termvectors`
2971  ///
2972  ///Arguments:
2973  /// - `index`: The index in which the document resides.
2974  /// - `field_statistics`: Specifies if document count, sum of document
2975  ///   frequencies and sum of total term frequencies should be returned.
2976  /// - `fields`: Comma-separated list of fields to return.
2977  /// - `offsets`: Specifies if term offsets should be returned.
2978  /// - `payloads`: Specifies if term payloads should be returned.
2979  /// - `positions`: Specifies if term positions should be returned.
2980  /// - `preference`: Specify the node or shard the operation should be
2981  ///   performed on.
2982  /// - `realtime`: Specifies if request is real-time as opposed to
2983  ///   near-real-time.
2984  /// - `routing`: Routing value.
2985  /// - `term_statistics`: Specifies if total term frequency and document
2986  ///   frequency should be returned.
2987  /// - `version`: Explicit version number for concurrency control.
2988  /// - `version_type`: Specific version type.
2989  ///```ignore
2990  /// let response = client.termvectors_get()
2991  ///    .index(index)
2992  ///    .field_statistics(field_statistics)
2993  ///    .fields(fields)
2994  ///    .offsets(offsets)
2995  ///    .payloads(payloads)
2996  ///    .positions(positions)
2997  ///    .preference(preference)
2998  ///    .realtime(realtime)
2999  ///    .routing(routing)
3000  ///    .term_statistics(term_statistics)
3001  ///    .version(version)
3002  ///    .version_type(version_type)
3003  ///    .send()
3004  ///    .await;
3005  /// ```
3006  pub fn termvectors_get(&self) -> builder::TermvectorsGet {
3007    builder::TermvectorsGet::new(self)
3008  }
3009
3010  ///Returns information and statistics about terms in the fields of a
3011  /// particular document.
3012  ///
3013  ///Sends a `POST` request to `/{index}/_termvectors`
3014  ///
3015  ///Arguments:
3016  /// - `index`: The index in which the document resides.
3017  /// - `field_statistics`: Specifies if document count, sum of document
3018  ///   frequencies and sum of total term frequencies should be returned.
3019  /// - `fields`: Comma-separated list of fields to return.
3020  /// - `offsets`: Specifies if term offsets should be returned.
3021  /// - `payloads`: Specifies if term payloads should be returned.
3022  /// - `positions`: Specifies if term positions should be returned.
3023  /// - `preference`: Specify the node or shard the operation should be
3024  ///   performed on.
3025  /// - `realtime`: Specifies if request is real-time as opposed to
3026  ///   near-real-time.
3027  /// - `routing`: Routing value.
3028  /// - `term_statistics`: Specifies if total term frequency and document
3029  ///   frequency should be returned.
3030  /// - `version`: Explicit version number for concurrency control.
3031  /// - `version_type`: Specific version type.
3032  /// - `body`
3033  ///```ignore
3034  /// let response = client.termvectors_post()
3035  ///    .index(index)
3036  ///    .field_statistics(field_statistics)
3037  ///    .fields(fields)
3038  ///    .offsets(offsets)
3039  ///    .payloads(payloads)
3040  ///    .positions(positions)
3041  ///    .preference(preference)
3042  ///    .realtime(realtime)
3043  ///    .routing(routing)
3044  ///    .term_statistics(term_statistics)
3045  ///    .version(version)
3046  ///    .version_type(version_type)
3047  ///    .body(body)
3048  ///    .send()
3049  ///    .await;
3050  /// ```
3051  pub fn termvectors_post(&self) -> builder::TermvectorsPost {
3052    builder::TermvectorsPost::new(self)
3053  }
3054
3055  ///Returns information and statistics about terms in the fields of a
3056  /// particular document.
3057  ///
3058  ///Sends a `GET` request to `/{index}/_termvectors/{id}`
3059  ///
3060  ///Arguments:
3061  /// - `index`: The index in which the document resides.
3062  /// - `id`: Document ID. When not specified a doc param should be supplied.
3063  /// - `field_statistics`: Specifies if document count, sum of document
3064  ///   frequencies and sum of total term frequencies should be returned.
3065  /// - `fields`: Comma-separated list of fields to return.
3066  /// - `offsets`: Specifies if term offsets should be returned.
3067  /// - `payloads`: Specifies if term payloads should be returned.
3068  /// - `positions`: Specifies if term positions should be returned.
3069  /// - `preference`: Specify the node or shard the operation should be
3070  ///   performed on.
3071  /// - `realtime`: Specifies if request is real-time as opposed to
3072  ///   near-real-time.
3073  /// - `routing`: Routing value.
3074  /// - `term_statistics`: Specifies if total term frequency and document
3075  ///   frequency should be returned.
3076  /// - `version`: Explicit version number for concurrency control.
3077  /// - `version_type`: Specific version type.
3078  ///```ignore
3079  /// let response = client.termvectors_get_with_id()
3080  ///    .index(index)
3081  ///    .id(id)
3082  ///    .field_statistics(field_statistics)
3083  ///    .fields(fields)
3084  ///    .offsets(offsets)
3085  ///    .payloads(payloads)
3086  ///    .positions(positions)
3087  ///    .preference(preference)
3088  ///    .realtime(realtime)
3089  ///    .routing(routing)
3090  ///    .term_statistics(term_statistics)
3091  ///    .version(version)
3092  ///    .version_type(version_type)
3093  ///    .send()
3094  ///    .await;
3095  /// ```
3096  pub fn termvectors_get_with_id(&self) -> builder::TermvectorsGetWithId {
3097    builder::TermvectorsGetWithId::new(self)
3098  }
3099
3100  ///Returns information and statistics about terms in the fields of a
3101  /// particular document.
3102  ///
3103  ///Sends a `POST` request to `/{index}/_termvectors/{id}`
3104  ///
3105  ///Arguments:
3106  /// - `index`: The index in which the document resides.
3107  /// - `id`: Document ID. When not specified a doc param should be supplied.
3108  /// - `field_statistics`: Specifies if document count, sum of document
3109  ///   frequencies and sum of total term frequencies should be returned.
3110  /// - `fields`: Comma-separated list of fields to return.
3111  /// - `offsets`: Specifies if term offsets should be returned.
3112  /// - `payloads`: Specifies if term payloads should be returned.
3113  /// - `positions`: Specifies if term positions should be returned.
3114  /// - `preference`: Specify the node or shard the operation should be
3115  ///   performed on.
3116  /// - `realtime`: Specifies if request is real-time as opposed to
3117  ///   near-real-time.
3118  /// - `routing`: Routing value.
3119  /// - `term_statistics`: Specifies if total term frequency and document
3120  ///   frequency should be returned.
3121  /// - `version`: Explicit version number for concurrency control.
3122  /// - `version_type`: Specific version type.
3123  /// - `body`
3124  ///```ignore
3125  /// let response = client.termvectors_post_with_id()
3126  ///    .index(index)
3127  ///    .id(id)
3128  ///    .field_statistics(field_statistics)
3129  ///    .fields(fields)
3130  ///    .offsets(offsets)
3131  ///    .payloads(payloads)
3132  ///    .positions(positions)
3133  ///    .preference(preference)
3134  ///    .realtime(realtime)
3135  ///    .routing(routing)
3136  ///    .term_statistics(term_statistics)
3137  ///    .version(version)
3138  ///    .version_type(version_type)
3139  ///    .body(body)
3140  ///    .send()
3141  ///    .await;
3142  /// ```
3143  pub fn termvectors_post_with_id(&self) -> builder::TermvectorsPostWithId {
3144    builder::TermvectorsPostWithId::new(self)
3145  }
3146
3147  ///Updates a document with a script or partial document.
3148  ///
3149  ///Sends a `POST` request to `/{index}/_update/{id}`
3150  ///
3151  ///Arguments:
3152  /// - `index`: Index name.
3153  /// - `id`: Document ID.
3154  /// - `source`: True or false to return the _source field or not, or a list of
3155  ///   fields to return.
3156  /// - `source_excludes`: List of fields to exclude from the returned _source
3157  ///   field.
3158  /// - `source_includes`: List of fields to extract and return from the _source
3159  ///   field.
3160  /// - `if_primary_term`: only perform the operation if the last operation that
3161  ///   has changed the document has the specified primary term.
3162  /// - `if_seq_no`: only perform the operation if the last operation that has
3163  ///   changed the document has the specified sequence number.
3164  /// - `lang`: The script language.
3165  /// - `refresh`: If `true` then refresh the affected shards to make this
3166  ///   operation visible to search, if `wait_for` then wait for a refresh to
3167  ///   make this operation visible to search, if `false` (the default) then do
3168  ///   nothing with refreshes.
3169  /// - `require_alias`: When true, requires destination to be an alias.
3170  /// - `retry_on_conflict`: Specify how many times should the operation be
3171  ///   retried when a conflict occurs.
3172  /// - `routing`: Routing value.
3173  /// - `timeout`: Operation timeout.
3174  /// - `wait_for_active_shards`: Sets the number of shard copies that must be
3175  ///   active before proceeding with the operation. Defaults to 1, meaning the
3176  ///   primary shard only. Set to `all` for all shard copies, otherwise set to
3177  ///   any non-negative value less than or equal to the total number of copies
3178  ///   for the shard (number of replicas + 1).
3179  /// - `body`
3180  ///```ignore
3181  /// let response = client.update()
3182  ///    .index(index)
3183  ///    .id(id)
3184  ///    .source(source)
3185  ///    .source_excludes(source_excludes)
3186  ///    .source_includes(source_includes)
3187  ///    .if_primary_term(if_primary_term)
3188  ///    .if_seq_no(if_seq_no)
3189  ///    .lang(lang)
3190  ///    .refresh(refresh)
3191  ///    .require_alias(require_alias)
3192  ///    .retry_on_conflict(retry_on_conflict)
3193  ///    .routing(routing)
3194  ///    .timeout(timeout)
3195  ///    .wait_for_active_shards(wait_for_active_shards)
3196  ///    .body(body)
3197  ///    .send()
3198  ///    .await;
3199  /// ```
3200  pub fn update(&self) -> builder::Update {
3201    builder::Update::new(self)
3202  }
3203
3204  ///Performs an update on every document in the index without changing the
3205  /// source, for example to pick up a mapping change.
3206  ///
3207  ///Sends a `POST` request to `/{index}/_update_by_query`
3208  ///
3209  ///Arguments:
3210  /// - `index`: Comma-separated list of indices; use `_all` or empty string to
3211  ///   perform the operation on all indices.
3212  /// - `source`: True or false to return the _source field or not, or a list of
3213  ///   fields to return.
3214  /// - `source_excludes`: List of fields to exclude from the returned _source
3215  ///   field.
3216  /// - `source_includes`: List of fields to extract and return from the _source
3217  ///   field.
3218  /// - `allow_no_indices`: Whether to ignore if a wildcard indices expression
3219  ///   resolves into no concrete indices. (This includes `_all` string or when
3220  ///   no indices have been specified).
3221  /// - `analyze_wildcard`: Specify whether wildcard and prefix queries should
3222  ///   be analyzed.
3223  /// - `analyzer`: The analyzer to use for the query string.
3224  /// - `conflicts`: What to do when the operation encounters version
3225  ///   conflicts?.
3226  /// - `default_operator`: The default operator for query string query (AND or
3227  ///   OR).
3228  /// - `df`: The field to use as default where no field prefix is given in the
3229  ///   query string.
3230  /// - `expand_wildcards`: Whether to expand wildcard expression to concrete
3231  ///   indices that are open, closed or both.
3232  /// - `from`: Starting offset.
3233  /// - `ignore_unavailable`: Whether specified concrete indices should be
3234  ///   ignored when unavailable (missing or closed).
3235  /// - `lenient`: Specify whether format-based query failures (such as
3236  ///   providing text to a numeric field) should be ignored.
3237  /// - `max_docs`: Maximum number of documents to process (default: all
3238  ///   documents).
3239  /// - `pipeline`: The pipeline id to preprocess incoming documents with.
3240  /// - `preference`: Specify the node or shard the operation should be
3241  ///   performed on.
3242  /// - `q`: Query in the Lucene query string syntax.
3243  /// - `refresh`: Should the affected indexes be refreshed?.
3244  /// - `request_cache`: Specify if request cache should be used for this
3245  ///   request or not, defaults to index level setting.
3246  /// - `requests_per_second`: The throttle for this request in sub-requests per
3247  ///   second. -1 means no throttle.
3248  /// - `routing`: Comma-separated list of specific routing values.
3249  /// - `scroll`: Specify how long a consistent view of the index should be
3250  ///   maintained for scrolled search.
3251  /// - `scroll_size`: Size on the scroll request powering the operation.
3252  /// - `search_timeout`: Explicit timeout for each search request. Defaults to
3253  ///   no timeout.
3254  /// - `search_type`: Search operation type.
3255  /// - `size`: Deprecated, please use `max_docs` instead.
3256  /// - `slices`: The number of slices this task should be divided into.
3257  ///   Defaults to 1, meaning the task isn't sliced into subtasks. Can be set
3258  ///   to `auto`.
3259  /// - `sort`: Comma-separated list of <field>:<direction> pairs.
3260  /// - `stats`: Specific 'tag' of the request for logging and statistical
3261  ///   purposes.
3262  /// - `terminate_after`: The maximum number of documents to collect for each
3263  ///   shard, upon reaching which the query execution will terminate early.
3264  /// - `timeout`: Time each individual bulk request should wait for shards that
3265  ///   are unavailable.
3266  /// - `version`: Whether to return document version as part of a hit.
3267  /// - `wait_for_active_shards`: Sets the number of shard copies that must be
3268  ///   active before proceeding with the operation. Defaults to 1, meaning the
3269  ///   primary shard only. Set to `all` for all shard copies, otherwise set to
3270  ///   any non-negative value less than or equal to the total number of copies
3271  ///   for the shard (number of replicas + 1).
3272  /// - `wait_for_completion`: Should this request wait until the operation has
3273  ///   completed before returning.
3274  /// - `body`
3275  ///```ignore
3276  /// let response = client.update_by_query()
3277  ///    .index(index)
3278  ///    .source(source)
3279  ///    .source_excludes(source_excludes)
3280  ///    .source_includes(source_includes)
3281  ///    .allow_no_indices(allow_no_indices)
3282  ///    .analyze_wildcard(analyze_wildcard)
3283  ///    .analyzer(analyzer)
3284  ///    .conflicts(conflicts)
3285  ///    .default_operator(default_operator)
3286  ///    .df(df)
3287  ///    .expand_wildcards(expand_wildcards)
3288  ///    .from(from)
3289  ///    .ignore_unavailable(ignore_unavailable)
3290  ///    .lenient(lenient)
3291  ///    .max_docs(max_docs)
3292  ///    .pipeline(pipeline)
3293  ///    .preference(preference)
3294  ///    .q(q)
3295  ///    .refresh(refresh)
3296  ///    .request_cache(request_cache)
3297  ///    .requests_per_second(requests_per_second)
3298  ///    .routing(routing)
3299  ///    .scroll(scroll)
3300  ///    .scroll_size(scroll_size)
3301  ///    .search_timeout(search_timeout)
3302  ///    .search_type(search_type)
3303  ///    .size(size)
3304  ///    .slices(slices)
3305  ///    .sort(sort)
3306  ///    .stats(stats)
3307  ///    .terminate_after(terminate_after)
3308  ///    .timeout(timeout)
3309  ///    .version(version)
3310  ///    .wait_for_active_shards(wait_for_active_shards)
3311  ///    .wait_for_completion(wait_for_completion)
3312  ///    .body(body)
3313  ///    .send()
3314  ///    .await;
3315  /// ```
3316  pub fn update_by_query(&self) -> builder::UpdateByQuery {
3317    builder::UpdateByQuery::new(self)
3318  }
3319
3320  /// Sends a bulk index request to OpenSearch with the specified index, id and
3321  /// document body.
3322  ///
3323  /// # Arguments
3324  ///
3325  /// * `index` - A string slice that holds the name of the index.
3326  /// * `id` - An optional string slice that holds the id of the document.
3327  /// * `body` - A reference to a serializable document body.
3328  ///
3329  /// # Returns
3330  ///
3331  /// Returns a Result containing a serde_json::Value representing the response
3332  /// from OpenSearch or an Error if the request fails.
3333  ///
3334  /// # Example
3335  ///
3336  /// ```
3337  /// use opensearch_client::OpenSearchClient;
3338  ///
3339  /// #[derive(Serialize)]
3340  /// struct MyDocument {
3341  ///   title: String,
3342  ///   content: String,
3343  /// }
3344  ///
3345  /// #[tokio::main]
3346  /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
3347  ///   let client = OpenSearchClient::new("http://localhost:9200");
3348  ///   let document = MyDocument {
3349  ///     title: "My Title".to_string(),
3350  ///     content: "My Content".to_string(),
3351  ///   };
3352  ///   let response = client
3353  ///     .bulk_index_document("my_index", Some("my_id".to_string()), &document)
3354  ///     .await?;
3355  ///   Ok(())
3356  /// }
3357  /// ```
3358  pub async fn bulk_index_document<T: Serialize>(
3359    &self,
3360    index: &str,
3361    id: Option<String>,
3362    body: &T,
3363  ) -> Result<(), Error> {
3364    let body_json = serde_json::to_value(body)?;
3365    let action = BulkAction::Index(IndexAction {
3366      index: index.to_owned(),
3367      id: id.clone(),
3368      pipeline: None,
3369    });
3370    self.bulk_action(action, Some(&body_json)).await
3371  }
3372
3373  /// Sends a bulk action to the OpenSearch server.
3374  ///
3375  /// # Arguments
3376  ///
3377  /// * `command` - A string slice that holds the command to be executed.
3378  /// * `action` - A `BulkAction` enum that specifies the action to be taken.
3379  /// * `body` - An optional `serde_json::Value` that holds the request body.
3380  ///
3381  /// # Returns
3382  ///
3383  /// A `Result` containing a `serde_json::Value` object representing the
3384  /// response from the server, or an `Error` if the request failed.
3385  ///
3386  /// # Examples
3387  ///
3388  /// ```
3389  /// use opensearch_client::{BulkAction, OpenSearchClient};
3390  ///
3391  /// #[tokio::main]
3392  /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
3393  ///   let client = OpenSearchClient::new("http://localhost:9200")?;
3394  ///   let action = BulkAction::Index {
3395  ///     index: "my_index".to_string(),
3396  ///     id: Some("1".to_string()),
3397  ///   };
3398  ///   let response = client.bulk_action("index", action, None).await?;
3399  ///   Ok(())
3400  /// }
3401  /// ```
3402  pub async fn bulk_action(&self, action: BulkAction, body: Option<&serde_json::Value>) -> Result<(), Error> {
3403    let j = serde_json::to_string(&action)?;
3404    let bulker_arc = Arc::clone(&self.bulker);
3405    let mut bulker = bulker_arc.lock().unwrap();
3406    bulker.push_str(j.as_str());
3407    bulker.push('\n');
3408    match body {
3409      None => {}
3410      Some(js) => {
3411        let j = serde_json::to_string(js)?;
3412        bulker.push_str(j.as_str());
3413        bulker.push('\n');
3414      }
3415    }
3416
3417    let bulker_size_arc = Arc::clone(&self.bulker_size);
3418    let mut bulker_size = bulker_size_arc.lock().unwrap();
3419    *bulker_size += 1;
3420    if *bulker_size >= self.max_bulk_size {
3421      drop(bulker_size);
3422      drop(bulker);
3423      self.flush_bulk().await?;
3424    }
3425    Ok(())
3426  }
3427
3428  /// Sends a bulk create request to the OpenSearch cluster with the specified
3429  /// index, id and body.
3430  ///
3431  /// # Arguments
3432  ///
3433  /// * `index` - A string slice that holds the name of the index.
3434  /// * `id` - A string slice that holds the id of the document.
3435  /// * `body` - A generic type `T` that holds the body of the document to be
3436  ///   created.
3437  ///
3438  /// # Returns
3439  ///
3440  /// Returns a `Result` containing a `serde_json::Value` on success, or an
3441  /// `Error` on failure.
3442  pub async fn bulk_create_document<T: Serialize>(&self, index: &str, id: &str, body: &T) -> Result<(), Error> {
3443    let body_json = serde_json::to_value(body)?;
3444
3445    let action = BulkAction::Create(CreateAction {
3446      index: index.to_owned(),
3447      id: id.to_owned(),
3448      ..Default::default()
3449    });
3450
3451    self.bulk_action(action, Some(&body_json)).await
3452  }
3453
3454  /// Asynchronously updates a document in bulk.
3455  ///
3456  /// # Arguments
3457  ///
3458  /// * `index` - A string slice that holds the name of the index.
3459  /// * `id` - A string slice that holds the ID of the document to update.
3460  /// * `body` - An `UpdateAction` struct that holds the update action to
3461  ///   perform.
3462  ///
3463  /// # Returns
3464  ///
3465  /// Returns a `Result` containing a `serde_json::Value` on success, or an
3466  /// `Error` on failure.
3467  pub async fn bulk_update_document(&self, index: &str, id: &str, body: &UpdateActionBody) -> Result<(), Error> {
3468    let action = BulkAction::Update(UpdateAction {
3469      index: index.to_owned(),
3470      id: id.to_owned(),
3471      ..Default::default()
3472    });
3473    let j = serde_json::to_value(body)?;
3474    self.bulk_action(action, Some(&j)).await
3475  }
3476
3477  /// Sends a bulk request to the OpenSearch server and returns a
3478  /// `BulkResponse`. If the bulker size is 0, it returns an empty
3479  /// `BulkResponse`. If the bulk request contains errors, it logs the errors
3480  /// and returns the `BulkResponse`.
3481  ///
3482  /// # Examples
3483  ///
3484  /// ```no_run
3485  /// use opensearch_client::OpenSearchClient;
3486  ///
3487  /// #[tokio::main]
3488  /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
3489  ///   let client = OpenSearchClient::new("http://localhost:9200", "user", "password");
3490  ///   let response = client.flush_bulk().await?;
3491  ///   println!("{:?}", response);
3492  ///   Ok(())
3493  /// }
3494  /// ```
3495  pub async fn flush_bulk(&self) -> Result<BulkResponse, Error> {
3496    let bulker_size_arc = Arc::clone(&self.bulker_size);
3497    let mut bulker_size = bulker_size_arc.lock().unwrap();
3498    if *bulker_size > 0 {
3499      let bulker_arc = Arc::clone(&self.bulker);
3500      let mut bulker = bulker_arc.lock().unwrap();
3501
3502      // let request_url = format!("{}_bulk", self.server);
3503
3504      match self.bulk().body(bulker.to_owned()).send().await
3505        // .client
3506        // .post(request_url)
3507        // .basic_auth(self.user.as_str(), Some(self.password.as_str()))
3508        // .body()
3509        // .header("Content-Type", "application/x-ndjson")
3510        // .send()
3511        // .await
3512      {
3513        Ok(response) => {
3514          let result: BulkResponse = response.into_inner();
3515          *bulker = String::new();
3516          *bulker_size = 0;
3517          // debug!("{:?}", &result);
3518          if result.errors {
3519            for map in &result.items {
3520              for (_, value) in map.iter() {
3521                if let Some(error) = &value.error {
3522                  if !error.kind.eq_ignore_ascii_case("version_conflict_engine_exception") {
3523                    info!("{:?}", &value);
3524                  }
3525                }
3526              }
3527            }
3528          }
3529
3530          Ok(result)
3531        }
3532        Err(err) => {
3533          println!("{:?}", &err);
3534          Err(err)
3535        }
3536      }
3537    } else {
3538      Ok(BulkResponse {
3539        took: 0,
3540        errors: false,
3541        items: vec![],
3542      })
3543    }
3544  }
3545
3546  /// Indexes a document in the specified index with the given body and optional
3547  /// ID.
3548  ///
3549  /// # Arguments
3550  ///
3551  /// * `index` - A string slice that holds the name of the index to which the
3552  ///   document will be added.
3553  /// * `body` - A reference to a serializable object that represents the
3554  ///   document to be added.
3555  /// * `id` - An optional string slice that holds the ID of the document to be
3556  ///   added. If not provided, a new ID will be generated.
3557  ///
3558  /// # Returns
3559  ///
3560  /// A `Result` containing an `IndexResponse` object if the operation was
3561  /// successful, or an `Error` if an error occurred.
3562  ///
3563  /// # Examples
3564  ///
3565  /// ```
3566  /// use opensearch_client::Client;
3567  ///
3568  /// #[derive(Serialize)]
3569  /// struct MyDocument {
3570  ///   title: String,
3571  ///   content: String,
3572  /// }
3573  ///
3574  /// #[tokio::main]
3575  /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
3576  ///   let client = Client::new("http://localhost:9200")?;
3577  ///
3578  ///   let document = MyDocument {
3579  ///     title: "My Title".to_string(),
3580  ///     content: "My Content".to_string(),
3581  ///   };
3582  ///
3583  ///   let response = client.index_document("my_index", &document, None).await?;
3584  ///
3585  ///   println!("Document ID: {}", response._id);
3586  ///
3587  ///   Ok(())
3588  /// }
3589  /// ```
3590  pub async fn index_document<T: Serialize>(
3591    &self,
3592    index: &String,
3593    body: &T,
3594    id: Option<String>,
3595  ) -> Result<types::IndexResponse, Error> {
3596    let body_json = serde_json::to_value(body)?;
3597    let partial_request = self.index_post().index(index).body(body_json);
3598    let request = match id {
3599      None => partial_request,
3600      Some(id) => partial_request.id(id),
3601    };
3602    let response = request.send().await?;
3603    Ok(response.into_inner())
3604  }
3605
3606  /// Creates a new document in the specified index with the given ID and body.
3607  ///
3608  /// # Arguments
3609  ///
3610  /// * `index` - A string slice that holds the name of the index.
3611  /// * `id` - A string slice that holds the ID of the document.
3612  /// * `body` - A generic type `T` that holds the body of the document. The
3613  ///   type `T` must implement the `Serialize` trait from the `serde` crate.
3614  ///
3615  /// # Returns
3616  ///
3617  /// Returns a `Result` containing an `IndexResponse` on success, or an `Error`
3618  /// on failure.
3619  ///
3620  /// # Examples
3621  ///
3622  /// ```rust
3623  /// use opensearch_client::OpenSearchClient;
3624  ///
3625  /// #[derive(Serialize)]
3626  /// struct MyDocument {
3627  ///   title: String,
3628  ///   content: String,
3629  /// }
3630  ///
3631  /// #[tokio::main]
3632  /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
3633  ///   let client = OpenSearchClient::new("http://localhost:9200")?;
3634  ///
3635  ///   let document = MyDocument {
3636  ///     title: "My Title".to_string(),
3637  ///     content: "My Content".to_string(),
3638  ///   };
3639  ///
3640  ///   let response = client.create_document("my_index", "1", &document).await?;
3641  ///
3642  ///   Ok(())
3643  /// }
3644  /// ```
3645  pub async fn create_document<T: Serialize>(
3646    &self,
3647    index: &String,
3648    id: &String,
3649    body: &T,
3650  ) -> Result<types::IndexResponse, Error> {
3651    let body_json = serde_json::to_value(body)?;
3652
3653    let response = self.create_put().index(index).id(id).body(body_json).send().await?;
3654    let result = response.into_inner();
3655
3656    Ok(result)
3657  }
3658
3659  /// Asynchronously retrieves a typed document from the specified index and ID.
3660  ///
3661  /// # Arguments
3662  ///
3663  /// * `index` - A string slice that holds the name of the index to retrieve
3664  ///   the document from.
3665  /// * `id` - A string slice that holds the ID of the document to retrieve.
3666  ///
3667  /// # Returns
3668  ///
3669  /// A `Result` containing the deserialized content of the retrieved document,
3670  /// or an `Error` if the operation failed.
3671  ///
3672  /// # Generic Type Parameters
3673  ///
3674  /// * `T` - The type of the document to retrieve. Must implement the
3675  ///   `DeserializeOwned` and
3676  /// `std::default::Default` traits.
3677  pub async fn get_typed<T: DeserializeOwned + std::default::Default>(
3678    &self,
3679    index: &str,
3680    id: &str,
3681  ) -> Result<types::GetResponseContent<T>, Error> {
3682    let response = self.get().index(index).id(id).send::<T>().await?;
3683    let result = response.into_inner();
3684
3685    Ok(result)
3686  }
3687
3688  /// Updates a document in the specified index with the given ID using the
3689  /// provided update action.
3690  ///
3691  /// # Arguments
3692  ///
3693  /// * `index` - A string slice that holds the name of the index to update the
3694  ///   document in.
3695  /// * `id` - A string slice that holds the ID of the document to update.
3696  /// * `action` - A reference to an `UpdateAction` enum that specifies the
3697  ///   update action to perform.
3698  ///
3699  /// # Returns
3700  ///
3701  /// Returns a `Result` containing an `IndexResponse` struct if the update was
3702  /// successful, or an `Error` if an error occurred.
3703  ///
3704  /// # Example
3705  ///
3706  /// ```rust
3707  /// use opensearch_client::{Client, UpdateAction};
3708  ///
3709  /// #[tokio::main]
3710  /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
3711  ///     let client = Client::new("http://localhost:9200")?;
3712  ///
3713  ///     let index = "my_index";
3714  ///     let id = "1";
3715  ///     let action = UpdateAction::new().doc(json!({"foo": "bar"}));
3716  ///
3717  ///     let response = client.update_document(index, id, &action).await?;
3718  ///
3719  ///     Ok(())
3720  /// }
3721  /// ```
3722  pub async fn update_document(
3723    &self,
3724    index: &str,
3725    id: &str,
3726    action: &UpdateAction,
3727  ) -> Result<types::IndexResponse, Error> {
3728    let body = serde_json::to_value(&action)?;
3729
3730    let response = self.update().body(body).index(index).id(id).send().await?;
3731    Ok(response.into_inner())
3732  }
3733
3734  pub fn get_bulker(&self, bulk_size: u32, max_concurrent_connections: u32) -> (JoinHandle<()>, Bulker) {
3735    Bulker::new(Arc::new(self.clone()), bulk_size, max_concurrent_connections)
3736  }
3737
3738  pub fn bulker(&self) -> BulkerBuilder {
3739    BulkerBuilder::new(Arc::new(self.clone()), self.max_bulk_size)
3740  }
3741
3742  #[cfg(feature = "search")]
3743  pub async fn search_typed<T: DeserializeOwned + std::default::Default>(
3744    &self,
3745    index: &str,
3746    search: Search,
3747  ) -> Result<types::SearchResult<T>, Error> {
3748    let response = self.search().index(index).body(search).send().await?;
3749    let result = response.into_inner();
3750    Ok(result)
3751  }
3752
3753  /// Searches for documents in the specified index and returns a stream of
3754  /// hits.
3755  ///
3756  /// # Arguments
3757  ///
3758  /// * `index` - The name of the index to search in.
3759  /// * `query` - The query to execute.
3760  /// * `sort` - The sort criteria to use.
3761  /// * `size` - The maximum number of hits to return.
3762  ///
3763  /// # Returns
3764  ///
3765  /// A stream of hits that match the specified search criteria.
3766  ///
3767  /// # Examples
3768  ///
3769  /// ```rust
3770  /// use opensearch_client::{Client, Query, SortCollection};
3771  ///
3772  /// #[tokio::main]
3773  /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
3774  ///   let client = Client::new("http://localhost:9200")?;
3775  ///   let query = Query::match_all();
3776  ///   let sort = SortCollection::new().add_field("_doc", "asc");
3777  ///   let stream = client.search_stream("my_index", &query, &sort, 10).await?;
3778  ///   stream
3779  ///     .for_each(|hit| {
3780  ///       println!("{:?}", hit);
3781  ///       futures::future::ready(())
3782  ///     })
3783  ///     .await;
3784  ///   Ok(())
3785  /// }
3786  /// ```
3787  #[cfg(feature = "search")]
3788  pub async fn search_stream<T: DeserializeOwned + std::default::Default>(
3789    &self,
3790    index: &str,
3791    query: &Query,
3792    sort: &SortCollection,
3793    size: u64,
3794  ) -> Result<impl Stream<Item = types::Hit<T>> + 'static, Error> {
3795    let start_state = SearchAfterState {
3796      client: Arc::new(self.clone()),
3797      stop: false,
3798      search_after: None,
3799      index: index.to_owned(),
3800      query: query.clone(),
3801      sort: sort.clone(),
3802      size,
3803    };
3804
3805    async fn stream_next<T: DeserializeOwned + std::default::Default>(
3806      state: SearchAfterState,
3807    ) -> Result<(Vec<types::Hit<T>>, SearchAfterState), Error> {
3808      let mut body: Search = Search::new()
3809        .size(state.size)
3810        .query(state.query.clone())
3811        .sort(state.sort.clone());
3812
3813      if let Some(search_after) = state.search_after.clone() {
3814        body = body.search_after(search_after.clone());
3815      }
3816      let response = state
3817        .client
3818        .clone()
3819        .search()
3820        .index(&state.index)
3821        .body(body)
3822        .send::<T>()
3823        .await?;
3824      let hits = response.into_inner().hits.hits;
3825      let next_state = SearchAfterState {
3826        stop: (hits.len() as u64) < state.size,
3827        search_after: hits.iter().last().and_then(|f| {
3828          if let Some(last_sort) = f.sort.clone().unwrap().as_array() {
3829            if last_sort.is_empty() {
3830              None
3831            } else {
3832              Some(Terms::from(last_sort))
3833            }
3834          } else {
3835            None
3836          }
3837        }),
3838        ..state
3839      };
3840
3841      Ok((hits, next_state))
3842    }
3843
3844    let stream = stream::unfold(start_state, move |state| {
3845      async move {
3846        if state.stop {
3847          None
3848        } else {
3849          let result = stream_next::<T>(state).await;
3850          match result {
3851            Ok((items, state)) => Some((stream::iter(items), state)),
3852            Err(_err) => None,
3853          }
3854        }
3855      }
3856    });
3857
3858    Ok(stream.flatten())
3859  }
3860}
3861
3862/// Represents the state of a search operation that uses the "search after"
3863/// feature.
3864#[cfg(feature = "search")]
3865struct SearchAfterState {
3866  client: Arc<OsClient>,
3867  index: String,
3868  stop: bool,
3869  size: u64,
3870  query: Query,
3871  sort: SortCollection,
3872  search_after: Option<Terms>,
3873}
3874
3875pub mod prelude {
3876  pub use self::super::OsClient;
3877}
3878
3879#[cfg(test)]
3880mod tests {
3881
3882  use std::path::PathBuf;
3883
3884  use serde::de::DeserializeOwned;
3885
3886  use super::*;
3887  fn load_entity<T: DeserializeOwned>(name: &str) -> T {
3888    let filename = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("tests/base/{name}"));
3889    let text = std::fs::read_to_string(filename).unwrap();
3890    serde_json::from_str(&text).unwrap()
3891  }
3892
3893  #[test]
3894  fn test_document_delete_response() {
3895    let decoded: types::DocumentDeleteResponse = load_entity("document_delete.response.json");
3896    assert_eq!(decoded.id, String::from("MzcIJX8BA7mbufL6DOwl"));
3897  }
3898}