Elasticsearch拼写错误查询处理:无需模糊匹配实现正确搜索
解决Elasticsearch拼写错误查询的方案(禁用模糊匹配)
给你几个不用模糊匹配(fuzziness)就能实现搜索正确内容的办法:
1. 提前配置同义词过滤器
在索引的分析器里添加同义词规则,把错误拼写映射到正确词汇,查询时错误输入会被自动转换成正确词来匹配。
首先创建带同义词过滤器的索引(若未创建):
PUT /products { "settings": { "analysis": { "filter": { "spelling_synonyms": { "type": "synonym", "synonyms": [ "kitchne => kitchen", "applinces => appliances" ] } }, "analyzer": { "synonym_analyzer": { "tokenizer": "standard", "filter": [ "lowercase", "spelling_synonyms" ] } } } }, "mappings": { "properties": { "title": { "type": "text", "analyzer": "synonym_analyzer" }, "keywords": { "type": "text", "analyzer": "synonym_analyzer" }, "description": { "type": "text", "analyzer": "synonym_analyzer" } } } }
之后用你原来的查询语句就能搜到正确内容,分析器会自动处理拼写错误:
{ "query": { "bool": { "must": [ { "multi_match": { "query": "Kitchne applinces", "fields": [ "title^3", "keywords^2", "description^1" ], "type": "phrase" } } ] } } }
2. 直接在查询里添加正确短语的匹配
如果不想修改索引设置,就在bool查询里用should子句同时包含错误和正确短语,只要匹配其中一个就返回结果,正确拼写的内容会获得更高评分。
修改后的查询语句:
{ "query": { "bool": { "should": [ { "multi_match": { "query": "Kitchne applinces", "fields": [ "title^3", "keywords^2", "description^1" ], "type": "phrase" } }, { "multi_match": { "query": "Kitchen appliances", "fields": [ "title^3", "keywords^2", "description^1" ], "type": "phrase" } } ], "minimum_should_match": 1 } } }
3. 用拼写建议器先获取正确词汇再搜索
分两步操作:先调用Suggest API获取正确拼写建议,再用建议后的词汇执行搜索。
第一步请求拼写建议:
{ "suggest": { "spelling_suggestion": { "text": "Kitchne applinces", "phrase": { "field": "title", "size": 1, "direct_generator": [ { "field": "title", "suggest_mode": "always" } ] } } } }
拿到返回的正确建议(比如Kitchen appliances)后,把原查询里的query值替换成这个正确词汇,再执行搜索即可。
内容的提问来源于stack exchange,提问作者Mohan T
相关产品推荐
相关产品推荐

