Home > Software design >  Add Nested To Aggregations
Add Nested To Aggregations

Time:06-28

I am trying to build the below aggregation

   "aggregations":{
      "main_aggregation":{
         "nested":{
            "path":"names"
         },
         "aggregations":{
            ...
         }
         
      }
   }

The code I am using for the nested is as below;

 NestedAggregationBuilder nested = AggregationBuilders.nested("path", "names");

However, I could not manage to add the nested block to the main aggregation ("main_aggregation").

Question 1: Is this the correct way of creating the nested block?

Question 2: How can I add the nested block to the "main_aggregation"?

Any help would be great!

CodePudding user response:

You can use below code:

AggregationBuilder an = AggregationBuilders.nested("main_aggregation", "names")
            .subAggregation(AggregationBuilders.terms("country").field("country"));

Above code will generate below aggregation query same as your requirement:

{
    "aggregations": {
        "main_aggregation": {
            "nested": {
                "path": "names"
            },
            "aggregations": {
                "country": {
                    "terms": {
                        "field": "country",
                        "size": 10
                    }
                }
            }
        }
    }
}
  • Related