如何让Elasticsearch忽略查询字符串中的连词(and、of、or等)?
如何让Elasticsearch忽略英文连词(and/of/or等)进行搜索
要解决查询中包含and、of、or这类无意义连词时的误匹配问题,核心思路是利用Elasticsearch的停用词(stopwords)机制,在索引和搜索阶段自动过滤掉这类词汇。以下是具体实现步骤:
1. 创建含停用词过滤器的自定义分析器
Elasticsearch内置了英文停用词列表,我们可以基于它创建一个自定义分析器,让字段在索引和搜索时自动过滤停用词。
创建索引配置示例
PUT /your_index { "settings": { "analysis": { "filter": { "english_stop_filter": { "type": "stop", "stopwords": "_english_" // 使用ES内置英文停用词,包含and、of、or等 } }, "analyzer": { "english_stop_analyzer": { "tokenizer": "standard", "filter": [ "lowercase", // 统一转小写 "english_stop_filter" // 过滤停用词 ] } } } }, "mappings": { "properties": { "fieldOne": { "type": "text", "analyzer": "english_stop_analyzer", "search_analyzer": "english_stop_analyzer" }, "fieldTwo": { "type": "text", "analyzer": "english_stop_analyzer", "search_analyzer": "english_stop_analyzer" }, "fieldThree": { "type": "text", "analyzer": "english_stop_analyzer", "search_analyzer": "english_stop_analyzer" } } } }
如果需要自定义停用词列表,只需将"stopwords": "_english_"替换为自定义数组,比如:
"stopwords": ["and", "of", "or", "the", "a"]
2. 调整查询配置
确保查询时也应用相同的停用词分析器,避免查询字符串中的连词被当作有效关键词。你的query_string查询可以调整为:
query_string: { query: `${sanitizedQueryString}~`, fields: ['fieldOne^5', 'fieldTwo^5', 'fieldThree'], analyzer: 'english_stop_analyzer' // 显式指定分析器,确保一致性 },
效果说明
- 索引阶段:数据中的"And"会被停用词过滤器过滤,
Farmers And Workers最终被索引为["farmers", "workers"]。 - 搜索阶段:查询字符串
harris and smith会被分析为["harris", "smith"],只会匹配前两条记录,不会命中第四条含"And"的记录。
注意事项
如果你的索引已经创建且无法重新创建,需要通过重新索引的方式更新字段分析器:先创建新的带停用词分析器的索引,再将旧索引的数据同步到新索引中。
内容的提问来源于stack exchange,提问作者Lloyd Banks
相关产品推荐
相关产品推荐

