zoukankan      html  css  js  c++  java
  • 使用haystack实现django全文检索搜索引擎功能

    前言

    django是python语言的一个web框架,功能强大。配合一些插件可为web网站很方便地添加搜索功能。

    搜索引擎使用whoosh,是一个纯python实现的全文搜索引擎,小巧简单。

    中文搜索需要进行中文分词,使用jieba

    直接在django项目中使用whoosh需要关注一些基础细节问题,而通过haystack这一搜索框架,可以方便地在django中直接添加搜索功能,无需关注索引建立、搜索解析等细节问题。

    haystack支持多种搜索引擎,不仅仅是whoosh,使用solr、elastic search等搜索,也可通过haystack,而且直接切换引擎即可,甚至无需修改搜索代码。

    配置搜索

    1.安装相关包

    pip install django-haystack
    pip install whoosh
    pip install jieba
    

    2.配置django的settings

    修改settings.py文件,添加haystack应用:

    INSTALLED_APPS = (
        ...
        'haystack', #将haystack放在最后
    )
    

    在settings中追加haystack的相关配置:

    HAYSTACK_CONNECTIONS = {
        'default': {
            'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
            'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
        }
    }
    
    # 添加此项,当数据库改变时,会自动更新索引,非常方便
    HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
    

    3.添加url

    在整个项目的urls.py中,配置搜索功能的url路径:

    urlpatterns = [
        ...
        url(r'^search/', include('haystack.urls')),
    ]
    

    4.在应用目录下,添加一个索引

    在子应用的目录下,创建一个名为 search_indexes.py 的文件。

    from haystack import indexes
    # 修改此处,为你自己的model
    from models import GoodsInfo
    
    # 修改此处,类名为模型类的名称+Index,比如模型类为GoodsInfo,则这里类名为GoodsInfoIndex
    class GoodsInfoIndex(indexes.SearchIndex, indexes.Indexable):
        text = indexes.CharField(document=True, use_template=True)
    
        def get_model(self):
    	    # 修改此处,为你自己的model
            return GoodsInfo
    
        def index_queryset(self, using=None):
            return self.get_model().objects.all()
    

    说明:
    1)修改上文中三处注释即可
    2)此文件指定如何通过已有数据来建立索引。get_model处,直接将django中的model放过来,便可以直接完成索引啦,无需关注数据库读取、索引建立等细节。
    3)text=indexes.CharField一句,指定了将模型类中的哪些字段建立索引,而use_template=True说明后续我们还要指定一个模板文件,告知具体是哪些字段

    5.指定索引模板文件

    在项目的“templates/search/indexes/应用名称/”下创建“模型类名称_text.txt”文件。

    例如,上面的模型类名称为GoodsInfo,则创建goodsinfo_text.txt(全小写即可),此文件指定将模型中的哪些字段建立索引,写入如下内容:(只修改中文,不要改掉object)

    {{ object.字段1 }}
    {{ object.字段2 }}
    {{ object.字段3 }}
    

    6.指定搜索结果页面

    在templates/search/下面,建立一个search.html页面。

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
    {% if query %}
        <h3>搜索结果如下:</h3>
        {% for result in page.object_list %}
            <a href="/{{ result.object.id }}/">{{ result.object.gName }}</a><br/>
        {% empty %}
            <p>啥也没找到</p>
        {% endfor %}
    
        {% if page.has_previous or page.has_next %}
            <div>
                {% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; 上一页{% if page.has_previous %}</a>{% endif %}
            |
                {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}下一页 &raquo;{% if page.has_next %}</a>{% endif %}
            </div>
        {% endif %}
    {% endif %}
    </body>
    </html>
    

    7.使用jieba中文分词器

    在haystack的安装文件夹下,路径如“/home/python/.virtualenvs/django_py2/lib/python2.7/site-packages/haystack/backends”,建立一个名为ChineseAnalyzer.py的文件,写入如下内容:

    import jieba
    from whoosh.analysis import Tokenizer, Token
    
    
    class ChineseTokenizer(Tokenizer):
        def __call__(self, value, positions=False, chars=False,
                     keeporiginal=False, removestops=True,
                     start_pos=0, start_char=0, mode='', **kwargs):
            t = Token(positions, chars, removestops=removestops, mode=mode,
                      **kwargs)
            seglist = jieba.cut(value, cut_all=True)
            for w in seglist:
                t.original = t.text = w
                t.boost = 1.0
                if positions:
                    t.pos = start_pos + value.find(w)
                if chars:
                    t.startchar = start_char + value.find(w)
                    t.endchar = start_char + value.find(w) + len(w)
                yield t
    
    
    def ChineseAnalyzer():
        return ChineseTokenizer()
    

    8.切换whoosh后端为中文分词

    将上面backends目录中的whoosh_backend.py文件,复制一份,名为whoosh_cn_backend.py,然后打开此文件,进行替换:

    # 顶部引入刚才添加的中文分词
    from .ChineseAnalyzer import ChineseAnalyzer 
    
    # 在整个py文件中,查找
    analyzer=StemmingAnalyzer()
    全部改为改为
    analyzer=ChineseAnalyzer()
    总共大概有两三处吧
    

    9.生成索引

    手动生成一次索引:

    python manage.py rebuild_index
    

    10.实现搜索入口

    在网页中加入搜索框:

    <form method='get' action="/search/" target="_blank">
        <input type="text" name="q">
        <input type="submit" value="查询">
    </form>
    

    丰富的自定义

    上面只是快速完成一个基本的搜索引擎,haystack还有更多可自定义,来实现个性化的需求。

    参考官方文档:http://django-haystack.readthedocs.io/en/master/

    自定义搜索view

    上面的配置中,搜索相关的请求被导入到haystack.urls中,如果想自定义搜索的view,实现更多功能,可以修改。

    haystack.urls中内容其实很简单,

    from django.conf.urls import url  
    from haystack.views import SearchView  
      
    urlpatterns = [  
        url(r'^$', SearchView(), name='haystack_search'),  
    ]  
    

    那么,我们写一个view,继承自SearchView,即可将搜索的url导入到自定义view中处理啦。

    class MySearchView(SearchView):
    # 重写相关的变量或方法
    template = 'search_result.html'
    

    查看SearchView的源码或文档,了解每个方法是做什么的,便可有针对性地进行修改。
    比如,上面重写了template变量,修改了搜索结果页面模板的位置。

    高亮

    在搜索结果页的模板中,可以使用highlight标签(需要先load一下)

    {% highlight <text_block> with <query> [css_class "class_name"] [html_tag "span"] [max_length 200] %}
    

    text_block即为全部文字,query为高亮关键字,后面可选参数,可以定义高亮关键字的html标签、css类名,以及整个高亮部分的最长长度。

    高亮部分的源码位于 haystack/templatetags/lighlight.py 和 haystack/utils/lighlighting.py文件中,可复制进行修改,实现自定义高亮功能。

    ref.

    1. http://django-haystack.readthedocs.io/en/master/
    2. http://blog.csdn.net/ac_hell/article/details/52875927
  • 相关阅读:
    【转】CDH rpm+http方式离线部署
    处理CDH环境Hadoop:NameNode is not formatted
    使用 prometheus-operator 监控 Kubernetes 集群【转】
    Prometheus监控k8s(10)-PrometheusOperator-更优雅的Prometheus部署【转】
    kali 网络配置作死踩坑
    01 校招信息收集渠道
    Pypora打开markdown(md)文件保存为PDF文件
    Github上的md文件查看后下载PDF文档方法(将HTML文件保存为PDF格式)
    利用后裔采集器快速采集文本数据(以京东为例)
    office安装公式编辑器mathtype6.9及mathtype过期解决方案
  • 原文地址:https://www.cnblogs.com/aaanthony/p/7435244.html
Copyright © 2011-2022 走看看