1

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.

Aftaab Zia
  • 11
  • 1
  • It is not working by passing the last score to next functions. It sums all functions' scores at the end. For this case, mutliplying 0.4 with weights of first two functions and getting the sum of all functions can work mathematically. If you set weight of first function to 15 * 0.4, weight of the second function to 10 * 0.4 and script to `doc['field3'].value * params.w2 + doc['field4'].value * params.w3`, you can get the result you want. – YD9 Mar 09 '22 at 08:19

0 Answers0