Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a way to retrieve the aggregations' buckets in a search response, with the java API ?

{
  "took" : 185,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 200,
    "max_score" : 1.0,
    "hits" : [...]
  },
  "aggregations" : {
    "agg1" : {
      "buckets" : [...]
    },
    "agg2" : {
      "buckets" : [...]
    }
  }
}

Currently, it's possible to get the aggregations but I can't figure out how to get the buckets.

Current 1.0 version of ElasticSearch (v1.0.0.Beta2) is still a beta version, and maybe this feature still has to be added, but didn't find info on that point too.

like image 541
ThomasC Avatar asked Jan 09 '14 11:01

ThomasC


2 Answers

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));
like image 147
mconlin Avatar answered Nov 17 '22 17:11

mconlin


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()+")");
}
like image 30
Charith De Silva Avatar answered Nov 17 '22 18:11

Charith De Silva