elastic_query_builder/aggregation/
max_aggregation.rs1use crate::aggregation::AggregationTrait;
2use crate::merge;
3use serde::ser::SerializeStruct;
4use serde::{Serialize, Serializer};
5use serde_json::{json, Value};
6
7#[derive(Default)]
8pub struct MaxAggregation {
9 name: String,
10 value: MaxValue,
11 aggregation: Value,
12}
13
14#[derive(Default)]
15struct MaxValue {
16 field: String,
17 script: String,
18 format: String,
19 missing: i64,
20}
21
22impl MaxAggregation {
23 pub fn new(name: &str) -> Self {
24 MaxAggregation {
25 name: name.to_string(),
26 ..Default::default()
27 }
28 }
29
30 pub fn set_field(mut self, field: &str) -> Self {
31 self.value.field = field.to_string();
32 self
33 }
34
35 pub fn set_script(mut self, script: &str) -> Self {
36 self.value.script = script.to_string();
37 self
38 }
39 pub fn set_missing(mut self, missing: i64) -> Self {
40 self.value.missing = missing;
41 self
42 }
43 pub fn set_format(mut self, fmt: &str) -> Self {
44 self.value.format = fmt.to_string();
45 self
46 }
47 pub fn set_aggregation<T>(mut self, aggregation: T) -> Self
48 where
49 T: AggregationTrait,
50 {
51 self.aggregation = aggregation.build();
52 self
53 }
54 pub fn append_aggregation<T>(mut self, query: T) -> Self
55 where
56 T: AggregationTrait,
57 {
58 let mut values = self.aggregation.clone();
59 merge(&mut values, &query.build());
60 self.aggregation = json!(values);
61 return self;
62 }
63}
64
65impl Serialize for MaxValue {
66 fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
67 where
68 S: Serializer,
69 {
70 let mut state = serializer.serialize_struct("MaxValue", 0)?;
71
72 if !self.field.is_empty() {
73 state.serialize_field("field", &self.field)?;
74 }
75 if !self.format.is_empty() {
76 state.serialize_field("format", &self.format)?;
77 }
78 if self.missing != 0 {
79 state.serialize_field("missing", &self.missing)?;
80 }
81 state.end()
82 }
83}
84
85impl Serialize for MaxAggregation {
86 fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
87 where
88 S: Serializer,
89 {
90 let mut state = serializer.serialize_struct("MaxAggregation", 0)?;
91 state.serialize_field("max", &self.value)?;
92 if !(self.aggregation.is_null() || self.aggregation.to_string().is_empty()) {
93 state.serialize_field("aggs", &self.aggregation)?;
94 }
95 state.end()
96 }
97}
98
99impl AggregationTrait for MaxAggregation {
100 fn name(&self) -> &str {
101 self.name.as_str()
102 }
103
104 fn build(&self) -> Value {
105 let name = self.name.to_string();
106 json!({ name: self })
107 }
108
109 fn query_name(&self) -> String {
110 "max".to_string()
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117 use crate::aggregation::AggregationTrait;
118
119 #[test]
120 fn test_terms_aggregation() {
121 let agg = MaxAggregation::new("hoge");
122
123 let json = agg.build();
124 println!("{}", json);
125 }
128}