Elasticsearch--联想提示

拼写纠错

对于已经建立的articles索引库,elasticsearch还提供了一种查询模式,suggest建议查询模式

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时,es可以提供根据索引库数据得出的正确拼写python web

自动补全

  • 自动补全对类型映射有特殊要求, 不能使用原索引库, 需要创建单独的自动补全索引库
  • 注意 推荐词的类型必须是completion
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" # 指定在哪些字段中获取推荐词
            }
        }
    }
}
'

搜索建议接口

  • 先进行自动补全的查询, 如果没有结果, 再进行拼写纠错的查询
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}

原文地址:https://www.cnblogs.com/oklizz/p/11448986.html