'Elasticsearch sort result by non mandatory fields

Lets imagine that we have the following documents:

 [{
    "translations": {
      "0": "3 Trunk.",
      "4": "1 Trunk. 3"
    },
    "defaultValue": "3 Trunk."
  },
  {
    "translations": {
      "0": "3 Trunk.",
      "4": "DDDDD"
    },
    "defaultValue": "3 Trunk."
  },
  {
    "translations": {
      "0": "3 Trunk."
    },
    "defaultValue": "3 Trunk."
  }]

And we try to sort:

 "sort": [
        {
            "translations.4.sortword": {
                "unmapped_type": "keyword",
                "missing": "_last",
                "order": "asc"
            }
        },
        {
            "translations.0.sortword": {
                "unmapped_type": "keyword",
                "missing": "_last",
                "order": "asc"
            }
        }
    ]

In UI we use translated value or default([0]) so we will see

1 Trunk. 3

DDDDD

3 Trunk.

How I can sort it in the correct way? Is there some projection/aggregation like in mongo which can help to do this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source