本文共 3119 字,大约阅读时间需要 10 分钟。
在已建立的 articles 索引库中,Elasticsearch 提供了一种强大的查询功能——suggest(建议查询模式),其中最常用的是 word-phrase 模式。通过这种方式,可以实现关键词的拼写纠正功能。
127.0.0.1:9200)。curl 127.0.0.1:9200/articles/article/_search?pretty -d '{ "_source": false, "suggest": { "text": "phtyon web", # 输入的内容 "word-phrase": { # 自定义字段名, 推荐结果会包含在该字段中 "phrase": { # 返回短语形式, 还可以使用term "field": "_all", # 指定在哪些字段中获取推荐词 "size": 1 # 返回的推荐词数量 } } }}' phtyon web),Elasticsearch 将根据索引库数据返回正确的拼写建议 python web。自动补全功能可以通过创建专门的索引库来实现。以下是创建自动补全索引库的步骤:
curl -X PUT 127.0.0.1:9200/completions/_mapping/words -H 'Content-Type: application/json' -d'{ "words": { "properties": { "suggest": { # 自定义的字段名 存储文章的标题 "type": "completion", # 自动补全的类型必须completion "analyzer": "ik_max_word" } } }}' curl 127.0.0.1:9200/completions/words/_search?pretty -d '{ "suggest": { "title-suggest" : { # 自定义字段名, 推荐结果会包含在该字段中 "prefix" : "pyth", # 输入的内容 补全结果python "completion" : { "field" : "suggest" # 指定在哪些字段中获取推荐词 } } }}' pyth),系统将返回完整的补全词 python。在实际应用中,搜索建议接口的实现可以通过以下步骤完成:
class SuggestionResource(Resource): """联想建议""" def get(self): """获取联想建议""" # 解析参数 qs_parser = RequestParser() qs_parser.add_argument('q', type=inputs.regex(r'^.{1,50}$'), required=True, location='args') args = qs_parser.parse_args() q = args.q # 首先尝试自动补全建议查询 query = { 'from': 0, 'size': 10, '_source': False, 'suggest': { 'word-completion': { 'prefix': q, 'completion': { 'field': 'suggest' } } } } ret = current_app.es.search(index='completions', body=query) options = ret['suggest']['word-completion'][0]['options'] # 如果没有结果,进行纠错建议查询 if not options: query = { 'from': 0, 'size': 10, '_source': False, 'suggest': { 'text': q, 'word-phrase': { 'phrase': { 'field': '_all', 'size': 1 } } } } ret = current_app.es.search(index='articles', doc_type='article', body=query) options = ret['suggest']['word-phrase'][0]['options'] results = [] for option in options: if option['text'] not in results: results.append(option['text']) return {'options': results} completion。转载地址:http://pmefk.baihongyu.com/