使用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
相關文章
相關標籤/搜索