I want to set secondary sorting criteria, without deactivating the default behavior, which is sorting by relevance score. In the documentation, all the examples seem to deactivate the default behavior and then sort by the chosen field.
Documentation also gives examples of setting several sorting criteria (the sort attribute of the query is an array of sorting criteria), but I don't see a mention of how to set the first one as sorting by relevance score.
The track_score option allows me to see the relevance score of each hit, but I would like to actually use it as the first ordering rule, and use the other one only for results that have the same relevance score.
You can sort by more than one criteria. The second sort will work whenever the first sort score is the same.
Here is an example:
POST test_stackoverflow_us/_bulk?refresh=true&pretty
{ "index": {}}
{"name":"obama a", "countryCode":"us", "rating":5}
{ "index": {}}
{"name":"obama b", "countryCode":"us", "rating":4}
{ "index": {}}
{"name":"obama ac", "countryCode":"ar", "rating":3}
{ "index": {}}
{"name":"obama ess", "countryCode":"es", "rating":3.5}
GET test_stackoverflow_us/_search
{
"query": {
"bool": {
"must": [
{
"bool": {
"must": [
{
"match_phrase_prefix": {
"name": {
"query": "obama"
}
}
}
],
"boost": 2
}
}
],
"should": [
{
"term": {
"countryCode": {
"value": "US",
"boost": 4
}
}
},
{
"term": {
"countryCode": {
"value": "AR",
"boost": 3
}
}
},
{
"term": {
"countryCode": {
"value": "ES",
"boost": 2
}
}
}
]
}
},
"size": 50,
"sort": [
{
"_score": {
"order": "desc"
}
},
{
"rating": {
"order": "desc"
}
}
]
}