Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we Round off the score in Elasticsearch

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

like image 395
Ashit_Kumar Avatar asked Apr 24 '17 12:04

Ashit_Kumar


People also ask

How are Elasticsearch scores calculated?

Before scoring documents, Elasticsearch first reduces the set of candidate documents by applying a boolean test that only includes documents that match the query. A score is then calculated for each document in this set, and this score determines how the documents are ordered.

How do I change my Elasticsearch score?

You can achieve it simply by removing the boost_mode parameter, the default boost_mode is to multiply the _score with whatever value comes out of the field_value_factor function.

What is score in Elasticsearch query?

In Elasticsearch, all document scores are positive 32-bit floating point numbers. If the script_score function produces a score with greater precision, it is converted to the nearest 32-bit float. Similarly, scores must be non-negative. Otherwise, Elasticsearch returns an error.

What is Max score in Elasticsearch?

The idea is quite simple: say that you want to collect the top 10 matches, that the maximum score for the term "elasticsearch" is 3.0 and the maximum score for the term "kibana" is 5.0.


1 Answers

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.

like image 159
mad Avatar answered Oct 12 '22 15:10

mad