Compute a final script score from the resultant score of a function score query in Elasticsearch

Viewed 346

I'm trying to build an Elasticsearch query that should do following: Calculate a score A which is going to be the sum of multiple functions with constant weights as below

"functions": [
  {
    "filter": {
      "term": {
        "field1": "value1"
      }
    },
    "weight": 10
  },
  {
    "filter": {
      "match": {
        "field2": "value2"
      }
    },
    "weight": 15
  }
]

Suppose A=25 in this case. Now I want to compute an overall score using the score from the above functions as below

score = A * W1 + doc['field3'] * W2 + doc['field4'] * W3

I've tried the following

{
    "explain": true,
    "sort": [
        {
            "_score": "desc"
        }
    ],
    "size": 10,
    "query": {
        "function_score": {
            "query": {
                "bool": {
                    "must": {
                        "match_all": {}
                    }
                }
            },
            "functions": [
                {
                    "filter": {
                        "term": {
                            "field1": "value1"
                        }
                    },
                    "weight": 15
                },
                {
                    "filter": {
                        "term": {
                            "field2": "value2"
                        }
                    },
                    "weight": 10
                },
                {
                    "script_score": {
                        "script": {
                            "source": "_score * params.w1 + doc['field3'].value * params.w2 + doc['field4'].value * params.w3",
                            "params": {
                                "w1": 0.4,
                                "w2": 0.1,
                                "w3": 0.2
                            }
                        }
                    }
                }
            ],
            "score_mode": "sum",
            "boost_mode": "replace"
        }
    }
}

But from what I've observed, the _score in the last script_score doesn't seem to the value from the previous two functions, hence the final score value is different. How can I compute the script_score on the result of the other two functions?

I'm using elasticsearch 7.12 for my use case.

0 Answers
Related