Reputation: 591
I am implementing a project in which the results are to be sorted based on score and in case of same score the result set to be sorted based on date field. The issue arises when the score differs by .00001 i.e by 5th or 6th Decimal position. Is there any way by which we can round off the score derived in Elasticsearch to 4th place of decimal so that the secondary sort can work on it. if not any workaround by which this can be achieved.
Thanks Ashit
Upvotes: 5
Views: 2062
Reputation: 43
I had the same problem, I wanted to round the score to order first by score, then by something else. I used also Mad's answer, with a function_score, but I was still having scores with number after the coma.
According to the documentation, I modified the boost_mode in order to get an integer :
GET /_search
{
"query": {
"function_score": {
"query": { "match_all": {} },
"boost_mode": "replace",
"script_score" : {
"script" : {
"source": "Math.round(_score)"
}
}
}
},
"sort": [
"_score",
{"postdate": "desc"}
]
}
Using this boost_mode helped me to get integers as scores.
Upvotes: 0
Reputation: 743
Here is a working solution using script score to round the actual score
GET /post/_search
{
"query": {
"function_score": {
"query": {
"match": {"title": "example"}
},
"script_score" : {
"script" : {
"source": "Math.round(_score)"
}
}
}
},
"sort": [
"_score",
{"postdate": "desc"}
]
}
In this search example we first sort on the rounded _score then on post.postdate in descending order.
Upvotes: 4