Elasticsearch布尔查询filter失效、部分搜索无结果如何解决?
过滤条件异常的解决方案
Elasticsearch 的 bool 查询存在默认规则:当查询结构中同时存在 filter/must 子句和 should 子句时,should 子句默认不是必选条件,仅用作结果评分,只有结构中没有 filter/must 子句时,才要求 should 至少匹配一条规则。这就是添加过滤条件后返回所有匹配过滤规则文档的原因。
解决方法是在 bool 结构中添加 minimum_should_match: 1 参数,强制要求至少匹配一条 should 子句的规则。如果 library 字段是默认的 text+keyword 复合类型,过滤时请使用 library.keyword 做精确匹配,避免 text 类型分词导致的匹配异常。
部分搜索功能的实现方案
默认的 match 查询匹配的是分词后的完整词项,你存入的 Second insight 分词后得到的词项是 second、insight,不存在 ins 这个词项,所以直接用 match 查询 ins 会返回空结果。有两种常用实现方案:
- 临时适配方案:使用
match_phrase_prefix查询,匹配以指定前缀开头的词项,适合短前缀的搜索场景,不需要修改索引映射配置。 - 生产级高性能方案:提前为需要搜索的文本字段配置
ngram分词器,索引写入时就会把词拆成指定长度的前后缀片段,搜索时直接匹配,查询速度远高于前缀查询,需要修改索引的 mapping 配置后重建索引。
组合功能的完整查询示例(临时适配方案)
{ "query": { "bool": { "should": [ { "match_phrase_prefix": { "title": "ins" }}, { "match_phrase_prefix": { "content": "ins" }} ], "filter": [ { "term": { "library.keyword": "workspace" } } ], "minimum_should_match": 1 } } }
Ngram 分词器配置参考(生产方案)
{ "settings": { "analysis": { "analyzer": { "partial_search_analyzer": { "tokenizer": "standard", "filter": ["lowercase", "ngram_filter"] } }, "filter": { "ngram_filter": { "type": "ngram", "min_gram": 2, "max_gram": 10 } } } }, "mappings": { "properties": { "title": { "type": "text", "analyzer": "partial_search_analyzer" }, "content": { "type": "text", "analyzer": "partial_search_analyzer" }, "library": { "type": "keyword" } } } }
配置完成重建索引后,直接使用普通 match 查询即可实现任意长度的片段搜索,无需使用前缀查询。
内容的提问来源于stack exchange,提问作者lutaev
相关产品推荐
相关产品推荐

