如何阻止Elasticsearch对查询分词?Elasticsearch 8.4过滤问题
解决Elasticsearch 8.4中match查询分词导致的过滤问题
方案一:用match_phrase查询替代match
match查询会自动拆分查询文本分词,而match_phrase会将整个查询字符串作为完整短语匹配,不会拆分词项,只会过滤掉包含"peanut butter"完整短语的文档,避免单独含"butter"的文档被误过滤:
must_not: [ match_phrase: { ingredients: { query : 'peanut butter' } } ]
方案二:使用term查询(依赖字段类型)
如果ingredients字段本身是keyword类型,或者包含keyword子字段(比如默认生成的ingredients.keyword),可以用term做精确匹配,直接匹配原始字符串:
must_not: [ term: { "ingredients.keyword": 'peanut butter' } ]
注意:若字段是text类型且无keyword子字段,直接用term查询text字段无效,因为text字段存储的是分词后的词项而非原始字符串。
方案三:给match查询设置operator为"and"(补充方案)
该方案仍会分词,但要求分词后的所有词项必须同时出现在文档中(顺序不固定),不过这和精确短语匹配有差异,比如会过滤掉含"butter peanut"的文档:
must_not: [ match: { ingredients: { query : 'peanut butter', operator: 'and' } } ]
内容的提问来源于stack exchange,提问作者Jonathan
相关产品推荐
相关产品推荐

