I want to code elasticsearch aggregation in JAVA API to find field collapsing and result grouping.
The json aggregation code is shown below I've got these code from elasticsearch docs
'dedup_by_score' aggregation has sub aggregation called 'top_hit' aggregation and use this in terms aggregation for bucket ordering.
... some query
"aggs": {
"dedup_by_score": {
"terms": {
"field": "keyword",
"order": {
"top_hit": "desc"
},
"size": 10
},
"aggs": {
"top_hit": {
"max": {
"script": {
"source": "_score"
}
}
}
}
}
}
I want to convert this json query into JAVA
And this is what I've already tried in JAVA
AggregationBuilder aggregation = AggregationBuilders.terms("dedup_by_score")
.field("keyword")
.order(BucketOrder.aggregation("top_hit", false))
.size(10)
.subAggregation(
AggregationBuilders.topHits("top_hit")
.subAggregation(
AggregationBuilders.max("max").script(new Script("_score"))
)
);
But I got an error like below from Elasticsearch
{
"type":"aggregation_initialization_exception",
"reason":"Aggregator [top_hit] of type [top_hits] cannot accept sub-aggregations"
}
How can I fix this Java code? I'm using Elasticsearch 6.7.1 version now.
Thanks in advance
Top hit aggs can't have sub-aggs. Try this:
AggregationBuilder aggregation = AggregationBuilders.terms("dedup_by_score")
.field("keyword")
.order(BucketOrder.aggregation("top_hit", false))
.size(10)
.subAggregation(
AggregationBuilders.max("max").script(new Script("_score"))
.subAggregation(
AggregationBuilders.topHits("top_hit")
)
);