1.默认排序
默认排序是 _score 降序
2.相关字段排序
GET /megacorp/employee/_search
{
“query”:{
“match_all”: {
}
},
“sort”: { “create_time”: { “order”: “asc” }}
}
按照create_time从小到大排序
3.多字段排序
GET /megacorp/employee/_search
{
“query”:{
“match_all”: {
}
},
“sort”: [
{“create_time”: { “order”: “asc” }},
{“age”: { “order”: “desc” }}
]
}
备注:sort字段是用于排序的值(数组)
4.字段多值排序
对数字或者日期可以查询多个值当中min、max、avg、sum排序
GET /megacorp/employee/_search
{
“query”:{
“match_all”: {
}
},
“sort”: { “update_time”: { “order”: “asc”,”mode”:”min” }}
}
备注:update_time字段是多值类型的
5.字符串排序
需要将映射新增raw字段(这样test本身用于索引,raw用于排序)
PUT megacorp/_mapping
{
“properties” : {
“test”:{
“type”: “string”,
“analyzer”: “english”,
“fields”: {
“raw”: {
“type”: “string”,
“index”: “not_analyzed”
}
}
}
}
}
检查
GET megacorp/_mapping/employee
test字段存入类似如下片段
“fields”: {
“raw”: {
“type”: “keyword”
}
},
备注:排序是发生在索引时建立的数据结构当中(列存储)
注意事项:
当使用bool查询的时候,返回的结果中”max_score”:是有值的,当我在bool查询后面加上了sort:
"sort" : [ {
"requestTime" : {
"order" : "desc"
}
} ]
返回的结果中”max_score”的值为null,然后查询官方文档找到了答案:
_score 和 max_score 字段都是 null 。 计算 _score 的花销巨大,通常仅用于排序; 如果我们并不根据相关性排序,所以记录 _score 是没有意义的。如果无论如何你都要计算 _score , 你可以将 track_scores 参数设置为 true 。
官方地址:
https://elasticsearch.cn/book/elasticsearch_definitive_guide_2.x/_Sorting.html