5

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

Ashit_Kumar
  • 601
  • 2
  • 10
  • 28
  • but elastericsearch gives in sorted order according to the score. – Ankur Jyoti Phukan Apr 24 '17 at 14:42
  • @AnkurJyotiPhukan yes I know that .. we have secondary sort property too in ES, want to do secondary sort on the records when they have same value for _score – Ashit_Kumar Apr 24 '17 at 14:52
  • Use [script sorting](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#_script_based_sorting) to manipulate the score. – Andrei Stefan Apr 26 '17 at 00:44

2 Answers2

4

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.

mad
  • 713
  • 7
  • 10
0

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.

K.Morel
  • 33
  • 7