按分数排序聚合桶

Ordering Aggregation Buckets by Score

是否可以按分数对聚合桶进行排序?

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

我看到 this document 解释了默认顺序是 doc_count,但我不知道是否可行以及如何按分数对桶进行排序。

是的,可以这样做:

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