Elasticsearch - 获取 child 个文档的计数,即使计数为零

Elasticsearch - get count of child docs, even if count is zero

Objective:对Parent类型的文档执行1次搜索,结果中包含每个parent文档的children的计数。

(Elasticsearch v5)

数据模型有 2 种文档类型:Parent 和 Child。

我发现我可以执行以下查询:

GET /stack/parent_doc/_search/
{
  "query": {
    "has_child": {
      "type": "child_doc",
      "inner_hits": {
        "_source": false,
        "size": 0
      },
      "query": {
        "match_all": {}
      }
    }
  }
}

并且我取回了所有 parent 的 ,它们至少有一个 child 及其 child 文档的数量,如下所示。这非常接近,但我还想要 parents,其中不包含 children。

{
    "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 子句,返回所有 Parent 文档,无论它们是否具有 children(这是我想要的)但没有 inner_hits,所以我不知道计数。

  "query": {
    "match_all": {}
  }

有没有办法在单个查询中执行此操作?

您需要使用 bool/should 包括您当前的查询加上另一个否定它的查询:

POST /stack/_search/
{
  "query": {
    "bool": {
      "should": [
        {
          "has_child": {
            "type": "child_doc",
            "inner_hits": {
              "_source": false,
              "size": 0
            },
            "query": {
              "match_all": {}
            }
          }
        },
        {
          "bool": {
            "must_not": {
              "has_child": {
                "type": "child_doc",
                "query": {
                  "match_all": {}
                }
              }
            }
          }
        }
      ]
    }
  }
}

现在你会得到所有的parent,不管他们有没有children,还会得到每个parent有多少children的信息。