How to access Aggregations result with elasticSearch java api in SearchResponse? How to access Aggregations result with elasticSearch java api in SearchResponse? elasticsearch elasticsearch

How to access Aggregations result with elasticSearch java api in SearchResponse?


Looking at the ES source on Github I see the following in their tests:

SearchResponse response = client().prepareSearch("idx").setTypes("type")                .setQuery(matchAllQuery())                .addAggregation(terms("keys").field("key").size(3).order(Terms.Order.count(false)))                .execute().actionGet();Terms  terms = response.getAggregations().get("keys");Collection<Terms.Bucket> buckets = terms.getBuckets();assertThat(buckets.size(), equalTo(3));


If anyone wonder about accessing actual documents count out of these buckets following code might help.

Terms  terms = response.getAggregations().get("agg1");Collection<Terms.Bucket> buckets = terms.getBuckets();for (Bucket bucket : buckets) {    System.out.println(bucket.getKeyAsText() +" ("+bucket.getDocCount()+")");}


In case anyone is looking for a sum aggregation, it's as easy as assigning the result to a org.elasticsearch.search.aggregations.metrics.sum.Sum variable:

ElasticConnector connector = ... // initialize ES connectorSearchResponde response = connector.getClient()    .prepareSearch(...)    .setQuery(...)    .addAggregation(AggregationBuilders.sum("my_sum").field(...))    .get();Sum sum = response.getAggregations().get("my_sum");double result = sum.getValue();