elasticsearch_dsl/search/aggregations/bucket/
nested_aggregation.rs

1use crate::search::*;
2use crate::util::*;
3use serde::Serialize;
4
5/// A special single-bucket aggregation that enables aggregating nested documents.
6///
7/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html>
8#[derive(Debug, Clone, Serialize, PartialEq)]
9pub struct NestedAggregation {
10    nested: NestedAggregationInner,
11
12    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
13    aggs: Aggregations,
14}
15
16#[derive(Debug, Clone, Serialize, PartialEq)]
17struct NestedAggregationInner {
18    path: String,
19}
20
21impl Aggregation {
22    /// Creates an instance of [`NestedAggregation`]
23    ///
24    /// - `path` - The nested path to aggregate.
25    pub fn nested(path: &str) -> NestedAggregation {
26        NestedAggregation {
27            nested: NestedAggregationInner {
28                path: path.to_string(),
29            },
30            aggs: Aggregations::new(),
31        }
32    }
33}
34
35impl NestedAggregation {
36    add_aggregate!();
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn serialization() {
45        assert_serialize_aggregation(
46            Aggregation::nested("nested_path"),
47            json!({ "nested": { "path": "nested_path" } }),
48        );
49
50        assert_serialize_aggregation(
51            Aggregation::nested("nested_path")
52                .aggregate("sub_agg", Aggregation::terms("test_field")),
53            json!({
54                "nested": {
55                    "path": "nested_path"
56                },
57                "aggs": {
58                    "sub_agg": {
59                        "terms": {
60                            "field": "test_field"
61                        }
62                    }
63                }
64            }),
65        );
66    }
67}