54.字符串排序问题

主要知识点:

  • 对一个field索引两次来解决字符串排序问题

   

实际程序中,如果对一个query string进行搜索,然后再按这个query string所搜索的string field进行排序的话,结果往往不准确,因为在搜索时是对query string进行分词后再搜索的,分词后的string field就变成多个单词,再排序的话就是按照这些单词的_source进行排序,而程序希望的排序往往是按照完整的string field进行排序,因此得到的结果就不是程序想要的结果。解决办法是在建立string field时就对同一个string field 建立两个索引,一个设置成分词,用来进行搜索;另一个不分词,用来进行排序。以下用一个简单例子进行完整演示

   

一、建立一个index website,在建立时就对title建立两次索引

PUT /website

{

"mappings": {

"article": {

"properties": {

"title": {

"type": "text",

"fields": {

"raw": {

"type": "string",

"index": "not_analyzed"

}

},

"fielddata": true

},

"content": {

"type": "text"

},

"post_date": {

"type": "date"

},

"author_id": {

"type": "long"

}

}

}

}

}

二、插入数据

PUT /website/article/1

{

"title":"python",

"content":"i love python",

"post_date":"2016-01-01",

"author_id":1101

}

PUT /website/article/2

{

"title":"i love es ",

"content":"i love es ",

"post_date":"2016-01-01",

"author_id":1101

}

PUT /website/article/3

{

"title":"scrapy",

"content":"i love scrapy",

"post_date":"2016-01-01",

"author_id":1101

}

   

三、进行搜索,并按titel.raw进行排序

GET /website/article/_search

{

"query": {

"match_all": {}

},

"sort": [

{

"title.raw": {

"order": "desc"

}

}

]

}

可以发现结果就是按完整的title进行排序

原文地址:https://www.cnblogs.com/liuqianli/p/8472256.html