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
boolquery where themustclause applies your specific filter to the parent "A" documents (this ensures only eligible "A" docs are included). - Add a
shouldclause containing ahas_childquery that fetches the "B" child documents (withinner_hitsenabled). - Set
minimum_should_matchto 0 so that parent docs without children aren’t excluded—this makes theshouldclause 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
mustclause guarantees only "A" documents meeting your filter criteria are returned, regardless of whether they have children. - The
shouldclause withhas_childwill add aninner_hitssection 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 thematch_allquery in thehas_childclause 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
相关产品推荐
相关产品推荐

