首页 > 解决方案 > 使用 elasticsearch 对完整字符串进行排序

问题描述

我正在尝试使用 elasticsearch 对以下项目进行排序

[
    {name: 'Company 1'},
    {name: 'Company 2'},
    {name: 'aa 01'},
    {name: 'aabb'}
]

如果我正在对我的名字进行排序(-> ... 是来自 ES 的排序部分)

aa 01 -> 01
Company 1 -> 1
Company 2 -> 2
aabb -> aabb

我想拥有

aa 01
aabb
Company 1
Company 2

我尝试使用type: 'keyword'(-> ... 是 ES 的排序部分)更改映射

Company 1 -> Company 1
Company 2 -> Company 2
aa 01 -> aa 01
aabb -> aabb

我试图找到其他alertnatives,但它似乎是旧的ES版本,就像这个基于第一个字符的弹性搜索字母排序,index_analyzer或者index不起作用

标签: elasticsearch

解决方案


您将按字典顺序获得结果,这对于计算机来说非常好,但对人类没有多大意义(期望结果按字母顺序排序)。

用于表示大写字母的字节的值低于用于表示小写字母的字节,因此名称按最低字节优先排序。ASCII 表

为此,您需要以字节顺序对应于您想要的排序顺序的方式对每个名称进行索引。换句话说,您需要一个能够发出单个小写标记的分析器。

为要排序的字段创建自定义关键字分析器:

PUT /my_index
{
  "settings" : {
    "analysis" : {
      "analyzer" : {
        "custom_keyword_analyzer" : {
          "tokenizer" : "keyword",
          "filter" : ["lowercase"]
        }
      }
    }
  },
  "mappings" : {
    "_doc" : {
      "properties" : {
        "name" : {
          "type" : "text",
          "fields" : {
            "raw" : {
              "type" : "text",
              "analyzer" : "custom_keyword_analyzer",
              "fielddata": true
            }
          }
        }
      }
    }
  }
}

索引您的数据:

POST my_index/_doc/1
{
  "name" : "Company 01"
}

POST my_index/_doc/2
{
  "name" : "Company 02"
}

POST my_index/_doc/3
{
  "name" : "aa 01"
}

POST my_index/_doc/4
{
  "name" : "aabb"
}

执行排序:

POST /my_index/_doc/_search
{
  "sort": "name.raw"
}

回复:

[
    {
        "_index": "my_index",
        "_type": "_doc",
        "_id": "3",
        "_score": null,
        "_source": {
            "name": "aa 01"
        },
        "sort": [
            "aa 01"
        ]
    },
    {
        "_index": "my_index",
        "_type": "_doc",
        "_id": "4",
        "_score": null,
        "_source": {
            "name": "aabb"
        },
        "sort": [
            "aabb"
        ]
    },
    {
        "_index": "my_index",
        "_type": "_doc",
        "_id": "1",
        "_score": null,
        "_source": {
            "name": "Company 01"
        },
        "sort": [
            "company 01"
        ]
    },
    {
        "_index": "my_index",
        "_type": "_doc",
        "_id": "2",
        "_score": null,
        "_source": {
            "name": "Company 02"
        },
        "sort": [
            "company 02"
        ]
    }
] 

参考:排序和归类


推荐阅读