Sorting on missing value with default fallback

Hi, is there a way in elasticsearch to "fallback" on a default field value when sorting on a missing field?

For instance, let assume I have a field A and a field B in my mapping, which are mutually exclusive so that each document in my index has either A or B defined. I can sort singularly on both of them, but is there a way of combining both at the same time? Something like, sort on field A if present, otherwise sort on field B.

I tried using inline script but without luck so far. Is there even a way of achieving what I would like to do?

Thank you.

You can specify multiple sort values: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#_missing_values

The sorts are applied sequentially. E.g. this:

GET /my_index/my_type/_search
{
    "sort" : [
        { "field_a" : {"order" : "asc"}},
        { "field_b" : {"order" : "desc"}},
        "_score"
    ],
    "query" : {
        "term" : { "user" : "foo" }
    }
}

will first sort documents by field_a ascending. By default, all documents missing field_a will be sorted to the last position (you can change that behavior if you want). Next, all ties are sorted by field_b descending, which includes the documents that were lacking field_a (because they are all tied for last). Finally, any remaining ties are sorted by their natural full-text score.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.