Nested Query(嵌套查询)

原文链接 https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html

译文链接 Nested Query(嵌套查询)

贡献者 小蚊子

Nested query allows to query nested objects / docs (see nested mapping). The query is executed against the nested objects / docs as if they were indexed as separate docs (they are, internally) and resulting in the root parent doc (or parent nested mapping). Here is a sample mapping we will work with:

嵌套查询允许查询被嵌套的对象/文档(参考nested mapping)。查询是在被索引分隔开的文档/嵌套的对象(内部)执行的,返回的结果是根文档(或者父嵌套映射)。这里是我们将用到的映射示例:

  1. curl -XPUT 'localhost:9200/my_index?pretty' -d'
  2. {
  3. "mappings": {
  4. "type1" : {
  5. "properties" : {
  6. "obj1" : {
  7. "type" : "nested"
  8. }
  9. }
  10. }
  11. }
  12. }'

这里是嵌套查询用法的示例:

  1. curl -XGET 'localhost:9200/_search?pretty' -d'
  2. {
  3. "query": {
  4. "nested" : {
  5. "path" : "obj1",
  6. "score_mode" : "avg",
  7. "query" : {
  8. "bool" : {
  9. "must" : [
  10. { "match" : {"obj1.name" : "blue"} },
  11. { "range" : {"obj1.count" : {"gt" : 5}} }
  12. ]
  13. }
  14. }
  15. }
  16. }
  17. }'

查询的路径指向了被嵌套的对象路径,查询包括查询将运行在匹配上的嵌套的文档和连接跟文档的直接路径上。注意任何在查询内部引用的字段必须使用全路径。

score_mode允许我们设置可以内部子嵌套对匹配到的父嵌套的文档的影响。默认是 avg,但是也可以是 sum,min,max,以及 none。

多层级的嵌套自动被支持,检测,如果一个嵌套查询存在另一个嵌套查询中,将产生一个内部嵌套查询去自动匹配有联系的嵌套(不是根)。