Emin Mastizada
Emin Mastizada

Reputation: 1405

change _score in elasticsearch to make equal to doc's score field

I have score (integer) field in data, I'm getting data from api, and posting it directly to localhost:9200//listings/ And I want the item _score to be equal to score field in data.

For now a solution is to add ?sort=score:desc to url

Upvotes: 2

Views: 2701

Answers (1)

Val
Val

Reputation: 217544

One solution is to use a function_score query, where you replace the default _score using a field_value_factor score function. It goes like this:

curl -XPOST localhost:9200/listings/_search -d '{
  "query": {
    "function_score": {
      "functions": [
        {
          "field_value_factor": {
              "field": "score",         <---- we use the score field instead
              "factor": 1,              <---- take the exact same score
              "missing": 1              <---- use 1 as score if the score field is missing
          }
        }
      ],
      "query": {
        "match_all": {}
      },
      "boost_mode": "replace"           <---- we're replacing the default _score
    }
  }
}'

So we're basically computing the score using the score field multiplied by 1 and if any document doesn't have the score field we just assume the score to be 1 (you can change that to whatever makes more sense in your case).

UPDATE

According to your comment, you need the _score to be multiplied by the document's score field. You can achieve it simply by removing the boost_mode parameter, the default boost_mode is to multiply the _score with whatever value comes out of the field_value_factor function.

If you need to completely replace the default scoring mechanism to be based on your score field instead, there's a more complex way using the similarity module, where you can define another similarity algorithm solely for your score field. There is a great blog post explaining the nitty gritty details of the similarity module.

Upvotes: 2

Related Questions