目标:对父类型的文档执行1次搜索,并在结果中包含每个父文档的子文档计数。
(Elasticsearch v5)
数据模型有两种文档类型:父文档和子文档。
我发现我可以进行以下查询:
GET /stack/parent_doc/_search/
{
"query": {
"has_child": {
"type": "child_doc",
"inner_hits": {
"_source": false,
"size": 0
},
"query": {
"match_all": {}
}
}
}
}
我会让所有的父母都回来
至少有一个孩子
以及他们的子文档计数,如下所示。这很接近,但我也想
包括没有孩子的父母。
{
"took": 4077,
"timed_out": false,
"_shards": {
"total": 20,
"successful": 20,
"failed": 0
},
"hits": {
"total": 4974405,
"max_score": 1,
"hits": [{
"_index": "stack",
"_type": "parent_doc",
"_id": "f34e4848-fd63-35a3-84d3-82cbc8796473",
"_score": 1,
"_source": {
"field": "value"
},
"inner_hits": {
"child_doc": {
"hits": {
"total": 1,
"max_score": 0,
"hits": []
}
}
}
},
{
"_index": "stack",
"_type": "parent_doc",
"_id": "f34e1ece-2274-35f6-af37-37138825db20",
"_score": 1,
"_source": {
"field": "value"
},
"inner_hits": {
"child_doc": {
"hits": {
"total": 5,
"max_score": 0,
"hits": []
}
}
}
}
]
}
}
如果我删除
match_all
查询的一部分,那么ES似乎忽略了
has_child
子句,返回所有父文档,无论它们是否有子文档(这是我想要的),但不包含
inner_hits
,所以我不知道计数。
"query": {
"match_all": {}
}
有没有一种方法可以在单个查询中实现这一点?