通过子文档查询父文档 | Elasticsearch: 权威指南 | Elastic
2025-10-30
has_child 的查询和过滤可以通过子文档的内容来查询父文档。
例如,我们根据如下查询,可查出所有80后员工所在的分公司:
GET /company/branch/_search
{
"query": {
"has_child": {
"type": "employee",
"query": {
"range": {
"dob": {
"gte": "1980-01-01"
}
}
}
}
}
}类似于 nested query ,has_child 查询可以匹配多个子文档
,并且每一个子文档的评分都不同。但是由于每一个子文档都带有评分,这些评分如何规约成父文档的总得分取决于 score_mode 这个参数。该参数有多种取值策略:默认为 none ,会忽略子文档的评分,并且会给父文档评分设置为 1.0 ;
除此以外还可以设置成 avg 、 min 、 max 和 sum 。
下面的查询将会同时返回 london 和 liverpool ,不过由于 Alice Smith 要比 Barry Smith 更加匹配查询条件,因此 london 会得到一个更高的评分。
GET /company/branch/_search
{
"query": {
"has_child": {
"type": "employee",
"score_mode": "max",
"query": {
"match": {
"name": "Alice Smith"
}
}
}
}
}has_child 的查询和过滤都可以接受这两个参数:min_children 和 max_children 。
使用这两个参数时,只有当子文档数量在指定范围内时,才会返回父文档。
如下查询只会返回至少有两个雇员的分公司:
GET /company/branch/_search
{
"query": {
"has_child": {
"type": "employee",
"min_children": 2,
"query": {
"match_all": {}
}
}
}
}带有 min_children 和 max_children 参数的 has_child 查询或过滤,和允许评分的 has_child 查询的性能非常接近。
官方地址:https://www.elastic.co/guide/cn/elasticsearch/guide/current/has-child.html