写点什么

Elasticsearch 查询结果排序

用户头像
escray
关注
发布于: 2021 年 02 月 24 日
Elasticsearch 查询结果排序

Elasticsearch 查询结果排序,部分内容来自 B 站中华石杉 Elasticsearch 顶尖高手系列课程核心知识篇,英文内容来自官方文档。 

默认排序规则


默认情况下,是按照_score 降序排序的


然而,某些情况下,可能没有有用的_score,比如说 filter


GET /_search{  "query": {    "bool": {      "filter": {        "term": {          "author_id": 1        }      }    }  }}
复制代码


当然,也可以是 constant_score


GET /_search{  "query": {    "constant_score": {      "filter": {        "term": {          "author_id": 1        }      }    }  }}
复制代码


定制排序规则


GET /employee/_search{  "query": {    "constant_score": {      "filter": {        "range": {          "age": {            "gte": 30          }        }      }    }  },  "sort": [    {      "join_date": {        "order": "asc"      }    }  ]}
复制代码
Sort search results


Allows you to add one or more sorts on specific fields. Each sort can be reversed as well. The sort is defined on a per field level, with special field name for _score to sort by score, and _doc to sort by index order.


PUT /my-index-000016{  "mappings": {    "properties": {      "post_date": {        "type": "date"      },      "user": {        "type": "keyword"      },      "name": {        "type": "keyword"      },      "age": {        "type": "integer"      }    }  }}
GET /my-index-000016/_search{ "sort": [ { "post_date": { "order": "asc" }}, "user", { "name": "desc" }, { "age": "desc" }, "_score" ], "query": { "term": {"user": "kimchy" } }}
复制代码


Sort Values


The sort values for each document returned are also returned as part of the response.


Sort mode example usage


PUT /my-index-000017
PUT /my-index-000017/_doc/1?refresh{ "product": "chocolate", "price": [20, 4]}
POST /my-index-000017/_search{ "query": { "term": { "product": "chocolate" } }, "sort": [ {"price" : {"order": "asc", "mode": "avg"} } ]}
复制代码


Memory Considerations


When sorting, the relevant sorted field values are loaded into memory. This means that per shard, there should be enough memory to contain them. For string based types, the field sorted on should not be analyzed / tokenized. For numeric types, if possible, it is recommended to explicitly set the type to narrower types(like short, integer and float).


发布于: 2021 年 02 月 24 日阅读数: 22
用户头像

escray

关注

Let's Go 2017.11.19 加入

在学 Elasticsearch 的项目经理

评论

发布
暂无评论
Elasticsearch 查询结果排序