elasticsearch搜索提示

elasticsearch搜索提示(补全)接口需要新增suggest字段并设type为:completion,结合到scrapy,修改es_types.py文件:

from datetime import datetime
from elasticsearch_dsl import DocType, Date, Nested, Boolean, analyzer, InnerObjectWrapper, Completion, Keyword, Text, Integer
from elasticsearch_dsl.connections import connections
connections.create_connection(hosts=[‘localhost‘])
class ArticleType(DocType):
    #文章类型
    suggest = Completion(analyzer="ik_max_word") #这样做由于原码问题这里会报错
    title = Text(analyzer="ik_max_word")
    create_date = Date()
    praise_nums = Integer()
    fav_nums = Integer()
    comment_nums = Integer()
    tags = Text(analyzer="ik_max_word")
    front_image_url = Keyword()
    url_object_id = Keyword()
    front_image_path = Keyword()
    url = Keyword()
    content = Text(analyzer="ik_max_word")

    class Meta:
        index = ‘jobbole‘
        doc_type = ‘article‘
if __name__ == ‘__main__‘:
    ArticleType.init()

解决办法:自定义CustomAnalysis类,继承自elasticsearch_dsl.analysis下的CustomAnalysis类:

from datetime import datetime
from elasticsearch_dsl import DocType, Date, Nested, Boolean,     analyzer, InnerObjectWrapper, Completion, Keyword, Text, Integer

from elasticsearch_dsl.analysis import CustomAnalyzer as _CustomAnalyzer

from elasticsearch_dsl.connections import connections
connections.create_connection(hosts=["localhost"])

class CustomAnalyzer(_CustomAnalyzer):
    def get_analysis_definition(self):
        return {}

ik_analyzer = CustomAnalyzer("ik_max_word", filter=["lowercase"])#大小写转换(搜索时忽略大小写影响)
class ArticleType(DocType):
    #伯乐在线文章类型
    suggest = Completion(analyzer=ik_analyzer)
    title = Text(analyzer="ik_max_word")
    create_date = Date()
    url = Keyword()
    url_object_id = Keyword()
    front_image_url = Keyword()
    front_image_path = Keyword()
    praise_nums = Integer()
    comment_nums = Integer()
    fav_nums = Integer()
    tags = Text(analyzer="ik_max_word")
    content = Text(analyzer="ik_max_word")

    class Meta:
        index = "jobbole"
        doc_type = "article"

if __name__ == "__main__":
    ArticleType.init()

在item中生成搜索建议词:

from spider.models.es_types import ArticleType
from elasticsearch_dsl.connections import connections
es = connections.create_connection(ArticleType._doc_type.using)
def gen_suggests(index, info_tuple):
    #根据字符串生成搜索建议数组
    used_words = set() #set为去重功能
    suggests = []
    for text, weight in info_tuple:
        if text:
            #字符串不为空时,调用elasticsearch的analyze接口分析字符串(分词、大小写转换)
            words = es.indices.analyze(index=index, analyzer="ik_max_word", params={‘filter‘:["lowercase"]}, body=text)
            anylyzed_words = set([r["token"] for r in words["tokens"] if len(r["token"])>1])
            new_words = anylyzed_words - used_words
        else:
            new_words = set()

        if new_words:
            suggests.append({‘input‘: list(new_words), ‘weight‘: weight})
    return suggests

class JobboleArticleItem(scrapy.Item):
    title = scrapy.Field()
    create_date = scrapy.Field(input_processor=MapCompose(date_convert))
    praise_nums = scrapy.Field(input_processor=MapCompose(number_convert))
    fav_nums = scrapy.Field(input_processor=MapCompose(number_convert))
    comment_nums = scrapy.Field(input_processor=MapCompose(number_convert))
    tags = scrapy.Field(input_processor=MapCompose(remove_comment_tags), output_processor=Join(‘,‘))
    front_image_url = scrapy.Field(output_processor=MapCompose(returnValue))
    url_object_id = scrapy.Field(input_processor=MapCompose(get_md5))
    front_image_path = scrapy.Field()
    url = scrapy.Field()
    content = scrapy.Field()

def save_to_elasticsearch(self):
        article = ArticleType()
        article.title = self[‘title‘]
        article.create_date = self[‘create_date‘]
        article.content = remove_tags(self[‘content‘])  # remove_tags()去除html标签
        article.front_image_url = self[‘front_image_url‘]
        if ‘front_image_path‘ in self:
            article.front_image_path = self[‘front_image_path‘]
        article.praise_nums = self[‘praise_nums‘]
        article.fav_nums = self[‘fav_nums‘]
        article.comment_nums = self[‘comment_nums‘]
        article.url = self[‘url‘]
        article.tags = self[‘tags‘]
        article.meta.id = self[‘url_object_id‘]

        #生成搜索建议词
        article.suggest = gen_suggests(ArticleType._doc_type.index, ((article.title, 10), (article.tags, 7)))
        article.save()  # 保存
        return
时间: 2024-10-10 18:17:09

elasticsearch搜索提示的相关文章

Android--多选自动搜索提示

一. 效果图 常见效果,在搜素提示选中之后可以继续搜索添加,选中的词条用特殊字符分开 二. 布局代码 <MultiAutoCompleteTextView android:id="@+id/autoMulti" android:layout_width="match_parent" android:layout_height="60dp" android:layout_marginTop="50dp" /> 三.

浅谈asp.net通过本机cookie仿百度(google)实现搜索input框自动弹出搜索提示

对于通过用户输入关键词实现自动弹出相关搜索结果,这里本人给两种解决方案,用于两种不同的情形. 常见方法是在数据库里建一个用户搜索关系表,然后通过用户搜索框输入的关键字异步调用数据表中的相关数据,显示在一个隐藏div中. 第二种方式也就是我现在着重讨论的方式,适用于单个用户,基于此用户以往的搜索数据来实现搜索提示功能.技术关键是记录下用户的以往搜索数据,写入cookie,然后页面从用户本机cookie调用数据. ok,下面进入正题.本文主要讲实现步骤,代码可根据自己实际需要更改. 一,如何写入co

仿百度搜索提示框效果

<!doctype html><html><head> <meta charset="UTF-8"> <title>百度搜索提示框</title> <style> * { margin: 0;padding: 0; outline: none;} .search101 { width: 650px; margin: 300px auto; font-size: 0; } .sou1 { width: 5

高德地图搜索提示获取信息回传activity刷新ui(二)

应用场景: 在主activity中点击进入到另一个activity搜索提示,获取经纬度,点确定返回到主activity,虽然说需求很奇葩,但是遇到了没办法.. 主要包含两部分,搜索提示+activity回退携带信息刷新主acitivity. 1>搜索提示 代码中贴到 2>activity进入到另一个activity,在另一个activity进行操作获取数据之后,回到到activity刷新页面: 主activity里面点击: Intent intent = new Intent(MainActi

通过HTTP RESTful API 操作elasticsearch搜索数据

通过HTTP RESTful API 操作elasticsearch搜索数据

C# WinForm 技巧:COMBOBOX搜索提示

comboBox和textBox支持内置的搜索提示功能, 在form的InitializeComponent()中添加如下语句:   this.comboBox1.AutoCompleteCustomSource.AddRange(new string[] { "10.152.154.89", "10.152.154.90", "10.152.252.10", "10.152.252.11" });//是将数据添加到搜索范围

Android AutoCompleteTextView控件实现类似百度搜索提示,限制输入数字长度

Android AutoCompleteTextView 控件实现类似被搜索提示,效果如下 1.首先贴出布局代码 activity_main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="f

讨论asp.net通过机器cookie仿百度(google)实现搜索input搜索提示弹出框自己主动

为实现自己主动弹出通过用户输入关键词相关的搜索结果,在这里,我举两个解决方案,对于两个不同的方案. 常用的方法是建立一个用户数据库中查找关系表.然后输入用户搜索框keyword异步调用数据表中的相关数据.显示在一个隐藏div中. 另外一种方式也就是我如今着重讨论的方式.适用于单个用户,基于此用户以往的搜索数据来实现搜索提示功能.技术关键是记录下用户的以往搜索数据,写入cookie,然后页面从用户本机cookie调用数据. ok,以下进入正题.本文主要讲实现步骤,代码可依据自己实际须要更改. 一,

搜索框带有搜索提示点击消失代码实例

搜索框带有搜索提示点击消失代码实例: 搜索框大家一定都不陌生,因为随时都可以用到,比较人性化的搜索框都有这样的效果,默认情况有搜索提示,点击搜索框,提示内容消失,下面就通过代码实例介绍一下如何实现此功能. 代码如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.5