Elasticsearch Subaggregation of tophits JAVA API not working

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")
    .order(BucketOrder.aggregation("top_hit", false))
            AggregationBuilders.max("max").script(new Script("_score"))

But I got an error like below from Elasticsearch

"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

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.