Search code examples
elasticsearch

ElasticSearch querying documents with the highest value in a field


I'm pretty new to ElasticSearch (here using 8.12) and just trying to grasp it's basics.
Is there a way to query documents from ElasticSearch so that the documents with the highest values receive the biggest scoring values?
So that for the following documents:

{ "id": 1, "rating": 2.134, "prev_rating": 3.321 },
{ "id": 2, "rating": 3.134, "prev_rating": 3.912 },
{ "id": 3, "rating": 4.134, "prev_rating": 4.321 },
{ "id": 4, "rating": 4.434, "prev_rating": 4.421 },
{ "id": 5, "rating": 4.834, "prev_rating": 4.921 }

would receive the following scores
(scores not to scale, but to highlight how I expect for these documents to get scored during the query):

{ "id": 5, "rating": 4.834, "prev_rating": 4.921, "_score": 20 }
{ "id": 4, "rating": 4.434, "prev_rating": 4.421, "_score": 13 },
{ "id": 3, "rating": 4.134, "prev_rating": 4.321, "_score": 10 },
{ "id": 2, "rating": 3.134, "prev_rating": 3.912, "_score": "should not event be scored/selected" },
{ "id": 1, "rating": 2.134, "prev_rating": 3.321, "_score": "should not event be scored/selected" },

I tried using "boost" in a query, but it just resulted in essentially the same response with bigger values for the "_score".
And "range" query does not seem to score documents higher for bigger value of either "rating" or "prev_rating"
Example query:

{
   "query":{
      "bool":{
         "must":[
            {
               "range":{
                  "prev_rating":{
                     "gte":4.1
                  }
               }
            },
            {
               "range":{
                  "rating":{
                     "gte":4
                  }
               }
            }
         ]
      }
   }
}

Solution

  • It sounds like you might want to use a rank_feature for that. A rank_feature is a special field type and query that score documents based on one or more stored "ranking" field.

    You can also achieve similar results with a script score