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
use crate::search::*;
use crate::util::*;
use std::collections::BTreeSet;

/// Returns documents that contain one or more **exact** terms in a provided field.
/// The terms query is the same as the term query, except you can search for multiple values.
///
/// To create a terms query with numeric values:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::terms("test", vec![123]);
/// ```
/// To create a terms query with string values and optional fields:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::terms("test", vec!["username"])
///     .boost(2)
///     .name("test");
/// ```
/// To create a terms lookup query:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::terms_lookup("test", "index", "id", "path")
///     .routing("routing")
///     .boost(1.3)
///     .name("lookup");
/// ```
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html>
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TermsQuery<T: Terms> {
    #[serde(rename = "terms")]
    inner: Inner<T>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
struct Inner<T: Terms> {
    #[serde(flatten)]
    pair: KeyValuePair<String, T>,

    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    boost: Option<Boost>,

    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    _name: Option<String>,
}

impl Query {
    /// Creates an instance of [`TermsQuery`]
    ///
    /// - `field` - Field you wish to search.
    /// - `values` - An array of terms you wish to find in the provided field. To return a
    /// document, one or more terms must exactly match a field value,
    /// including whitespace and capitalization.<br>
    /// By default, Elasticsearch limits the `terms` query to a maximum of
    /// 65,536 terms. You can change this limit using the
    /// [`index.max_terms_count setting`](https://www.elastic.co/guide/en/elasticsearch/reference/current/index-modules.html#index-max-terms-count).<br>
    /// > To use the field values of an existing document as search terms,
    /// use the [terms lookup](crate::TermsLookup) parameters.
    pub fn terms<S, I>(field: S, values: I) -> TermsQuery<BTreeSet<Scalar>>
    where
        S: Into<String>,
        I: IntoIterator,
        I::Item: Into<Scalar>,
    {
        TermsQuery {
            inner: Inner {
                pair: KeyValuePair::new(field.into(), values.into_iter().map(Into::into).collect()),
                boost: None,
                _name: None,
            },
        }
    }

    /// Creates an instance of [`TermsQuery`]
    ///
    /// - `field` - Field you wish to search.
    /// - `index` - Name of the index from which to fetch field values.
    /// - `id` - [ID](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-id-field.html)
    /// of the document from which to fetch field values.
    /// - `path` - Name of the field from which to fetch field values. Elasticsearch uses
    /// these values as search terms for the query. If the field values
    /// include an array of nested inner objects, you can access those objects
    /// using dot notation syntax.
    pub fn terms_lookup<S: Into<String>>(
        field: S,
        index: S,
        id: S,
        path: S,
    ) -> TermsQuery<TermsLookup> {
        TermsQuery {
            inner: Inner {
                pair: KeyValuePair::new(
                    field.into(),
                    TermsLookup {
                        index: index.into(),
                        id: id.into(),
                        path: path.into(),
                        routing: None,
                    },
                ),
                boost: None,
                _name: None,
            },
        }
    }
}

impl<T: Terms> TermsQuery<T> {
    add_boost_and_name!();
}

impl TermsQuery<TermsLookup> {
    /// Custom [routing value](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-routing-field.html)
    /// of the document from which to fetch term values. If a custom routing
    /// value was provided when the document was indexed, this parameter is
    /// required.
    pub fn routing(mut self, routing: impl Into<String>) -> Self {
        self.inner.pair.value.routing = Some(routing.into());
        self
    }
}

impl ShouldSkip for TermsQuery<BTreeSet<Scalar>> {
    fn should_skip(&self) -> bool {
        self.inner.pair.value.should_skip()
    }
}

impl ShouldSkip for TermsQuery<TermsLookup> {}

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

    mod scalar {
        use super::*;

        test_serialization! {
            with_required_fields(
                Query::terms("test", vec![123, 12, 13]),
                json!({"terms": { "test": [12, 13, 123] } })
            );

            with_all_fields(
                Query::terms("test", vec![123]).boost(2).name("test"),
                json!({
                    "terms": {
                        "test": [123],
                        "boost": 2,
                        "_name": "test",
                    }
                })
            );
        }

        #[test]
        fn should_skip_when_there_are_no_values() {
            let values: Vec<Scalar> = Vec::new();
            let query = Query::terms("test", values);

            assert!(query.should_skip())
        }

        #[test]
        fn should_not_skip_when_there_are_no_values() {
            let query = Query::terms("test", vec![123]);

            assert!(!query.should_skip())
        }
    }

    mod lookup {
        use super::*;

        test_serialization! {
            with_required_fields(
                Query::terms_lookup("test", "index_value", "id_value", "path_value"),
                json!({
                    "terms": {
                        "test": {
                            "index": "index_value",
                            "id": "id_value",
                            "path": "path_value",
                        }
                    }
                })
            );

            with_all_fields(
                Query::terms_lookup("test", "index_value", "id_value", "path_value")
                    .routing("routing_value")
                    .boost(2)
                    .name("test"),
                json!({
                    "terms": {
                        "test": {
                            "index": "index_value",
                            "id": "id_value",
                            "path": "path_value",
                            "routing": "routing_value"
                        },
                        "boost": 2,
                        "_name": "test",
                    }
                })
            );
        }
    }
}