Elastic Search sort documents with same score using another field value
Asked Answered
U

2

4

I'm using elastic search and I would like to sort documents having same score to the query shown below, on the basis of higher number of - "likes" field - integer type stored in all documents. Code -

query: {
                multi_match: {
                        query: "some cooler",
                        type: "most_fields",
                        fields: ["info1", "info2", "info3"]
                }
        }
Unfold answered 20/7, 2016 at 21:46 Comment(0)
M
10

You should check the sort documentation

Just add a sort section on json sorting by score followed by your custom field.

{
    "query" : {...},
    "sort" : [
        "_score",
        { "likes" : {"order" : "desc"}}
    ]
}

score order is 'desc' by default. Other fields are 'asc' by default so you need to define 'desc' order for your 'likes' field if that's what you want.

Mog answered 21/7, 2016 at 2:57 Comment(0)
S
0

You can simply use _score in your sort criteria, like this:

{
  ...
  "sort": [
    "_score",
    "another_field"
  ]
}

This will sort all documents by descending score and, for those documents that have the exact same score, they will be sorted by the another_field as a tie-breaker. By default that another_field will be sorted in ascending order but this can be customized (read the docs for more details).

Scoring consistency

Note that ElasticSearch does not guarantee consistent scoring, so this might be problematic when you want to use a field as a tie-breaker for score, particularly if you are making a boolean query using should.

You might expect documents that match the should criteria in the exact same way to have the same score. But, if the index has multiple shards, scores might not be exactly the same (more information here). This is normally not a problem when ordering only by score because the scores should be similar, but if you are using a tie-breaker, then the tie-breaker field will only work within the documents of one shard, in other words, documents that match the criteria in the same way might not be ordered by your tie-breaker, but instead by shard first and then by the tie-breaker field.

This can be a problem if you really care about the order of the tie-breaker field. To avoid this problem you might want to use the dfs_query_then_fetch search type. More detailed explanation here.

State answered 24/6 at 22:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.