如果对一个text field进行排序,结果往往不准确,因为分词后是多个单词,再排序就不是我们想要的结果了
通常解决方案是,将一个text field建立两次索引,一个分词,用来进行搜索;一个不分词,用来进行排序
创建索引
在ES6中没有String类型了,如果是不能被检索需要定义为keyword
PUT /web5
{
"mappings": {
"article": {
"properties": {
"title": {
"type": "text",
"fields": {
"raw": {
"type": "keyword"
}
},
"fielddata": true
},
"content": {
"type": "text"
},
"post_date": {
"type": "date"
},
"author_id": {
"type": "long"
}
}
}
}
}
查询出来的数据
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 1,
"hits": [
{
"_index": "web5",
"_type": "article",
"_id": "2",
"_score": 1,
"_source": {
"title": "two article",
"content": "this is my two article",
"post_date": "2018-11-02",
"author_id": 123
}
},
{
"_index": "web5",
"_type": "article",
"_id": "1",
"_score": 1,
"_source": {
"title": "one article",
"content": "this is my one article",
"post_date": "2018-11-01",
"author_id": 123
}
},
{
"_index": "web5",
"_type": "article",
"_id": "3",
"_score": 1,
"_source": {
"title": "three article",
"content": "this is my three article",
"post_date": "2018-11-03",
"author_id": 123
}
}
]
}
}
正常查询请求
GET /web5/article/_search
{
"query": {
"match_all": {}
},
"sort": [
{
"title": {
"order": "desc"
}
}
]
}
排序字段
全文查询请求
GET /web5/article/_search
{
"query": {
"match_all": {}
},
"sort": [
{
"title.raw": {
"order": "desc"
}
}
]
}
排序字段
“fields”: {“raw”: {“type”: “keyword”}} ,#可以对一个字段提供多种索引模式,使用text类型做全文检索,也可使用keyword类型做聚合和排序
“fielddata” : false, #针对text字段加快排序和聚合(doc_values对text无效);此项官网建议不开启,非常消耗内存