对嵌套文档进行排序和分页

Tar*_*hut 6 elasticsearch

Elasticsearch 具有开箱即用的排序和分页支持。但是,如果我只想检索嵌套对象,对它们进行分页并按其字段排序怎么办?例如:

{
  "mappings" : {
    "library" : {
      "properties" : {
        "name" : {"type": "string"},
        "books" : {
          "type": "nested",
          "properties" : {
            "title" : {"type": "string"},
            "author" : {"type": "string"},
            "year" : {"type": "integer"}
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎么能要求Elasticsearch:“给我最初的10booksoffset = 20title= 'Elasticsearch'排序由year”?嵌套类型是否可能,或者我应该使用较慢的父子关系?

Val*_*Val 7

是的,这是可能的,您可以使用嵌套的内部命中来实现您想要的:

POST index/library/_search
{
    "query" : {
        "nested" : {
            "path" : "books",
            "query" : {
                "match" : {"books.title" : "Elasticsearch"}
            },
            "inner_hits" : {
                "from": 20,
                "size": 10,
                "sort": {"books.year": "asc"}
            } 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢 Val,`inner_hits` 有效,但它仅在其父文档的范围内对嵌套对象进行排序(和分页)。因此,如果查询结果包含 2 个 `library` 文档,每个文档都有一个排序数组,只有它自己的 `books`,但我想要实现的是一个所有 `books` 都匹配的排序数组。那可能吗? (5认同)

Tar*_*hut 6

我发现无法对嵌套文档进行排序和分页。本主题证明了这一点https://discuss.elastic.co/t/nested-objects-hits-inner-hits-and-sorting/32565