原文地址: https://www.elastic.co/guide/cn/elasticsearch/guide/current/has-child.html, 版权归 www.elastic.co 所有
英文版地址: https://www.elastic.co/guide/en/elasticsearch/guide/current/has-child.html
英文版地址: https://www.elastic.co/guide/en/elasticsearch/guide/current/has-child.html
请注意:
本书基于 Elasticsearch 2.x 版本,有些内容可能已经过时。
本书基于 Elasticsearch 2.x 版本,有些内容可能已经过时。
通过子文档查询父文档 (has_child)edit
has_child查询和过滤可以通过子文档的内容来查询父文档。例如,我们根据如下查询,可查出所有80后员工所在的分公司:
GET /company/branch/_search
{
"query": {
"has_child": {
"type": "employee",
"query": {
"range": {
"dob": {
"gte": "1980-01-01"
}
}
}
}
}
}
类似于nested查询,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"
}
}
}
}
}
score_mode为默认的none时,会比其他模式快得多,这是因为Elasticsearch不需要计算每一个子文档的评分。只有当你真正需要关心评分结果时,才需要设置score_mode的值为avg、min、max或sum 。
参数 min_children 和 max_children edit
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查询的性能非常接近。