rs_es/operations/
analyze.rs

1/*
2 * Copyright 2015-2019 Ben Ashford
3 * Copyright 2015 Astro
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18//! Implementation of ElasticSearch Analyze operation
19
20use serde::Deserialize;
21
22use crate::{
23    error::EsError,
24    {Client, EsResponse},
25};
26
27#[derive(Debug)]
28pub struct AnalyzeOperation<'a, 'b> {
29    /// The HTTP client that this operation will use
30    client: &'a mut Client,
31
32    body: &'b str,
33    index: Option<&'b str>,
34    analyzer: Option<&'b str>,
35}
36
37impl<'a, 'b> AnalyzeOperation<'a, 'b> {
38    pub fn new(client: &'a mut Client, body: &'b str) -> AnalyzeOperation<'a, 'b> {
39        AnalyzeOperation {
40            client,
41            body,
42            index: None,
43            analyzer: None,
44        }
45    }
46
47    pub fn with_index(&mut self, index: &'b str) -> &mut Self {
48        self.index = Some(index);
49        self
50    }
51
52    pub fn with_analyzer(&mut self, analyzer: &'b str) -> &mut Self {
53        self.analyzer = Some(analyzer);
54        self
55    }
56
57    pub fn send(&mut self) -> Result<AnalyzeResult, EsError> {
58        let mut url = match self.index {
59            None => "/_analyze".to_owned(),
60            Some(index) => format!("{}/_analyze", index),
61        };
62        match self.analyzer {
63            None => (),
64            Some(analyzer) => url.push_str(&format!("?analyzer={}", analyzer)),
65        }
66        let response = self.client.do_es_op(&url, |url| {
67            self.client.http_client.post(url).body(self.body.to_owned())
68        })?;
69
70        Ok(response.read_response()?)
71    }
72}
73
74impl Client {
75    /// Analyze
76    ///
77    /// See: https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-analyze.html
78    pub fn analyze<'a>(&'a mut self, body: &'a str) -> AnalyzeOperation {
79        AnalyzeOperation::new(self, body)
80    }
81}
82
83/// The result of an analyze operation
84#[derive(Debug, Deserialize)]
85pub struct AnalyzeResult {
86    pub tokens: Vec<Token>,
87}
88
89#[derive(Debug, Deserialize)]
90pub struct Token {
91    pub token: String,
92    #[serde(rename = "type")]
93    pub token_type: String,
94    pub position: u64,
95    pub start_offset: u64,
96    pub end_offset: u64,
97}