原文地址: https://www.elastic.co/guide/cn/elasticsearch/guide/current/nested-sorting.html, 版权归 www.elastic.co 所有
英文版地址: https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-sorting.html
英文版地址: https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-sorting.html
请注意:
本书基于 Elasticsearch 2.x 版本,有些内容可能已经过时。
本书基于 Elasticsearch 2.x 版本,有些内容可能已经过时。
使用嵌套字段排序edit
尽管嵌套字段的值存储于独立的嵌套文档中,但依然有方法按照嵌套字段的值排序。 让我们添加另一个记录,以使得结果更有意思:
PUT /my_index/blogpost/2
{
"title": "Investment secrets",
"body": "What they don't tell you ...",
"tags": [ "shares", "equities" ],
"comments": [
{
"name": "Mary Brown",
"comment": "Lies, lies, lies",
"age": 42,
"stars": 1,
"date": "2014-10-18"
},
{
"name": "John Smith",
"comment": "You're making it up!",
"age": 28,
"stars": 2,
"date": "2014-10-16"
}
]
}
假如我们想要查询在10月份收到评论的博客文章,并且按照 stars 数的最小值来由小到大排序,那么查询语句如下:
GET /_search
{
"query": {
"nested": {
"path": "comments",
"filter": {
"range": {
"comments.date": {
"gte": "2014-10-01",
"lt": "2014-11-01"
}
}
}
}
},
"sort": {
"comments.stars": {
"order": "asc",
"mode": "min",
"nested_path": "comments",
"nested_filter": {
"range": {
"comments.date": {
"gte": "2014-10-01",
"lt": "2014-11-01"
}
}
}
}
}
}
|
此处的 |
|
|
结果按照匹配的评论中 |
|
|
排序子句中的 |
为什么要在nested_filter中重复查询条件呢?(前面的quer.nested.path/filter已经定义过) 原因是排序发生在查询执行之后。
查询要匹配在10月份收到评论的博客,但返回的是博客文档。
如果不加入nested_filter子句,那么对文档的排序将基于博客的所有评论,而不是仅仅在10月份接收到的评论。