logo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use serde::{de, Deserialize, Serialize, Serializer};

/// Elasticsearch analyze API response
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AnalyzeResponse {
    /// Standard response, when `explain` value is `false`
    #[serde(rename = "tokens")]
    Standard(Vec<Token>),

    /// Explained response, when `explain` value is `true`
    #[serde(rename = "detail")]
    Explained(ExplainedResponse),
}

/// Extracted token from text using tokenizer
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Token {
    /// The characters of the current token
    pub token: String,

    /// The start offset of the current token
    pub start_offset: u32,

    /// The end offset of the current token
    pub end_offset: u32,

    /// The type of the current token
    #[serde(rename = "type")]
    pub ty: TokenType,

    /// The position of the current token
    pub position: u32,

    /// Token in bytes
    pub bytes: Option<String>,

    /// Whether or not the current token is marked as a keyword
    pub keyword: Option<bool>,

    /// The position length of the current token
    pub position_length: Option<u32>,

    /// Term frequency in given text analysis
    pub term_frequency: Option<u32>,
}

/// Explained response structure
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct ExplainedResponse {
    custom_analyzer: bool,

    analyzer: Option<AnalysisObject>,

    #[serde(default, rename = "charfilters")]
    char_filters: Vec<CharFilter>,

    tokenizer: Option<AnalysisObject>,

    #[serde(default, rename = "tokenfilters")]
    token_filters: Vec<AnalysisObject>,
}

/// Structure for analyzer, tokenizer and token filters
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct AnalysisObject {
    name: String,
    tokens: Vec<Token>,
}

/// Structure for char filters
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct CharFilter {
    name: String,
    filtered_text: Vec<String>,
}

/// Type of token
#[derive(Debug, Clone, PartialEq)]
pub enum TokenType {
    /// Alphanumeric token
    Alphanum,

    /// Synonym token
    Synonym,

    /// Word token
    Word,

    /// Hangul (Korean alphabet) token
    Hangul,

    /// Numeric token
    Num,

    /// Email token
    Email,

    /// Words with apostrophe token
    Apostrophe,

    /// CJK (Chinese, Japanese, and Korean) tokens
    Double,

    /// Normalized CJK (Chinese, Japanese, and Korean) tokens.
    /// Normalizes width differences in CJK (Chinese, Japanese, and Korean) characters as follows:
    /// Folds full-width ASCII character variants into the equivalent basic Latin characters
    /// Folds half-width Katakana character variants into the equivalent Kana characters
    Katakana,

    /// Acronym token
    Acronym,

    /// Gram token
    Gram,

    /// Fingerprint token
    Fingerprint,

    /// Shingle token
    Shingle,

    /// Other token
    Other(String),
}

impl Default for TokenType {
    fn default() -> Self {
        Self::Alphanum
    }
}

impl Serialize for TokenType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Alphanum => "<ALPHANUM>",
            Self::Synonym => "SYNONYM",
            Self::Word => "word",
            Self::Hangul => "<HANGUL>",
            Self::Num => "<NUM>",
            Self::Email => "<EMAIL>",
            Self::Apostrophe => "<APOSTROPHE>",
            Self::Double => "<DOUBLE>",
            Self::Katakana => "<KATAKANA>",
            Self::Acronym => "<ACRONYM>",
            Self::Gram => "gram",
            Self::Fingerprint => "fingerprint",
            Self::Shingle => "shingle",
            Self::Other(other) => other,
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for TokenType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        Ok(match String::deserialize(deserializer)?.as_str() {
            "<ALPHANUM>" => Self::Alphanum,
            "SYNONYM" => Self::Synonym,
            "word" => Self::Word,
            "<HANGUL>" => Self::Hangul,
            "<NUM>" => Self::Num,
            "<EMAIL>" => Self::Email,
            "<APOSTROPHE>" => Self::Apostrophe,
            "<DOUBLE>" => Self::Double,
            "<KATAKANA>" => Self::Katakana,
            "<ACRONYM>" => Self::Acronym,
            "gram" => Self::Gram,
            "fingerprint" => Self::Fingerprint,
            "shingle" => Self::Shingle,
            other => Self::Other(other.to_string()),
        })
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn deserialize_standard() {
        let json_response = json!({
            "tokens": [
                {
                    "token": "test1",
                    "start_offset": 0,
                    "end_offset": 6,
                    "type": "<ALPHANUM>",
                    "position": 0
                },
                {
                    "token": "test2",
                    "start_offset": 7,
                    "end_offset": 11,
                    "type": "<ALPHANUM>",
                    "position": 1
                }
            ]
        });

        let token_1 = Token {
            token: "test1".to_string(),
            start_offset: 0,
            end_offset: 6,
            ty: TokenType::Alphanum,
            position: 0,
            bytes: None,
            keyword: None,
            position_length: None,
            term_frequency: None,
        };
        let token_2 = Token {
            token: "test2".to_string(),
            start_offset: 7,
            end_offset: 11,
            ty: TokenType::Alphanum,
            position: 1,
            bytes: None,
            keyword: None,
            position_length: None,
            term_frequency: None,
        };

        let expected = AnalyzeResponse::Standard(vec![token_1, token_2]);
        let result: AnalyzeResponse = serde_json::from_value(json_response).unwrap();

        assert_eq!(expected, result);
    }

    #[test]
    fn deserialize_explained() {
        let json_response = json!({
            "detail": {
                "custom_analyzer": true,
                "charfilters": [
                    {
                        "name": "html_strip",
                        "filtered_text": [
                            "test"
                        ]
                    }
                ],
                "tokenizer": {
                    "name": "lowercase",
                    "tokens": [
                        {
                            "token": "test",
                            "start_offset": 0,
                            "end_offset": 6,
                            "type": "SYNONYM",
                            "position": 0
                        }
                    ]
                },
                "tokenfilters": [
                    {
                        "name": "__anonymous__stop",
                        "tokens": [
                            {
                                "token": "test",
                                "start_offset": 0,
                                "end_offset": 6,
                                "type": "SYNONYM",
                                "position": 0
                            }
                        ]
                    }
                ]
            }
        });

        let token = Token {
            token: "test".to_string(),
            start_offset: 0,
            end_offset: 6,
            ty: TokenType::Synonym,
            position: 0,
            bytes: None,
            keyword: None,
            position_length: None,
            term_frequency: None,
        };

        let expected = AnalyzeResponse::Explained(ExplainedResponse {
            custom_analyzer: true,
            analyzer: None,
            char_filters: vec![CharFilter {
                name: "html_strip".to_string(),
                filtered_text: vec!["test".to_string()],
            }],
            tokenizer: Some(AnalysisObject {
                name: "lowercase".to_string(),
                tokens: vec![token.clone()],
            }),
            token_filters: vec![AnalysisObject {
                name: "__anonymous__stop".to_string(),
                tokens: vec![token],
            }],
        });

        let result: AnalyzeResponse = serde_json::from_value(json_response).unwrap();

        assert_eq!(expected, result);
    }
}