Search code examples
elasticsearchelasticsearch-6

Ordering Aggregation Buckets by Score


Is it possible to order the aggregation bucket by score?

"aggs": {
    "UnitAggregationBucket": {
      "terms": {
        "field": "unitId",
        "size": 10,
        /* "order": order by max score documents per bucket */
      }
    }
  }

I have seen this document which explains the default order is doc_count, but I cannot find out if it is possible and how to order the buckets by score.


Solution

  • Yes, it is possible to do that like this:

    {
      "size": 0,
      "query": {
        ...
      },
      "aggs": {
        "UnitAggregationBucket": {
          "terms": {
            "field": "unitId",
            "size": 10,
            "order": {
              "score": "desc"
            }
          },
          "aggs": {
            "score": {
              "max": {
                "script": "_score"
              }
            }
          }
        }
      }
    }