elasticsearch_dsl/search/queries/joining/
nested_query.rs

1use crate::search::*;
2use crate::util::*;
3
4/// Wraps another query to search
5/// [nested](https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html)
6/// fields.
7///
8/// The `nested` query searches nested field objects as if they were indexed as
9/// separate documents. If an object matches the search, the `nested` query
10/// returns the root parent document.
11///
12/// To create nested query:
13/// ```
14/// # use elasticsearch_dsl::queries::*;
15/// # use elasticsearch_dsl::queries::params::*;
16/// # let query =
17/// Query::nested("vehicles", Query::term("vehicles.license", "ABC123"))
18///     .boost(3)
19///     .name("test");
20/// ```
21/// To create multi-level nested query:
22/// ```
23/// # use elasticsearch_dsl::queries::*;
24/// # use elasticsearch_dsl::queries::params::*;
25/// # let query =
26/// Query::nested("driver", Query::nested("driver.vehicle", Query::term("driver.vehicle.make", "toyota")))
27///     .boost(3)
28///     .name("test");
29/// ```
30/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html>
31#[derive(Debug, Clone, PartialEq, Serialize)]
32#[serde(remote = "Self")]
33pub struct NestedQuery {
34    path: String,
35
36    query: Box<Query>,
37
38    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
39    score_mode: Option<NestedQueryScoreMode>,
40
41    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
42    ignore_unmapped: Option<bool>,
43
44    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
45    inner_hits: Option<Box<InnerHits>>,
46
47    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
48    boost: Option<f32>,
49
50    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
51    _name: Option<String>,
52}
53
54impl Query {
55    /// Creates an instance of [`NestedQuery`]
56    ///
57    /// - `path` - Path to the nested object you wish to search.
58    /// - `query` - Query you wish to run on nested objects in the `path`. If an object
59    ///   matches the search, the `nested` query returns the root parent document.<br/>
60    ///   You can search nested fields using dot notation that includes the
61    ///   complete path, such as `obj1.name`.<br/>
62    ///   Multi-level nesting is automatically supported, and detected,
63    ///   resulting in an inner nested query to automatically match the relevant
64    ///   nesting level, rather than root, if it exists within another nested
65    ///   query.<br/>
66    ///   Multi-level nested queries are also supported.
67    pub fn nested<T, U>(path: T, query: U) -> NestedQuery
68    where
69        T: ToString,
70        U: Into<Query>,
71    {
72        NestedQuery {
73            path: path.to_string(),
74            query: Box::new(query.into()),
75            score_mode: None,
76            ignore_unmapped: None,
77            inner_hits: None,
78            boost: None,
79            _name: None,
80        }
81    }
82}
83
84impl NestedQuery {
85    /// Indicates how scores for matching child objects affect the root parent
86    /// document’s
87    /// [relevance score](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-filter-context.html#relevance-scores).
88    pub fn score_mode(mut self, score_mode: NestedQueryScoreMode) -> Self {
89        self.score_mode = Some(score_mode);
90        self
91    }
92
93    /// Indicates whether to ignore an unmapped `path` and not return any
94    /// documents instead of an error. Defaults to `false`.
95    ///
96    /// If `false`, Elasticsearch returns an error if the `path` is an unmapped
97    /// field.
98    ///
99    /// You can use this parameter to query multiple indices that may not
100    /// contain the field `path`.
101    pub fn ignore_unmapped(mut self, ignore_unmapped: bool) -> Self {
102        self.ignore_unmapped = Some(ignore_unmapped);
103        self
104    }
105
106    /// The [parent-join](https://www.elastic.co/guide/en/elasticsearch/reference/current/parent-join.html)
107    /// and [nested](https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html)
108    /// features allow the return of documents that have matches in a different scope. In the
109    /// parent/child case, parent documents are returned based on matches in child documents or
110    /// child documents are returned based on matches in parent documents. In the nested case,
111    /// documents are returned based on matches in nested inner objects.
112    ///
113    /// In both cases, the actual matches in the different scopes that caused a document to be
114    /// returned are hidden. In many cases, it’s very useful to know which inner nested objects
115    /// (in the case of nested) or children/parent documents (in the case of parent/child) caused
116    /// certain information to be returned. The inner hits feature can be used for this. This
117    /// feature returns per search hit in the search response additional nested hits that caused a
118    /// search hit to match in a different scope.
119    ///
120    /// Inner hits can be used by defining an `inner_hits` definition on a `nested`, `has_child`
121    /// or `has_parent` query and filter.
122    ///
123    /// <https://www.elastic.co/guide/en/elasticsearch/reference/current/inner-hits.html>
124    pub fn inner_hits(mut self, inner_hits: InnerHits) -> Self {
125        self.inner_hits = Some(Box::new(inner_hits));
126        self
127    }
128
129    add_boost_and_name!();
130}
131
132impl ShouldSkip for NestedQuery {
133    fn should_skip(&self) -> bool {
134        self.query.should_skip()
135    }
136}
137
138serialize_with_root!("nested": NestedQuery);
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn serialization() {
146        assert_serialize_query(
147            Query::nested("vehicles", Query::term("vehicles.license", "ABC123")),
148            json!({
149                "nested": {
150                    "path": "vehicles",
151                    "query": {
152                        "term": {
153                            "vehicles.license": {
154                                "value": "ABC123"
155                            }
156                        }
157                    }
158                }
159            }),
160        );
161
162        assert_serialize_query(
163            Query::nested("vehicles", Query::term("vehicles.license", "ABC123"))
164                .boost(3)
165                .name("test"),
166            json!({
167                "nested": {
168                    "path": "vehicles",
169                    "query": {
170                        "term": {
171                            "vehicles.license": {
172                                "value": "ABC123"
173                            }
174                        }
175                    },
176                    "boost": 3.0,
177                    "_name": "test",
178                }
179            }),
180        );
181
182        assert_serialize_query(
183            Query::nested(
184                "driver",
185                Query::nested(
186                    "driver.vehicles",
187                    Query::term("driver.vehicles.make.keyword", "toyota"),
188                ),
189            ),
190            json!({
191                "nested": {
192                    "path": "driver",
193                    "query": {
194                        "nested": {
195                            "path": "driver.vehicles",
196                            "query": {
197                                "term": {
198                                    "driver.vehicles.make.keyword": {
199                                        "value": "toyota"
200                                    }
201                                }
202                            }
203                        }
204                    }
205                }
206            }),
207        );
208    }
209}