Elasticsearch 字符串排序问题
程序员文章站
2022-05-12 15:57:49
...
对一个字符串类型的字段进行排序通常不准确,因为已经被分词成多个词条了
解决方式:对字段索引两次,一次索引分词(用于搜索),一次索引不分词(用于排序)
//不同查询
GET /lib3/_search
//默认的text是进行了分词,进行排序将报错
GET /lib3/user/_search
{
"query": {
"match_all": {}
},
"sort": [
{
"interests": {
"order": "desc"
}
}
]
}
//由于不能直接修改mapping,先删除索引
DELETE lib3
//创建索引时,对字段索引两次
PUT /lib3
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 0
},
"message": {
"user": {
"properties": {
"name": {
"type": "text"
},
"address": {
"type": "text"
},
"age": {
"type": "integer"
},
"birthday": {
"type": "date"
},
"interests": {
"type": "text", //text类型默认分词,用于搜索
"fields": { //keyword默认不分词,用于排序
"raw": {
"type": "keyword"
}
},
"fielddate": true
}
}
}
}
}
//将按照整个字符串进行排序
GET /lib3/user/_search
{
"query": {
"match_all": {}
},
"sort": [
{
"interests.raw": {
"order": "asc"
}
}
]
}