You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch 5.5如何获取符合条件的父文档A并包含存在的子文档B?

How to Retrieve Parent Docs with Optional Child Inner Hits in Elasticsearch 5.5

Absolutely, you can achieve this requirement in Elasticsearch 5.5! As you noted, a standalone has_child query will only return parent documents that have matching children, but we can combine it with other query components to include parent docs even when they don’t have any children.

Here’s the practical approach:

  • Use a bool query where the must clause applies your specific filter to the parent "A" documents (this ensures only eligible "A" docs are included).
  • Add a should clause containing a has_child query that fetches the "B" child documents (with inner_hits enabled).
  • Set minimum_should_match to 0 so that parent docs without children aren’t excluded—this makes the should clause optional, but still retrieves children when they exist.

Example Query

{
  "query": {
    "bool": {
      "must": [
        // Your specific filter for "A" documents goes here
        { "term": { "some_field": "filter_value" } }
      ],
      "should": [
        {
          "has_child": {
            "type": "B", // Replace with your actual child document type
            "query": { "match_all": {} }, // Use a specific query if you need to filter children
            "inner_hits": {} // Includes the child documents in the response
          }
        }
      ],
      "minimum_should_match": 0
    }
  }
}

Key Details:

  • The must clause guarantees only "A" documents meeting your filter criteria are returned, regardless of whether they have children.
  • The should clause with has_child will add an inner_hits section to the response for any "A" document that has "B" children. If there are no children, this section won’t appear for that parent.
  • If you need to filter which children are included in inner_hits, replace the match_all query in the has_child clause with your desired child-specific filter.

This setup exactly matches what you’re looking for: all filtered "A" docs, with their "B" children included as inner hits when available.

内容的提问来源于stack exchange,提问作者Tofig Hasanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:30:46