whwright
whwright

Reputation: 561

How to build sibling aggregations using the Elasticsearch Java API?

I want to do a filter aggregation, nested aggregation, and then 3 sibling aggregations. I have tested this and it works using the REST API. Here is the query I used:

{
  "aggs": {
    "filter_agg": {
      "filter": {
        ...
      },
      "aggs": {
        "nested_agg": {
          "nested": {
            "path": "myProperty"
          },
          "aggs": {
            "sibling_agg_1": {
              ...
            },
            "sibling_agg_2": {
              ...
            },
            "sibling_agg_3": {
              ...
            }
          }
        }
      }
    }
  }
}

Now, I want to implement this query using the Java APIs in my codebase. I am not sure how to do sibling aggregations, as the only method available to the FilterAggregationBuilder is subAggregation().

In the context of the Java API is are these sibling aggregations sub aggregations?

The Java code I have started to write looks like this:

client.prepareSearch(index)
    .setTypes(types)
    .setSearchType(SearchType.COUNT)
    .addAggregation(myFilterAggregation
      .subAggregation(AggregationBuilders.nested("nested_agg").path("myProperty"))

and then the only thing I can continue to do to build the SearchRequestBuilder is more subAggregation's - is that the correct way to implement this? The REST API and Java API seem different in this case.

Upvotes: 0

Views: 2459

Answers (1)

Val
Val

Reputation: 217394

You can do it like this by adding sub-aggregation to the nested one (note that I chose a terms aggregation since it wasn't clear from your query DSL what specific aggregation type you're using as the sibling aggregations):

// create the nested aggregation
NestedBuilder nestedAgg = AggregationBuilders.nested("nested_agg").path("myProperty");

// now add each of your sub-aggregation to it
nestedAgg.subAggregation(AggregationBuilders.terms("sibling_agg_1").field("field1"));
nestedAgg.subAggregation(AggregationBuilders.terms("sibling_agg_2").field("field2"));
nestedAgg.subAggregation(AggregationBuilders.terms("sibling_agg_3").field("field3"));

// finally add the nested aggregation to the filter aggregation
client.prepareSearch(index)
    .setTypes(types)
    .setSearchType(SearchType.COUNT)
    .addAggregation(myFilterAggregation
      .subAggregation(nestedAgg);

Upvotes: 2

Related Questions