How to sort Nulls Last with Elastic?

Viewed 2009

How I can sort String field in elastic search. I need to take it last, but cannot do that.

I try some sorting by ASC but it is not working

Example:

[
{"url":"https://amazon"},
{"url":"https://amazon"},
{"url":null},
{"url":"https://amazon"}
]

my code:

sourceBuilder = sourceBuilder.sort("url", SortOrder.ASC)

And using my code i get the same

I expect to see:
[
{"url":"https://amazon"},
{"url":"https://amazon"},
{"url":"https://amazon"},
{"url":null}
]
1 Answers

try "missing": "_last" in sort

GET testindex/_search
{
  "sort": [
    {
      "url": {
        "order": "asc",
        "missing": "_last"
      }
    }
  ]
}

Mapping

PUT testindex3/_mapping
{
  "properties": {
    "url": {
      "type": "text",
      "fields": {
        "keyword": {
          "type": "keyword",
          "ignore_above": 256
        }
      }
    }
  }
}
Related