django-haystack插件基本使用操做流程

搜索

  搜索能够使用最原始的模糊匹配的like方式进行搜索。固然这种搜索方式对于一些小量的数据是很是合适的。可是随着数据量愈来愈大。这时候咱们就须要使用搜索引擎了。搜索引擎会将全部须要搜索的数据使用算法作一个索引,之后搜索的时候就只须要根据这个索引便可找到相应的数据。搜索引擎作索引的过程会比较慢,甚至占用空间,可是一旦索引创建完成,那么之后再搜索的时候就会很快了。html

django-haystack插件概述

  这个插件是专门给Django提供搜索功能的。django-haystack提供了一个搜索的接口,底层能够根据本身的需求更换搜索引擎。他其实有点相似于Django中的ORM插件,提供了一个操做数据库的接口,可是底层具体使用哪一个数据库是能够本身设置的。python

  django-haystack支持的搜索引擎有Solr、Elasticsearch、Whoosh、Xapian等。Whoosh是基于纯Python的搜索引擎,检索速度快,集成方便。正则表达式

安装

1 pip3 install django-haystack 2 pip3 install whoosh

集成步骤

 1.在项目中安装django-haystack,在settings.py算法

 1 INSTALLED_APPS = [  2     'django.contrib.admin',  3     'django.contrib.auth',  4     'django.contrib.contenttypes',  5     'django.contrib.sessions',  6     'django.contrib.sites',  7 
 8     # 添加
 9     'haystack', 10 ]

 2.设置搜索引擎,在settings中数据库

1 HAYSTACK_CONNECTIONS = { 2     'default': { 3         # 设置haystack的搜索引擎
4         'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 5         # 设置索引文件的位置
6         'PATH': os.path.join(BASE_DIR, 'whoosh_index'), 7  } 8

3.建立索引类 django

   在模型所属的app下建立一个search_indexes.py文件,而后建立索引类。假如要给News app建立索引,代码以下:api

1 class NewsIndex(indexes.SearchIndex,indexes.Indexable): 2     text = indexes.CharField(document=True,use_template=True) 3 
4     def get_model(self): 5         return News 6 
7     def index_queryset(self, using=None): 8         return self.get_model().objects.all() 

4.添加url映射 session

1 urlpatterns = [ 2     path('',views.index,name='index'), 3     # 添加search的url映射
4     path('search/',include('haystack.urls')), 5     path('news/', include("apps.news.urls")), 6

 5.添加模板app

   在templates文件夹下建立如下结构的目录:ui

1 templates 2  search 3  indexes 4  news(app的名字) 5                 news(模型的名字)_text.txt 

   而后在news_text.txt中添加须要被索引的字段

1 # 根据标题和内容文本
2 {{ object.title }} 3 {{ object.content }}

  紧接着templates文件下建立search.html模板文件,haystack会自动在templates文件下寻找这个模板文件渲染,而且会给这个模板传入page/paginator/query等参数,django内置的分页与查询的关键字。咱们能够经过page.object_list获取到查询出来的数据。

<ul class="recommend-list">
    {% for result in page.object_list %}
        {% with result.object as news %}
            <li>
                <div class="thumbnail-group">
                    <a href="#">
                        <img src="{{ news.thumbnail }}" alt="">
                    </a>
                </div>
                <div class="news-group">
                    <p class="title">
                        <a href="#">{{ news.title }}</a>
                    </p>
                    <p class="desc">
                        {{ news.desc }}
                    </p>
                    <p class="more">
                       <span class="category">{{ news.caetgory.name }}</span>
                        <span class="pub-time">{{ news.pub_time }}</span>
                        <span class="author">{{ news.author.username }}</span>
                    </p>
                </div>
            </li>
        {% endwith %}
    {% endfor %}
</ul>

6.创建索引  

1 python manage.py rebuild_index 

若是不想每次数据操做后都要手动的建立索引,能够在settings中配置: 

1 # 增删改查后自动建立索引
2 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

 7.使用jieba分词替换Whoosh默认的分词

  Whoosh默认是采用正则表达式进行分词的,这对于英文词汇适用,可是中文支持的很差,这里替换为jieba分词,jieba分词库对中文却支持的好。

  安装

1 pip3 install jieba

  

  安装完成后,拷贝D:\python\Lib\site-packages\haystack\backends\whoosh_backend.py其中的代码,将他放在项目的其余包中,而后建立一个名叫whoosh_cn_backend.py文件,把刚刚复制的代码粘贴进去,而后再添加如下代码: 

 1 import jieba  2 from whoosh.analysis import Tokenizer, Token  3 
 4 class ChineseTokenizer(Tokenizer):  5     def __call__(self, value, positions=False, chars=False,  6                  keeporiginal=False, removestops=True,  7                  start_pos=0, start_char=0, mode='', **kwargs):  8         t = Token(positions, chars, removestops=removestops, mode=mode,  9                   **kwargs) 10         seglist = jieba.cut(value, cut_all=True) 11         for w in seglist: 12             t.original = t.text = w 13             t.boost = 1.0
14             if positions: 15                 t.pos = start_pos + value.find(w) 16             if chars: 17                 t.startchar = start_char + value.find(w) 18                 t.endchar = start_char + value.find(w) + len(w) 19             yield t 20 
21 def ChineseAnalyzer(): 22     return ChineseTokenizer()

  而后再将以前的代码中的分析器analyzer=StemmingAnalyzer()替换为analyzer=ChineseAnalyzer()就好了。

了解更多:http://django-haystack.readthedocs.io/en/master/tutorial.html

相关文章
相关标签/搜索