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.