elasticsearch - 使用 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
不起作用
解决方案
您将按字典顺序获得结果,这对于计算机来说非常好,但对人类没有多大意义(期望结果按字母顺序排序)。
用于表示大写字母的字节的值低于用于表示小写字母的字节,因此名称按最低字节优先排序。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"
]
}
]
参考:排序和归类
推荐阅读
- android - 在移动到另一个片段之前出现返回和主页按钮
- android - 我如何在模块化应用程序中访问可绘制文件夹
- node.js - 缺少 ) 在 ejs 模板中的参数列表之后
- c# - ASP.NET 核心 MVC 项目中的错误代码 500.19
- javascript - 如何将现有组件添加到 Vue.JS 中的模板 onclick?
- mysql - 使用 CloudFormation 时如何将 Aurora 无服务器 MySQL 集群从 5.6 升级到 5.7
- reactjs - 无法在浏览器的 cookie 中存储 json Web 令牌
- delphi - 我不能关闭多个 TSpeedButtons
- javascript - 通过 AJAX 提交表单(使用 javascript)
- xml - 使用 spark-scala 在 Databricks 中解析嵌套 XML 文件