使用haystack实现django全文检索搜索引擎功能

前言

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

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

中文搜索须要进行中文分词,使用jiebapython

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

haystack支持多种搜索引擎,不单单是whoosh,使用solr、elastic search等搜索,也可经过haystack,并且直接切换引擎便可,甚至无需修改搜索代码。数据库

配置搜索

1.安装相关包

pip install django-haystack
pip install whoosh
pip install jieba

2.配置django的settings

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

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 的文件。python2.7

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