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
//! Allows constructing Elasticsearch search query.
//!
//! Elasticsearch provides a full Query DSL (Domain Specific Language) based on JSON to define queries. Think of the Query DSL as an AST (Abstract Syntax Tree) of queries, consisting of two types of clauses:
//!
//! **Leaf query clauses**
//!
//! Leaf query clauses look for a particular value in a particular field, such as the match, term or range queries. These queries can be used by themselves.
//!
//! **Compound query clauses**
//!
//! Compound query clauses wrap other leaf or compound queries and are used to combine multiple queries in a logical fashion (such as the bool or dis_max query), or to alter their behavior (such as the constant_score query).
//!
//! <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html>

// Public modules
pub mod params;

pub mod compound;
pub mod custom;
pub mod full_text;
pub mod geo;
pub mod joining;
pub mod shape;
pub mod span;
pub mod specialized;
pub mod term_level;

pub use self::compound::*;
pub use self::custom::*;
pub use self::full_text::*;
pub use self::geo::*;
pub use self::joining::*;
pub use self::shape::*;
pub use self::span::*;
pub use self::specialized::*;
pub use self::term_level::*;

// Very special queries
mod match_all_query;
mod match_none_query;

pub use self::match_all_query::*;
pub use self::match_none_query::*;

use crate::util::*;

macro_rules! query {
    ($($variant:ident($query:ty)),+ $(,)?) => {
        /// A container enum for supported Elasticsearch query types
        #[derive(Clone, PartialEq, Serialize)]
        #[serde(untagged)]
        #[allow(missing_docs)]
        pub enum Query {
            $(
                $variant($query),
            )*
        }

        impl IntoIterator for Query {
            type Item = Self;
            type IntoIter = std::option::IntoIter<Self::Item>;

            fn into_iter(self) -> Self::IntoIter {
                if self.should_skip() {
                    None.into_iter()
                } else {
                    Some(self).into_iter()
                }
            }
        }

        impl ShouldSkip for Query {
            fn should_skip(&self) -> bool {
                match self {
                    $(
                        Self::$variant(q) => q.should_skip(),
                    )+
                }
            }
        }

        impl std::fmt::Debug for Query {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self {
                    $(
                        Self::$variant(q) => q.fmt(f),
                    )+
                }
            }
        }

        $(
            impl From<$query> for Query {
                fn from(q: $query) -> Self {
                    Query::$variant(q)
                }
            }

            impl PartialEq<$query> for Query {
                fn eq(&self, other: &$query) -> bool {
                    match self {
                        Self::$variant(query) => query.eq(other),
                        _ => false,
                    }
                }
            }

            impl PartialEq<Query> for $query {
                fn eq(&self, other: &Query) -> bool {
                    match other {
                        Query::$variant(query) => self.eq(query),
                        _ => false,
                    }
                }
            }

            impl From<$query> for Option<Query> {
                fn from(q: $query) -> Self {
                    if q.should_skip() {
                        None
                    } else {
                        Some(Query::$variant(q))
                    }
                }
            }

            impl From<$query> for Queries {
                fn from(q: $query) -> Self {
                    if q.should_skip() {
                        Default::default()
                    } else {
                        Self(vec![q.into(); 1])
                    }
                }
            }
        )+
    };
}

query!(
    Bool(BoolQuery),
    Prefix(PrefixQuery),
    Regexp(RegexpQuery),
    Wildcard(WildcardQuery),
    TermsSet(TermsSetQuery),
    Term(TermQuery),
    Terms(TermsQuery),
    TermsLookup(TermsLookupQuery),
    Exists(ExistsQuery),
    Range(RangeQuery),
    Ids(IdsQuery),
    ConstantScore(ConstantScoreQuery),
    DistanceFeatureDate(DistanceFeatureQuery<chrono::DateTime<chrono::Utc>>),
    DistanceFeatureGeo(DistanceFeatureQuery<crate::GeoPoint>),
    Match(MatchQuery),
    MatchBoolPrefix(MatchBoolPrefixQuery),
    MatchPhrasePrefix(MatchPhrasePrefixQuery),
    MatchAll(MatchAllQuery),
    MatchNone(MatchNoneQuery),
    MatchPhrase(MatchPhraseQuery),
    MultiMatch(MultiMatchQuery),
    Nested(NestedQuery),
    Boosting(BoostingQuery),
    DisMax(DisMaxQuery),
    Pinned(PinnedQuery),
    Percolate(PercolateQuery),
    PercolateLookup(PercolateLookupQuery),
    FunctionScore(FunctionScoreQuery),
    RankFeature(RankFeatureQuery),
    RankFeatureSaturation(RankFeatureSaturationQuery),
    RankFeatureLogarithm(RankFeatureLogarithmQuery),
    RankFeatureSigmoid(RankFeatureSigmoidQuery),
    RankFeatureLinear(RankFeatureLinearQuery),
    MoreLikeThis(MoreLikeThisQuery),
    Fuzzy(FuzzyQuery),
    GeoDistance(GeoDistanceQuery),
    GeoBoundingBox(GeoBoundingBoxQuery),
    GeoShapeLookup(GeoShapeLookupQuery),
    GeoShape(GeoShapeQuery),
    ShapeLookup(ShapeLookupQuery),
    Shape(ShapeQuery),
    Json(JsonQuery),
    Wrapper(WrapperQuery),
    Script(ScriptQuery),
    ScriptScore(ScriptScoreQuery),
);

/// A collection of queries
#[derive(Default, Clone, PartialEq, Serialize)]
pub struct Queries(Vec<Query>);

impl std::fmt::Debug for Queries {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl<T> From<T> for Queries
where
    T: IntoIterator,
    T::Item: Into<Option<Query>>,
{
    fn from(value: T) -> Self {
        Self(
            value
                .into_iter()
                .filter_map(Into::into)
                .filter(|x| !x.should_skip())
                .collect(),
        )
    }
}

impl ShouldSkip for Queries {
    fn should_skip(&self) -> bool {
        self.0.should_skip()
    }
}

impl Queries {
    /// Pushes multiple queries to the collection
    pub fn extend<Q>(&mut self, queries: Q)
    where
        Q: Into<Queries>,
    {
        self.0.extend(queries.into().0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adds_query() {
        let mut queries = Queries::default();

        let query = Query::terms("test", [1]);

        queries.extend(query);

        assert_eq!(queries.0.len(), 1);
    }

    #[test]
    fn adds_queries() {
        let mut queries = Queries::default();

        let query_1 = Query::terms("test", [1]);
        let query_2 = Query::terms("test", [2]);

        queries.extend([query_1, query_2]);

        assert_eq!(queries.0.len(), 2);
    }

    #[test]
    fn skips_queries() {
        let mut queries = Queries::default();

        let empty_values: [i32; 0] = [];

        let query_1 = Query::terms("test", empty_values).into();
        let query_2 = Query::from(Query::terms("test", empty_values));
        let query_3 = Query::Terms(Query::terms("test", empty_values));

        queries.extend([query_1, query_2, query_3]);

        assert!(queries.0.is_empty());
    }

    #[test]
    fn skips_query() {
        let mut queries = Queries::default();

        let empty_values: [i32; 0] = [];

        let query = Query::terms("test", empty_values);

        queries.extend(query);

        assert!(queries.0.is_empty());
    }

    #[test]
    fn partial_eq() {
        assert_eq!(
            Query::term("field", "value"),
            Query::from(Query::term("field", "value"))
        );
        assert_eq!(
            Query::from(Query::term("field", "value")),
            Query::term("field", "value"),
        );
    }
}