Django自學筆記之全文檢索

1.依次安裝以下包: 

pip install django-haystack
pip install whoosh
pip install jieba

2.修改settings.py文件: 

  • 添加應用 
INSTALLED_APPS = (
    ...
    '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.在應用目錄下建立search_indexes.py文件:

#!/usr/bin/env python
# coding=utf-8

from haystack import indexes
from .models import HeroInfo

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

    def get_model(self):
        # 哪個表,這裏查找英雄表
        return HeroInfo

    def index_queryset(self, using=None):
        # 基於哪些數據進行檢索
        return self.get_model().objects.all()

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

(此例應用名稱爲:booktest,文本文件爲:heroinfo_text.txt):

這裏列出了要對哪些列的內容進行檢索(注意字段是CharField類型的纔可以)

# 我們在models.py中創建的HeroInfo,hname和hcontent是CharField類型
class HeroInfo(models.Model):
    hname = models.CharField('名字',max_length=20)
    hgender = models.BooleanField(default=True)
    isDelete = models.BooleanField(default=False)
    hcontent = models.CharField('英雄介紹',max_length=1000)
    hbook = models.ForeignKey('BookInfo',verbose_name='所屬圖書',on_delete=models.CASCADE)
# /templates/search/indexes/booktest/heroinfo_text.txt
# heroinfo_text.txt中:
{{object.hname}}
{{object.hcontent}}

5.在目錄“templates/search/”下建立檢索的結果頁面search.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>檢索的結果頁面</title>
</head>
<body>
搜索的關鍵詞:{{query}}
{% if query %}
    <h3>搜索結果如下:</h3>
    {% if not page.object_list|length == 0 %}
    <table border="1">
        <tr>
            <th width="50%">姓名</th>
            <th width="50%">英雄介紹</th>
        </tr>
        {% for result in page.object_list %}
                <tr>
                    <th width="50%"><a href="/search/{{ result.object.id }}/">{{ result.object.hname }}</a></th>
                    <th width="80%"><a href="/search/{{ result.object.id }}/">{{ result.object.hcontent }}</a></th>
                </tr>
        {% endfor %}
        </table>
    {{page}}
    共{{page.object_list|length}}條數據
        {% 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 %}
    {% elif page.object_list|length == 0 %}
        <p>啥也沒找到啊</p>
    {% endif %}
{% else %}
未輸入關鍵詞,請<a href="/search_index/">返回查詢頁</a>
{% endif %}
</body>
</html>

在目錄“templates”下建立搜索輸入內容界面search_index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method='get' action="/search/" target="_blank">
    <input type="text" name="q" placeholder="請輸入至少兩個字">
    <input type="submit" value="查詢">
</form>

</body>
</html>

6.設置視圖views.py文件:

from django.shortcuts import render
from django.http import HttpResponse
from .models import *

# 搜索輸入內容界面視圖
def search_index(request):
    return render(request,'search_index.html')

# 這個是點擊查詢結果後顯示的頁面
def search_result(request,id):
    result = HeroInfo.objects.filter(pk=id)
    li = []
    for i in result:
        li.append('英雄id:'+id)
        li.append('<br>')
        li.append('<br>')
        li.append('英雄姓名:'+i.hname)
        li.append('<br>')
        li.append('<br>')
        li.append('英雄介紹:'+i.hcontent)
        li.append('<br>')
        li.append('<br>')
        li.append('<a href="/search_index/">返回查詢首頁</a>')
        return HttpResponse(li)

7.建立ChineseAnalyzer.py文件:

  • 保存在haystack的安裝文件夾下,路徑大致如“.....Lib/site-packages/haystack/backends”
# encoding: utf-8
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_backend.py文件,改名爲whoosh_cn_backend.py:

先導入:from .ChineseAnalyzer import ChineseAnalyzer
然後查找
analyzer=StemmingAnalyzer()
改爲
analyzer=ChineseAnalyzer()

9.生成索引:

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

 10.啓動服務:

python manage.py runserver

輸入網址查看:http://127.0.0.1:8000/search_index/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章