深入研究 Elasticsearch 文档,我偶然发现了这一点:
不区分大小写的排序
假设我们有三个用户文档,其名称字段分别包含 Boffey、BROWN 和 bailey。首先,我们将应用字符串排序和多字段中描述的使用 not_analyzed 字段进行排序的技术:
PUT /my_index
{
"mappings": {
"user": {
"properties": {
"name": { //1
"type": "string",
"fields": {
"raw": { //2
"type": "string",
"index": "not_analyzed"
}
}
}
}
}
}
}
- 该
analyzed
name
字段用于搜索。
- 该
not_analyzed
name.raw
字段用于排序。
前面的搜索请求将按以下顺序返回文档:BROWN、Boffey、bailey。这被称为字典顺序而不是字母顺序。从本质上讲,用于表示大写字母的字节的值低于用于表示小写字母的字节,因此名称首先以最低字节排序。
这对计算机可能有意义,但对于那些合理地期望这些名称按字母顺序排序的人来说没有多大意义,而不管大小写。为了实现这一点,我们需要以字节顺序对应于我们想要的排序顺序的方式来索引每个名称。
换句话说,我们需要一个能够发出单个小写标记的分析器:
按照这个逻辑,您需要使用自定义关键字分析器将其小写,而不是存储原始文档:
PUT /my_index
{
"settings" : {
"analysis" : {
"analyzer" : {
"case_insensitive_sort" : {
"tokenizer" : "keyword",
"filter" : ["lowercase"]
}
}
}
},
"mappings" : {
"seing" : {
"properties" : {
"name" : {
"type" : "string",
"fields" : {
"raw" : {
"type" : "string",
"analyzer" : "case_insensitive_sort"
}
}
}
}
}
}
}
现在 ordering byname.raw
应该按字母顺序排序,而不是按字典顺序排序。
使用 Marvel 在我的本地机器上完成的快速测试:
索引结构:
PUT /my_index
{
"settings": {
"analysis": {
"analyzer": {
"case_insensitive_sort": {
"tokenizer": "keyword",
"filter": [
"lowercase"
]
}
}
}
},
"mappings": {
"user": {
"properties": {
"name": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
},
"keyword": {
"type": "string",
"analyzer": "case_insensitive_sort"
}
}
}
}
}
}
}
测试数据:
PUT /my_index/user/1
{
"name": "Tim"
}
PUT /my_index/user/2
{
"name": "TOM"
}
使用原始字段查询:
POST /my_index/user/_search
{
"sort": "name.raw"
}
结果:
{
"_index" : "my_index",
"_type" : "user",
"_id" : "2",
"_score" : null,
"_source" : {
"name" : "TOM"
},
"sort" : [
"TOM"
]
},
{
"_index" : "my_index",
"_type" : "user",
"_id" : "1",
"_score" : null,
"_source" : {
"name" : "Tim"
},
"sort" : [
"Tim"
]
}
使用小写字符串查询:
POST /my_index/user/_search
{
"sort": "name.keyword"
}
结果:
{
"_index" : "my_index",
"_type" : "user",
"_id" : "1",
"_score" : null,
"_source" : {
"name" : "Tim"
},
"sort" : [
"tim"
]
},
{
"_index" : "my_index",
"_type" : "user",
"_id" : "2",
"_score" : null,
"_source" : {
"name" : "TOM"
},
"sort" : [
"tom"
]
}
我怀疑第二个结果在你的情况下是正确的。