首页 > 解决方案 > 如何使用 Elastic 对 Null 进行最后排序?

问题描述

如何在弹性搜索中对字符串字段进行排序。我需要把它放在最后,但不能那样做。

我尝试按 ASC 进行排序,但它不起作用

例子:

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

我的代码:

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

并使用我的代码我得到相同的

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

标签: javaspringspring-bootsortingelasticsearch

解决方案


尝试 "missing": "_last" 排序

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

映射

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

推荐阅读