elasticsearch_dsl/search/queries/term_level/
fuzzy_query.rs

1use crate::search::*;
2use crate::util::*;
3use serde::Serialize;
4
5/// Returns documents that contain terms similar to the search term, as measured by a
6/// [Levenshtein edit distance](https://en.wikipedia.org/wiki/Levenshtein_distance).
7///
8/// An edit distance is the number of one-character changes needed to turn one term into another.
9/// These changes can include:
10///
11/// - Changing a character (**b**ox → **f**ox)
12/// - Removing a character (**b**lack → lack)
13/// - Inserting a character (sic → sic**k**)
14/// - Transposing two adjacent characters (**ac**t → **ca**t)
15///   To find similar terms, the fuzzy query creates a set of all possible variations, or expansions, of the search term within a specified edit distance. The query then returns exact matches for each expansion.
16///
17/// To create a fuzzy query with numeric values:
18/// ```
19/// # use elasticsearch_dsl::queries::*;
20/// # use elasticsearch_dsl::queries::params::*;
21/// # let query =
22/// Query::fuzzy("test", 123);
23/// ```
24/// To create a fuzzy query with string values and optional fields:
25/// ```
26/// # use elasticsearch_dsl::queries::*;
27/// # use elasticsearch_dsl::queries::params::*;
28/// # let query =
29/// Query::fuzzy("test", "username")
30///     .boost(2)
31///     .name("test");
32/// ```
33/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html>
34#[derive(Debug, Clone, PartialEq, Serialize)]
35#[serde(remote = "Self")]
36pub struct FuzzyQuery {
37    #[serde(skip)]
38    field: String,
39
40    value: Option<Term>,
41
42    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
43    fuzziness: Option<Fuzziness>,
44
45    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
46    max_expansions: Option<u8>,
47
48    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
49    prefix_length: Option<u8>,
50
51    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
52    transpositions: Option<bool>,
53
54    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
55    rewrite: Option<Rewrite>,
56
57    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
58    boost: Option<f32>,
59
60    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
61    _name: Option<String>,
62}
63
64impl Query {
65    /// Creates an instance of [`FuzzyQuery`]
66    ///
67    /// - `field` - Field you wish to search.
68    /// - `value` - Fuzzy you wish to find in the provided field.
69    pub fn fuzzy<T, U>(field: T, value: U) -> FuzzyQuery
70    where
71        T: ToString,
72        U: Serialize,
73    {
74        FuzzyQuery {
75            field: field.to_string(),
76            value: Term::new(value),
77            fuzziness: None,
78            max_expansions: None,
79            prefix_length: None,
80            transpositions: None,
81            rewrite: None,
82            boost: None,
83            _name: None,
84        }
85    }
86}
87
88impl FuzzyQuery {
89    /// Maximum edit distance allowed for matching.
90    /// See [Fuzziness](Fuzziness)
91    /// for valid values and more information. See
92    /// [Fuzziness in the match query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html#query-dsl-match-query-fuzziness)
93    /// for an example.
94    pub fn fuzziness<T>(mut self, fuzziness: T) -> Self
95    where
96        T: Into<Fuzziness>,
97    {
98        self.fuzziness = Some(fuzziness.into());
99        self
100    }
101
102    /// Maximum number of terms to which the query will expand.
103    /// Defaults to `50`.
104    pub fn max_expansions(mut self, max_expansions: u8) -> Self {
105        self.max_expansions = Some(max_expansions);
106        self
107    }
108
109    /// Number of beginning characters left unchanged for fuzzy matching.
110    /// Defaults to `0`.
111    pub fn prefix_length(mut self, prefix_length: u8) -> Self {
112        self.prefix_length = Some(prefix_length);
113        self
114    }
115
116    /// Indicates whether edits include transpositions of two adjacent characters (ab → ba).
117    /// Defaults to `true`
118    pub fn transpositions(mut self, transpositions: bool) -> Self {
119        self.transpositions = Some(transpositions);
120        self
121    }
122
123    /// Method used to rewrite the query. For valid values and more information, see the
124    /// [rewrite](Rewrite) parameter.
125    pub fn rewrite(mut self, rewrite: Rewrite) -> Self {
126        self.rewrite = Some(rewrite);
127        self
128    }
129
130    add_boost_and_name!();
131}
132
133impl ShouldSkip for FuzzyQuery {
134    fn should_skip(&self) -> bool {
135        self.value.should_skip()
136    }
137}
138
139serialize_with_root_keyed!("fuzzy": FuzzyQuery);
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    #[test]
146    fn serialization() {
147        assert_serialize_query(
148            Query::fuzzy("test", 123),
149            json!({
150                "fuzzy": {
151                    "test": {
152                        "value": 123
153                    }
154                }
155            }),
156        );
157
158        assert_serialize_query(
159            Query::fuzzy("test", 123)
160                .fuzziness(Fuzziness::Auto)
161                .max_expansions(3)
162                .prefix_length(4)
163                .transpositions(false)
164                .rewrite(Rewrite::ScoringBoolean)
165                .boost(2)
166                .name("test"),
167            json!({
168                "fuzzy": {
169                    "test": {
170                        "value": 123,
171                        "fuzziness": "AUTO",
172                        "max_expansions": 3,
173                        "prefix_length": 4,
174                        "transpositions": false,
175                        "rewrite": "scoring_boolean",
176                        "boost": 2.0,
177                        "_name": "test"
178                    }
179                }
180            }),
181        );
182
183        assert_serialize_query(
184            Query::bool().filter(Query::fuzzy("test", None::<String>)),
185            json!({ "bool": {} }),
186        )
187    }
188}