全文檢索 Django

**

全文檢索

**
全文檢索不同於特定字段的模糊查詢,使用全文檢索的效率更高,並且能夠對於中文進行分詞處理
haystack:django的一個包,可以方便地對model裏面的內容進行索引、搜索,設計爲支持whoosh,solr,Xapian,Elasticsearc四種全文檢索引擎後端,屬於一種全文檢索的框架
whoosh:純Python編寫的全文搜索引擎,雖然性能比不上sphinx、xapian、Elasticsearc等,但是無二進制包,程序不會莫名其妙的崩潰,對於小型的站點,whoosh已經足夠使用
jieba:一款免費的中文分詞包,如果覺得不好用可以使用一些收費產品

1.在虛擬環境中依次安裝包

pip install django-haystack
pip install whoosh
pip install jieba

2.修改settings.py文件
添加應用

INSTALLED_APPS = (
    ...
    'haystack',
)

3.添加搜索引擎

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
        'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
    }
}

4.自動生成索引

HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

5.在項目的urls.py中添加url

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

6.在應用目錄下建立search_indexes.py文件

coding=utf-8

from haystack import indexes
from models import GoodsInfo


class GoodsInfoIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)

    def get_model(self):
        return GoodsInfo

    def index_queryset(self, using=None):
        return self.get_model().objects.all()

7.在目錄“templates/search/indexes/應用名稱/”下創建“模型類名稱_text.txt”文件

goodsinfo_text.txt,這裏列出了要對哪些列的內容進行檢索

{{ object.gName }}
{{ object.gSubName }}
{{ object.gDes }}

8.在目錄“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>

9.建立ChineseAnalyzer.py文件
保存在haystack的安裝文件夾下,路徑如“/home/python/.virtualenvs/django_py2/lib/python2.7/site-packages/haystack/backends”
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()

10.複製whoosh_backend.py文件,改名爲whoosh_cn_backend.py
注意:複製出來的文件名,末尾會有一個空格,記得要刪除這個空格

from .ChineseAnalyzer import ChineseAnalyzer 
查找:
analyzer=StemmingAnalyzer()
改爲:
analyzer=ChineseAnalyzer()

11.生成索引

初始化索引數據
python manage.py rebuild_index

12.在模板中創建搜索欄

<form method='get' action="/search/" target="_blank">
    <input type="text" name="q"> //此處name必須命名爲 q
    <input type="submit" value="查詢">
</form>
發佈了42 篇原創文章 · 獲贊 28 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章