多字段ElasticSearch排序问题

c90pui9n  于 2022-12-22  发布在  ElasticSearch
关注(0)|答案(1)|浏览(204)

在这里找到我的ES设置json:

"properties": {
      "Type": { "type": "keyword" },
      "Name": {
        "type": "text",
        "copy_to": "RawData",
        "fields": {
          "raw": {
            "type": "keyword",
            "normalizer": "case_insensitive"
          }
        },
     "analyzer": "rawdata_index_analyzer",
     "search_analyzer": "search_analyzer"
      },
      "PostalCode": {
        "type": "text",
        "copy_to": "RawData",
        "fields": {
          "raw": {
            "type": "keyword"
          }
        },
        "analyzer": "rawdata_index_analyzer",
        "search_analyzer": "search_analyzer"
      },
      "Address": {
        "type": "text",
        "copy_to": "RawData",
        "fields": {
          "raw": {
            "type": "keyword",
            "normalizer": "case_insensitive"
          }
        },
        "analyzer": "rawdata_index_analyzer",
        "search_analyzer": "search_analyzer"
      },
    }

现在让我们假设我想先按名称排序,然后按地址排序。但这里有一个陷阱,名称不是必填字段,这意味着它可能是空的。在前端,这显示为名称,地址(如果名称存在)或地址(如果名称不存在)块。如果名称是空的,那么排序主要显示在第一个,按地址排序。这是由非空名称和地址跟随。
这使得排序看起来很奇怪,因为在前端,它是一个串连接在一起。
这可以通过创建一个新的索引来解决,连接名称和地址。有没有更好的方法来做到这一点。

Example we have 3 entries: (The right order should be this in the frontend)
name1 zddress1
name2 zddress2
zddress1

 but the order currently is:

zddress1 (because this has a empty '' name)
name1 zddress1
name2 zddress2
afdcj2ne

afdcj2ne1#

这不是最好的解决方案,但我尝试了一个脚本排序的解决方案。您可以给予一下这个解决方案:

POST sort-sample/_doc
{
  "address": "zddress1"
}

POST sort-sample/_doc
{
  "name": "name1",
  "address": "zddress1"
}

POST sort-sample/_doc
{
  "name": "name2",
  "address": "zddress2"
}


GET sort-sample/_search
{
  "sort": [
    {
      "_script": {
        "type": "string",
        "script": {
          "lang": "painless",
          "source": """if (doc['name.keyword'].size() > 0) { return doc['name.keyword'].value } else { return "z"}"""
        },
        "order": "asc"
      }
    },
    {
      "address.keyword": {
        "order": "asc"
      }
    }
  ]
}

相关问题