1. 程式人生 > 實用技巧 >django-haystack+jieba+whoosh實現全文檢索

django-haystack+jieba+whoosh實現全文檢索

1haystack簡介

  1.1、什麼是haystack?

      1.haystack是django的開源搜尋框架,該框架支援Solr,Elasticsearch,Whoosh, *Xapian*搜尋引擎,不用更改程式碼,直接切換引擎,減少程式碼量。

      2.搜尋引擎使用Whoosh,這是一個由純Python實現的全文搜尋引擎,沒有二進位制檔案等,比較小巧,配置比較簡單,當然效能自然略低。

      3.中文分詞Jieba,由於Whoosh自帶的是英文分詞,對中文的分詞支援不是太好,故用jieba替換whoosh的分片語件。

2 haystack配置使用(前後端不分離)

  參考部落格:

https://www.cnblogs.com/gcgc/p/10762416.html

2.1、安裝

pip install django-haystack
pip install whoosh
pip install jieba

2.2、在setting.py中配置

'''註冊app '''
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages
', 'django.contrib.staticfiles', # haystack要放在應用的上面 'haystack', 'app01', # 這個app01是自己建立的app ] ''' 模板路徑 ''' TEMPLATES = [ { 'DIRS': [os.path.join(BASE_DIR,'templates')], }, ] '''配置haystack ''' # 全文檢索框架配置 HAYSTACK_CONNECTIONS = { 'default': { # 指定whoosh引擎
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', # 'ENGINE': 'app01.whoosh_cn_backend.WhooshEngine', # whoosh_cn_backend是haystack的whoosh_backend.py改名的檔案為了使用jieba分詞 # 索引檔案路徑 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), } } # 新增此項,當資料庫改變時,會自動更新索引,非常方便 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
setting.py

2.3、app01/models.py 定義表

from django.db import models

# Create your models here.
class UserInfo(models.Model):
    name = models.CharField(max_length=254)
    age = models.IntegerField()


class ArticlePost(models.Model):
    author = models.ForeignKey(UserInfo,on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    desc = models.SlugField(max_length=500)
    body = models.TextField()
app01/models.py

2.4、索引檔案生成

  1)在子應用下建立索引檔案

      在子應用的目錄下,建立一個名為app01/search_indexes.py的檔案

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from haystack import indexes
from .models import ArticlePost

# 修改此處,類名為模型類的名稱+Index,比如模型類為GoodsInfo,則這裡類名為GoodsInfoIndex(其實可以隨便寫)
class ArticlePostIndex(indexes.SearchIndex, indexes.Indexable):
    # text為索引欄位
    # document = True,這代表haystack和搜尋引擎將使用此欄位的內容作為索引進行檢索
    # use_template=True 指定根據表中的那些欄位建立索引檔案的說明放在一個檔案中
    text = indexes.CharField(document=True, use_template=True)

    # 對那張表進行查詢
    def get_model(self):  # 過載get_model方法,必須要有!
        # 返回這個model
        return ArticlePost

    # 建立索引的資料
    def index_queryset(self, using=None):
        # 這個方法返回什麼內容,最終就會對那些方法建立索引,這裡是對所有欄位建立索引
        return self.get_model().objects.all()
app01/search_indexes.py

  2)指定索引模板檔案

# 建立檔案路徑命名必須這個規範:templates/search/indexes/應用名稱/模型類名稱_text.txt
# templates/search/indexes/app01/articlepost_text.txt
{{ object.title }}
{{ object.author.name }}
{{ object.body }}
templates/search/indexes/app01/articlepost_text.txt

  3)使用命令建立索引

python manage.py rebuild_index  # 建立索引檔案

2.5、全文檢索引擎使用

from django.contrib import admin
from django.urls import path,re_path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'app01/', include(('app01.urls', 'app01'), namespace='app01')),
]
urls.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import url
from haystack.views import SearchView
from app01 import views

urlpatterns=[
    url(r'search/$', SearchView(), name='haystack_search'),
]
app01/urls.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
    <div class="col-md-9">
    <div class="row text-center vertical-middle-sm">
        <h1>搜尋關鍵字:{{ query }}</h1>
        <h1>搜尋結果:{{ page.object_list }}</h1>
    </div>
  {# 如果存在搜尋關鍵字 #}
    {% if query %}
        {% for result in page.object_list %}<div class="media">
                <div class="media-body">
                    <h4 class="list-group-item-heading">{{ result.object.title }}</h4>
                    <p class="list-group-item-text">作者:{{ result.object.author.name }}</p>
                    <p class="list-group-item-text">概要:{{ result.object.body|slice:'60'}}</p>
                </div>
            </a>
        </div>
            {% empty %}
            <h3>沒有找到相關文章</h3>
        {% endfor %}
    {% endif %}

{#    分頁外掛,下一頁和上一頁記得要帶上q={{ query }}引數,否則單擊下一頁時會丟失搜尋引數q,而顯示出來全部的文章的第二頁#}
        <div class="pagination">
            <span class="step-links">
                {% if page.has_previous %}
                    <a href="?q={{ query }}&page={{ page.previous_page_number }}">上一頁</a>
                {% endif %}

                <span class="current">
                    Page{{ page.number }} of {{ page.paginator.num_pages }}
                </span>

                {% if page.has_next %}
                    <a href="?q={{ query }}&page={{ page.next_page_number }}">下一頁</a>
                {% endif %}
            </span>
        </div>
    </div>
</body>
</html>
templates/search/search.html
python manage.py rebuild_index                      # 重新建立索引檔案
http://127.0.0.1:8000/app01/search/?q=天龍八部       # 原始碼中匹配時 "q" 所以這裡不能變

6、替換成jieba分詞

    1)將haystack原始碼複製到專案中並改名

'''1.複製原始碼中檔案並改名 '''
將 C:\python37\Lib\site-packages\haystack\backends\whoosh_backend.py檔案複製到專案中
並將 whoosh_backend.py改名為 whoosh_cn_backend.py 放在APP中如:app01\whoosh_cn_backend.py

'''2.修改原始碼中檔案'''
# 在全域性引入的最後一行加入jieba分詞器
from jieba.analyse import ChineseAnalyzer

# 修改為中文分詞法
查詢
analyzer=StemmingAnalyzer()
改為
analyzer=ChineseAnalyzer()

    2)Django內settings內修改相應的haystack後臺檔名

# 全文檢索框架配置
HAYSTACK_CONNECTIONS = {
    'default': {
        # 指定whoosh引擎
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        # 'ENGINE': 'app01.whoosh_cn_backend.WhooshEngine',      #article.whoosh_cn_backend便是你剛剛新增的檔案
        # 索引檔案路徑
        'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
    }
}
# 新增此項,當資料庫改變時,會自動更新索引,非常方便
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
settings.py

3django-haystack+jieba全文索引(前後端分離版)

https://www.cnblogs.com/crazymagic/p/10046593.html
https://www.jb51.net/article/166095.htm
docker:https://www.cnblogs.com/stellar/p/9967347.html