I guess you are trying to group by a field in elasticsearch, you can do it by using Terms aggregation.
Here is how to do using query dsl,
POST _search
{
"aggs": {
"genders": {
"terms": {
"field": "gender"
},
"aggs": {
"top_tag_hits": {
"top_hits": {
"_source": {
"include": [
"include_fields_name"
]
},
"size": 100
}
}
}
}
}
}
and gender is field in document,
Its response can be
{
...
"aggregations" : {
"genders" : {
"buckets" : [
{
"key" : "male",
"doc_count" : 10,
"tag_top_hits":{"hits":...}
},
{
"key" : "female",
"doc_count" : 10,
"tag_top_hits":{"hits":...}
},
]
}
}
}
Using Java api, I've added tophits aggregation for your comment. (but not in query dsl)
client.prepareSearch("index").setTypes("types").addAggregation(
AggregationBuilders.terms("agg_name").field("gender").subAggregation(
AggregationBuilders.topHits("documents").setSize(10)
)
).execute(new ActionListener<SearchResponse>() {
@Override
public void onResponse(SearchResponse response) {
Terms agg_name_aggregation=response.getAggregations().get("agg_name");
for (Terms.Bucket bucket : agg_name_aggregation.getBuckets()) {
TopHits topHits=bucket.getAggregations().get("documents");
System.out.println("term = " + bucket.getKey());
// do what you want with top hits..
}
}
@Override
public void onFailure(Throwable e) {
e.printStackTrace();
}
});
Hope this helps!!