Search code examples
javaelasticsearchelasticsearch-java-apielasticsearch-jest

ElasticSearch Bucket Aggregations


I'm new to ElasticSearch aggregations.

By going through the documentation I understand that in my use case I need to use Bucket Aggregations.

I however, am unable to find any solid documentation / code which provides examples how to build a query for this. I'm using Jest as my Client to talk to ElasticSearch.

My use case is :

Suppose I have the following documents :

{ name : 'abc' , field_1: '123' , field_2 : '3211' } , { name : 'abc' , field_1: '33' , field_2 : '011' }, { name : 'xyz' , field_1: '33' , field_2 : '011' } , { name : 'xyz' , field_1: '33' , field_2 : '011' }

When I query ES I would want the results to be grouped by the field 'name'

So the returned document would be something of the sort :

{
 { name : 'abc' , 
     aggregation : { 
     { 
           field_1 : '123' , field_2 : '3211' 
       } ,

     { 
           field_1 : '33' , field_2 : '011' 
       } ,

}

} 

,

{ name : 'xyz' , 
     aggregation : { 
     { 
           field_1 : '123' , field_2 : '3211' 
       } ,

     { 
           field_1 : '33' , field_2 : '011' 
       } ,

}

}

}

I couldn't find any sample code using Jest / using SearchSourceBuilders in ElastcSearch ( which Jest can use)

Any help would be greatly appreciated!


Solution

  • Take a look at this merged pull request to Jest. You can find a good code example there. It is not exactly the same solution as you describe in your question, but it is the only possible way to achieve results close to what you want. Also, take a look at the test to the pull request. for(Entry entry : termBuckets) { TopHitsAggregation topHitAgg = entry.getTopHitsAggregation("top_hits_test"); List<String> hits = topHitAgg.getSourceAsStringList(); assertEquals(2, hits.size()); } Seems close to what you want.