Sort by score for composite aggregation results in Elasticsearch

Viewed 2244

Elasticsearch ver: 6.2.4

I have now got the results of composite aggregation by:

GET index/_search
{
  "aggs": {
    "my_buckets": {
      "composite": {
        "sources": [
          {
            "name": {
              "terms": {
                "field": "name.keyword"
                }
            }
          }
        ]
      }
    }
  },
  "query":{

   }
}

To simplify the question, the query part is omitted here.

I can get the results like:

"aggregations": {
    "my_buckets": {
      "buckets": [
        {
          "key": {
            "name": "Bill Gates"
          },
          "doc_count": 1
        },
        {
          "key": {
            "name": "Steven Paul Jobs"
          },
          "doc_count": 1
        },
        {
          "key": {
            "name": "Gates Godar"
          },
          "doc_count": 1
        }
        ]
       }
      }

I notice that the order of the searchresults are not sorted by the sorce (similarity) of the query string.

How can we achieve to sort the composite aggregation results by the score?

Thanks.

1 Answers

The only option I found is to use a pipeline bucket_sort agregation using the values from a max metric agregation reading the score

{
  "aggs": {
    "myBuckets": {
      "composite": {
        "sources": []
      },
      "aggs": {
        "mySort": {
          "bucket_sort": {
            "sort": [
              {
                "max_score": {
                  "order": "desc"
                }
              }
            ]
          }
        },
        "max_score": {
          "max": {
            "script": "_score"
          }
        }
      }
    }
  }
}
Related