# 全文檢索框架 pip install django-haystack # 全文檢索引擎 pip install whoosh # 中文分詞框架 pip install jieba
heystack一些配置都是固定寫好的,須要注意下html
1.安裝haystack應用python
INSTALLED_APPS = ( ... 'haystack', )
2.在settings.py文件中配置搜索引擎django
# 配置搜索引擎後端 HAYSTACK_CONNECTIONS = { 'default': { # 使用whoosh引擎:提示,若是不須要使用jieba框架實現分詞,就使用whoosh_backend 'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine', # 索引文件路徑 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), # 在項目目錄下建立文件夾 whoosh_index } } # 當添加、修改、刪除數據時,自動生成索引 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
search_indexes.py
文件 定義商品索引類GoodsSKUIndex()
,繼承自indexes.SearchIndex
和indexes.Indexable
後端
from haystack import indexes
from .models import GoodsSKU框架
class GoodsSKUIndex(indexes.SearchIndex, indexes.Indexable):
# 定義字符類型的屬性,名稱固定爲text
# document=True表示創建的索引數據存儲到文件中
# use_template=True表示經過模板指定表中的字段,用於查詢
text = indexes.CharField(document=True, use_template=True)測試
# 針對哪張表進行查詢
def get_model(self):
return GoodsSKUui
# 針對哪些行進行查詢
def index_queryset(self, using=None):
return self.get_model().objects.filter(isDelete=False)
搜索引擎
在templates
下面新建目錄search/indexes/應用名
url
goods
應用中的GoodsSKU
模型類中的字段要創建索引文件夾:search/indexes/goods
在新建目錄下,建立goodssku_text.txt
,並編輯要創建索引的字段,以下圖 spa
templates/search/indexes/goods/goodssku_text_txt
python manage.py rebuild_index
/search/
get
接收關鍵字:q
import haystack.urls url(r'^search/', include(haystack.urls)),
全文檢索結果:
templates/search
目錄下的search.html
search.html
,咱們須要本身創建該html文件,並定義本身的搜索結果頁面 傳遞的上下文包括:
settings.py
文件中設置HAYSTACK_SEARCH_RESULTS_PER_PAGE
HAYSTACK_SEARCH_RESULTS_PER_PAGE
能夠控制每頁顯示數量HAYSTACK_SEARCH_RESULTS_PER_PAGE = 1
search.html
編寫,相似商品列表頁面