yesman
yesman

Reputation: 7829

Order results from query by custom score defined in aggregation

I have a bunch of objects like this:

{
  "id": "12dfb835-6a0c-4047-ab51-d4e34116478e"
  "foo": "bar"
}

{
  "id": "3297b9d2-e05c-4874-91e4-c5b11e8e38c2"
  "foo": "bar"
}

I also have the below query. It basically groups documents by id, then calculates a score based on a script.

{
  "query": {
    "bool": {
      "must": [
        {
          "match_all": {}
        }
      ]
    }
  },
  "aggs": {
    "userID": {
      "terms": {
        "field": "id"
      },
      "aggs": {
        "my-awesome-score": {
          "scripted_metric": {
            "init_script": "state.scores = []",
            "map_script": "state.scores.add(42)",
            "combine_script": "double score = 0; for (s in state.scores) { score += s } return score",
            "reduce_script": "double score = 0; for (a in states) { score += a } return score"
          }
        }
      }
    }
  }
}

This returns results like this:

 "buckets" : [
        {
          "key" : "12dfb835-6a0c-4047-ab51-d4e34116478e",
          "doc_count" : 1,
          "my-awesome-score" : {
            "value" : 42.0
          }
        },
        {
          "key" : "3297b9d2-e05c-4874-91e4-c5b11e8e38c2",
          "doc_count" : 1,
          "my-awesome-score" : {
            "value" : 42.0
          }
        }
        ]

However, in the hits of my query result, all my documents have the default _score of 1. How do I get Elastic to use my-awesome-score as the value for _score for my hits, and sort by that metric?

Upvotes: 0

Views: 243

Answers (1)

Joe - Check out my books
Joe - Check out my books

Reputation: 16895

The aggregations API is separated from the hits/search API so aggregation result cannot be used to influence scores or sorts returned along with the hits.

You could apply script-based sorting but the main takeaway here is that the score is confined to a single hit and unlike a scripted metric aggregation mentioned in your snippet, it'll never have access to other docs' attributes. In other words, your script can generate a score just for the doc it's currently passing through -- independently of the other docs.

Upvotes: 1

Related Questions