一:搜索引擎簡介
一:搜索引擎介紹
django是python語言后台web開發的一個框架,配合一些插件可為web網站實現很方便的搜索功能
django搜索引擎使用whoosh是一個純python開發的全文搜索引擎,小巧簡單
二:搜索引擎作用
搜索引擎可以在表中針對某些關鍵進行全文分析,根據關鍵詞建立索引數據 mu
索引類似於新華字典的目錄,可以快速搜索數據
# 例如 MacBook:商品1,商品2,商品3
二:搜索引擎框架(haystack)
一:作用
直接在django項目中使用whoosh需要關注一些基礎細節問題,而通過haystack這一搜索框架,可以方便地在django中直接添加搜索功能,無需關注索引建立、搜索解析等細節問題。
haystack支持多種搜索引擎,whoosh,solr,elasticsearch等 雖然whoosh性能相比elasticsearch較低,但是其無二進制包程序不會莫名其妙崩潰,在中小型網站完全適用
二:圖解
三:whoosh使用方式
一:安裝依賴包
pip install django-haystack # 安裝haystack框架 pip install whoosh # 安裝whoosh搜索引擎
二:settings配置文件
一:注冊haystack框架
INSTALLED_APPS = [ # 注冊haystack框架 'haystack' ]
二:配置搜索引擎
HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), # whoosh_index 文件夾不需要自己手動創建 會自動創建 } } # 添加此項,當數據庫改變時,會自動更新索引,非常方便 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
三:全局添加url路由
urlpatterns = [ ... url(r'^search/', include('haystack.urls')), ]
四:應用目錄下創建search_indexes.py文件(固定名稱)
search_indexes代碼
from haystack import indexes # 導入索引 from . import models # 導入模型表 class GoodsIndex(indexes.SearchIndex,indexes.Indexable): text = indexes.CharField(document=True,use_template=True)
'''
document:使用文檔建立索引字段
use_template:使用模板語法
'''
def get_model(self): # 為那個模型表建立索引 return models.GoodInfo def index_queryset(self, using=None): return self.get_model().objects.all()
五:模板文件夾創建如下文件
_text.txt指定模型表中那些字段建立索引
# 指定那些字段建立索引 {{object.name}} # 商品名稱建立索引 {{object.desc}} # 商品簡介建立索引
六:生成索引文件
python manage.py rebuild_index
七:在templates/search下建立search.html文件
搜索出結果后,haystack會把搜索出的結果傳遞給templates/search目錄下的search.html,傳遞的上下文包括:
query:搜索關鍵字
page:當前頁的page對象 –>遍歷page對象,獲取到的是SearchResult類的實例對象,對象的屬性object才是模型類的對象。
paginator:分頁paginator對象
<form action="/search" method="get"> <p>商品搜索:<input type="text" name="q"></p> <p>提交:<input type="submit"></p> </form> <p>搜索關鍵字:{{ query }}</p> <p>當前頁page對象:{{ page }}</p> <p>分頁對象:{{ paginator }}</p> <ul> {% for item in page %} <li> {{ item.object.name }}</li> <li> {{ item.object.desc }}</li> {% endfor %} </ul>
通過HAYSTACK_SEARCH_RESULTS_PER_PAGE 可以控制每頁顯示數量。
四:jieba
一:安裝
pip install jieba
二:作用
whoosh不能很好的進行分詞 而使用jieba可以很好的分詞
二:使用方式
import jieba split_data = '很好吃的草莓' # 要被切割的數據 res = jieba.cut(split_data,cut_all=True) print(res) # <generator object Tokenizer.cut at 0x0000000009EA27D8> 拿到一個生成器 for value in res: print(value)
三:Haystack使用方式
一:在haystack的安裝文件夾下,例如D:\Softwares\python3.6\Lib\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()
二:將上面backends目錄中的whoosh_backend.py文件,復制一份命名為whoosh_cn_backend.py,然后打開此文件進行替換:
# 頂部引入剛才添加的中文分詞 from .ChineseAnalyzer import ChineseAnalyzer # 在整個py文件中,查找 替換 analyzer=StemmingAnalyzer()
analyzer=ChineseAnalyzer()
三: 修改settings.py文件中的配置項。
HAYSTACK_CONNECTIONS = { 'default': { # 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', # 原來的默認的 'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine', # jieba搜索 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), # whoosh_index 文件夾不需要自己手動創建 會自動創建 } }
四:重新生成索引文件
python manage.py rebuild_index