ElasticSearch 1.7.5:缺失字段与Term查询无结果问题求助
Elasticsearch 1.7.5: Query for documents missing nested field and matching term returns no results
我来帮你排查这个问题,你的查询没返回结果大概率是两个核心原因导致的,结合你的映射配置和ES版本,我们一步步解决:
问题1:嵌套字段的missing查询逻辑不符合预期
你的topics是nested类型,虽然设置了include_in_parent: true,但直接用missing: {field: "topics.description"}时,它的逻辑是检查父文档中是否存在扁平化后的该字段——只要有一个topics子文档包含description,父文档就会保留这个字段,所以原查询只会匹配完全没有topics数组或者**所有topics子文档都缺失description**的文档,无法覆盖你实际需要的场景。
问题2:fundedUnder.programme的分词不匹配
你的映射里fundedUnder.programme是string类型,但没有指定analyzer: "analyzer_keyword"(不像topics下的字段),所以它会使用默认的standard分词器,这个分词器会自动把大写字母转为小写。也就是说,你索引中的"ABC"会被存成"abc",而你的term查询用的是精确匹配的"ABC",自然匹配不到任何结果。
修正后的查询
结合这两个问题,我们调整查询语句,分两种常见场景:
场景1:匹配所有fundedUnder.programme为"ABC",且所有topics子文档都缺失description(或无topics数组)的文档
{ "query": { "filtered": { "filter": { "bool": { "must": [ // 先使用小写匹配,后续优化映射后可改用原词 { "term": { "fundedUnder.programme": "abc" } }, { "bool": { "should": [ // 匹配完全没有topics数组的文档 { "missing": { "field": "topics" } }, // 匹配所有topics子文档都没有description的情况 { "nested": { "path": "topics", "filter": { "bool": { "must_not": [ { "exists": { "field": "topics.description" } } ] } }, "score_mode": "none" } } ], "minimum_should_match": 1 } } ] } } } } }
场景2:匹配fundedUnder.programme为"ABC",且**至少有一个topics子文档缺失description**的文档
如果你的需求是只要存在一个topics子文档没有description就匹配,那么可以简化为:
{ "query": { "filtered": { "filter": { "bool": { "must": [ { "term": { "fundedUnder.programme": "abc" } }, { "nested": { "path": "topics", "filter": { "missing": { "field": "topics.description" } }, "score_mode": "none" } } ] } } } } }
额外优化建议:调整映射避免分词问题
为了彻底解决programme字段的匹配问题,建议把它也设置为关键词分词,这样就能直接用原词精确匹配:
"fundedUnder": { "properties": { "programme": { "type": "string", "analyzer": "analyzer_keyword" }, "subprogramme": { "type": "string" } } }
注意修改映射后需要重新索引数据才能生效。
内容的提问来源于stack exchange,提问作者kolurbo
相关产品推荐
相关产品推荐

