Term Aggregation ElasticSearch

I want to group STATUS field which I am fetching from elasticsearch through Java API. Below is my code

SearchRequest request =
    Requests.searchRequest(ConstantsValue.indexName)
    .types(ConstantsValue._Type)
    .source("{\"_source\" : [\"STATUS\"],\"aggs\": {\"group_by_STATUS\": {\"terms\": {\"field\": \"STATUS\"}}}}");

    SearchResponse response = client.search(request).actionGet();
    for (SearchHit hit : response.getHits()) 
    {         
       System.out.println("Value  :"+hit.sourceAsString());
    }

But it shows all STATUS value in result. The output which I am getting is

Value  :{"STATUS":"SUCCESS"}
Value  :{"STATUS":"SUCCESS"}
Value  :{"STATUS":"ERROR"}
Value  :{"STATUS":"ERROR"}
Value  :{"STATUS":"ERROR"}
Value  :{"STATUS":"WAITING"}
Value  :{"STATUS":"WAITING"}
Value  :{"STATUS":"ERROR"}
Value  :{"STATUS":"WAITING"}
Value  :{"STATUS":"SUCCESS"}

I want each status just once so that I can apply further queries. I have tried my best but can't get it. If I could fetch unique value, that would be help me to find some more attributes. Please help me in this

Hi, you must read Aggregations instead Hits :

StringTerms terms = response.getAggregations().get("group_by_STATUS");
for(Terms.Bucket entry : terms.getBuckets() ) {
String status = entry.getKeyAsString().toString();
}

1 Like

It's working now.. thank you

1 Like