Ekenstein
Ekenstein

Reputation: 541

Elasticsearch alter the score for a filtered query

I have a mapping that looks something like:

"foo" : {
    "name" : {
        "type" : "string",
    },

    "points": {
        "type" : "double"
    }
}

What we are currently doing is to use filtered queries to search on names. In addition to this we now want to alter the score for each result depending on what points contain.

So, if points is 3.0, we wish to have _score + 3 and so on.

The query can look something like:

{
    "from": 0,
    "size": 50,
    "query": {
        "filtered": {
            "query": {
                "match_all": {}
            },
            "filter": {
                //filters
            }
        }
    }
}

Upvotes: 0

Views: 403

Answers (1)

Val
Val

Reputation: 217254

You can use the function_score query to achieve this. It's pretty easy and goes like this:

{
  "query": {                                 
    "function_score": {
      "filter": {                            <--- your filters go in here
         //your filters
      },
      "boost_mode": "sum",                   <--- the script score will be summed with the query score
      "script_score": "doc.points.value"     <--- script score returns the value of the points field
    }
  }
}

Since you have a single function, it is also possible to use the default boost_mode (i.e. multiply) and have the script score return the summed score directly:

{
  "query": {                                 
    "function_score": {
      "filter": {                                     <--- your filters go in here
         //your filters
      },
      "script_score": "_score + doc.points.value"     <--- script score returns the value of the points field
    }
  }
} 

Upvotes: 1

Related Questions