elasticsearch_dsl/search/aggregations/metrics/
avg_aggregation.rs

1use crate::search::*;
2use crate::util::*;
3
4/// A `single-value` metrics aggregation that computes the average of numeric values that are extracted
5/// from the aggregated documents. These values can be extracted either from specific numeric fields
6/// in the documents.
7///
8/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-avg-aggregation.html>
9#[derive(Debug, Clone, Serialize, PartialEq)]
10pub struct AvgAggregation {
11    avg: AvgAggregationInner,
12}
13
14#[derive(Debug, Clone, Serialize, PartialEq)]
15struct AvgAggregationInner {
16    field: String,
17
18    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
19    missing: Option<Number>,
20}
21
22impl Aggregation {
23    /// Creates an instance of [`AvgAggregation`]
24    ///
25    /// - `field` - field to aggregate
26    pub fn avg<T>(field: T) -> AvgAggregation
27    where
28        T: ToString,
29    {
30        AvgAggregation {
31            avg: AvgAggregationInner {
32                field: field.to_string(),
33                missing: None,
34            },
35        }
36    }
37}
38
39impl AvgAggregation {
40    /// The missing parameter defines how documents that are missing a value should be treated. By
41    /// default they will be ignored but it is also possible to treat them as if they had a value.
42    pub fn missing<T>(mut self, missing: T) -> Self
43    where
44        T: Into<Number>,
45    {
46        self.avg.missing = Some(missing.into());
47        self
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn serialization() {
57        assert_serialize_aggregation(
58            Aggregation::avg("test_field"),
59            json!({ "avg": { "field": "test_field" } }),
60        );
61
62        assert_serialize_aggregation(
63            Aggregation::avg("test_field").missing(100.1),
64            json!({
65                "avg": {
66                    "field": "test_field",
67                    "missing": 100.1
68                }
69            }),
70        );
71    }
72}