How to Multiply on search Score

I’m trying to modify the score by multiplying with aggregation but it is returning a “null” value for new_score

[
    {
        '$search': {
            'index': 'default', 
            'text': {
                'query': 'Dinosaur', 
                'path': 'title'
            }
        }
    }, {
        '$project': {
            'title': 1, 
            'awards': '$awards.wins', 
            'score': {
                '$meta': 'searchScore'
            }, 
            'new_score': {
                '$multiply': [
                    '$score', '$awards'
                ]
            }
        }
    }
]

Output of the aggregation

{
  "_id": {
    "$oid": "573a139bf29313caabcf33d0"
  },
  "title": "Dinosaur",
  "awards": 4,
  "score": 5.398964881896973,
  "new_score": null
}

Most likely this happens becomes you are using the field score which is computed in the same $project stage. A computed field is only available in the next stage. So rather than

I would try to replace $score with the expression you use to compute score. That is I would

'new_score': {
                '$multiply': [
                    { '$meta': 'searchScore' },
                    '$awards'
                ]
            }
1 Like

I have just notice that awards is also computed. So try

'new_score': {
                '$multiply': [
                    { '$meta': 'searchScore' },
                    '$awards.wins'
                ]
            }

This worked, thank you @steevej

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.