Has Parent Query

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

译文链接Has Parent Query

贡献者 @小蚊子

has_parent查询接受一个查询和父类型。查询是在父文档空间上执行的,它是被被父类型指定的。查询返回相关父文档匹配到的子文档。剩下的设置选项和has_child查询一样

  1. curl -XGET 'localhost:9200/_search?pretty' -d'
  2. {
  3. "query": {
  4. "has_parent" : {
  5. "parent_type" : "blog",
  6. "query" : {
  7. "term" : {
  8. "tag" : "something"
  9. }
  10. }
  11. }
  12. }
  13. }'

Scoring Capabilities(打分能力)

has_parent也支持打分。默认的是flase,将忽略父文档的分数。这里的分数与has_parent查询(默认为1)的分数等同。如果score设置为true,则匹配的 parent 文档的分数就被聚合在 child 文档中属于匹配的 parent 文档。打分模式可以使用 score_modehas_parent query 中指定:

  1. curl -XGET 'localhost:9200/_search?pretty' -d'
  2. {
  3. "query": {
  4. "has_parent" : {
  5. "parent_type" : "blog",
  6. "score" : true,
  7. "query" : {
  8. "term" : {
  9. "tag" : "something"
  10. }
  11. }
  12. }
  13. }
  14. }'

ignore unmapped(忽略未映射的)

当将ignore_unmapped设置为true时,将忽略一个为被映射的类型,该查询不能匹配任何文档。这个在可能产生不同的映射的多索引查询中起作用。当设置为flase(默认值),如果类型未被映射,则查询将报异常。

Sorting(排序)

子文档不能以父文档中的排序字段来排序。如果你需要通过父文档中的字段来排序子文档,则你可以用function_score查询,通过_score来排序。

通过父文档中的view_count字段排序tags:

  1. curl -XGET 'localhost:9200/_search?pretty' -d'
  2. {
  3. "query": {
  4. "has_parent" : {
  5. "parent_type" : "blog",
  6. "score" : true,
  7. "query" : {
  8. "function_score" : {
  9. "script_score": {
  10. "script": "_score * doc[\u0027view_count\u0027].value"
  11. }
  12. }
  13. }
  14. }
  15. }
  16. }'