Has Child Query

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

译文链接 http://www.apache.wiki/pages/editpage.action?pageId=5505029

贡献者 @小蚊子

has_child 过滤接受一个查询和child类型来执行,产生其子文档能匹配查询的父文档。这有一个例子:

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

Scoring capabilities(打分能力)

has_child也支持打分。支持的模式有min,max,sum,avg,或者none.默认的是none,产生和以前的版本相同的行为。如果打分模式设置为none意外的其他值,匹配子文档的所有分数将被聚合在有关联的父文档。has_child查询中的score_mode字段指定打分类型的值:

  1. curl -XGET 'localhost:9200/_search?pretty' -d'
  2. {
  3. "query": {
  4. "has_child" : {
  5. "type" : "blog_tag",
  6. "score_mode" : "min",
  7. "query" : {
  8. "term" : {
  9. "tag" : "something"
  10. }
  11. }
  12. }
  13. }
  14. }'

Min/Max Children(最小/最大子文档)

has_child 查询允许你指定最小或者(和)最大数目的子文档需要匹配,来使父文档被当做一个匹配:

  1. curl -XGET 'localhost:9200/_search?pretty' -d'
  2. {
  3. "query": {
  4. "has_child" : {
  5. "type" : "blog_tag",
  6. "score_mode" : "min",
  7. "min_children": 2,
  8. "max_children": 10,
  9. "query" : {
  10. "term" : {
  11. "tag" : "something"
  12. }
  13. }
  14. }
  15. }
  16. }'
  1. min_childrenmax_children都是可选的

min_childrenmax_children 参数可以和score_mode参数结合使用

ignore unmapped(忽略未映射)

如果把Ignore_unmapped选项设置为true,将忽略一个没被索引的类型,从该查询中不会匹配任何文档。这个选项在查询不同的映射导致的多索引查询时有用。当设置为false(默认值),如果类型没有被映射时查询将抛出异常。

Sorting(排序)

父文档不能以经常作为子文档的排序字段来排序。如果你需要用子文档中的字段来给父文档排序时,你可以用function_score查询,使用_score来排序。

根据子文档的click_count字段排序:

  1. curl -XGET 'localhost:9200/_search?pretty' -d'
  2. {
  3. "query": {
  4. "has_child" : {
  5. "type" : "blog_tag",
  6. "score_mode" : "max",
  7. "query" : {
  8. "function_score" : {
  9. "script_score": {
  10. "script": "_score * doc[\u0027click_count\u0027].value"
  11. }
  12. }
  13. }
  14. }
  15. }
  16. }'