Elasticsearch动态模板下跨嵌套路径nested查询结果异常咨询
问题原因
该问题由两个核心错误共同导致:
动态模板路径匹配规则错误
Elasticsearch 中path_match的通配符*仅匹配单段路径(不跨.分隔符),仅**可匹配任意多段路径。你当前的动态模板没有针对entities层级的匹配规则,虽然查询返回的mapping看起来和静态配置一致,但实际entities层级是动态映射推断生成的普通object类型,而非你预期的nested类型。
普通object类型的字段不会像nested类型一样做上下文隔离,其内容会被平铺到父文档的查询上下文中。跨上下文的嵌套查询逻辑差异
- 当外层嵌套路径为
sections.foo.sentences.entities时,该层级为正确的nested类型,上下文完全隔离,内层查询sections.bar路径下的字段属于完全独立的另一个nested上下文,无法命中,返回空结果,符合预期。 - 当外层嵌套路径为
sections.bar.sentences.entities时,该层级实际为普通object类型,没有查询上下文隔离,内层查询sections.foo路径下的字段在根文档上下文中存在,exists查询直接命中,因此返回了文档。
修复方案
- 补充
entities层级的匹配规则,调整动态模板顺序,将更具体的匹配规则放在前面:
{ "dynamic_templates": [ { "nested_has_props": { "path_match": "*.has_props.*", "match_mapping_type": "string", "mapping": { "type": "keyword" } } }, { "has_props": { "path_match": "*.has_props", "match_mapping_type": "object", "mapping": { "type": "nested" } } }, { "entities_nested": { "path_match": "*.entities", "match_mapping_type": "object", "mapping": { "type": "nested" } } }, { "sentences": { "path_match": "*.sentences", "match_mapping_type": "object", "mapping": { "type": "nested" } } }, { "section_nested": { "path_match": "sections.*", "match_mapping_type": "object", "mapping": { "type": "nested" } } } ], "properties": { "sections": { "type": "nested" } } }
- 多层嵌套查询时,严格按层级逐层嵌套声明path,不要直接跨多层写嵌套路径,避免上下文逻辑混乱。
内容的提问来源于stack exchange,提问作者t.vu
相关产品推荐
相关产品推荐

