|
| 1 | +use crate::aggregation::AggregationTrait; |
| 2 | +use crate::merge; |
| 3 | +use serde::ser::SerializeStruct; |
| 4 | +use serde::{Serialize, Serializer}; |
| 5 | +use serde_json::{json, Map, Value}; |
| 6 | + |
| 7 | +#[derive(Default)] |
| 8 | +pub struct ReverseNestedAggregation { |
| 9 | + name: String, |
| 10 | + aggregation: Value, |
| 11 | +} |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | +impl ReverseNestedAggregation { |
| 16 | + pub fn new(name: &str) -> Self { |
| 17 | + let term = ReverseNestedAggregation { |
| 18 | + name: name.to_string(), |
| 19 | + ..Default::default() |
| 20 | + }; |
| 21 | + term |
| 22 | + } |
| 23 | + |
| 24 | + pub fn append_aggregation<T>(mut self, query: T) -> Self |
| 25 | + where |
| 26 | + T: AggregationTrait, |
| 27 | + { |
| 28 | + let mut values = self.aggregation.clone(); |
| 29 | + merge(&mut values, &query.build()); |
| 30 | + self.aggregation = json!(values); |
| 31 | + self |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | + |
| 36 | +impl Serialize for ReverseNestedAggregation { |
| 37 | + fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> |
| 38 | + where |
| 39 | + S: Serializer, |
| 40 | + { |
| 41 | + let mut state = serializer.serialize_struct("BoolQuery", 0)?; |
| 42 | + state.serialize_field("reverse_nested", &Value::Object(Map::new()))?; |
| 43 | + if !(self.aggregation.is_null() || self.aggregation.to_string().is_empty()) { |
| 44 | + state.serialize_field("aggs", &self.aggregation)?; |
| 45 | + } |
| 46 | + // } |
| 47 | + state.end() |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl AggregationTrait for ReverseNestedAggregation { |
| 52 | + fn name(&self) -> &str { |
| 53 | + self.name.as_str() |
| 54 | + } |
| 55 | + |
| 56 | + fn build(&self) -> Value { |
| 57 | + let name = self.name.to_string(); |
| 58 | + json!({ name: self }) |
| 59 | + } |
| 60 | + |
| 61 | + fn query_name(&self) -> String { |
| 62 | + "reverse_nested".to_string() |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +#[cfg(test)] |
| 67 | +mod tests { |
| 68 | + use super::*; |
| 69 | + use crate::aggregation::AggregationTrait; |
| 70 | + use crate::aggregation::max_aggregation::MaxAggregation; |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn test_nested_aggregation() { |
| 74 | + let agg = ReverseNestedAggregation::new("hoge") |
| 75 | + .append_aggregation(MaxAggregation::new("updated_at").set_field("updated_at")); |
| 76 | + |
| 77 | + let json = agg.build(); |
| 78 | + |
| 79 | + println!("{}", json); |
| 80 | + // assert_eq!(json["test"]["nested"]["field"], "test"); |
| 81 | + // assert_eq!(json["test"]["nested"]["size"], 1); |
| 82 | + } |
| 83 | +} |
0 commit comments