安裝和配置
1.安裝。
pip install django-haystack==2.6.1# 安裝全文檢索框架
pip install whoosh==2.7.4# 安裝whoosh搜索引擎
2.配置。
在settings.py文件中添加如下配置:INSTALLED_APPS = (# ...'haystack',# 全文檢索框架# ...)
# 全文檢索框架配置
HAYSTACK_CONNECTIONS = {'default': {# 使用whoosh引擎'ENGINE':'haystack.backends.whoosh_backend.WhooshEngine',# 索引文件路徑'PATH': os.path.join(BASE_DIR,'whoosh_index'),? ? }}
# 當添加、修改、刪除數據時,自動生成索引
HAYSTACK_SIGNAL_PROCESSOR ='haystack.signals.RealtimeSignalProcessor'
索引文件生成
1.在goods應用目錄下新建一個search_indexes.py文件,在其中定義一個商品索引類。
from haystack import indexes
from goods.models import GoodsSKU
#指定對于某個類的某些數據建立索引
class GoodsSKUIndex(indexes.SearchIndex, indexes.Indexable):
?????? text = indexes.CharField(document=True,use_template=True)
????? def? get_model(self):
????????????? return? GoodsSKU
????? def? index_queryset(self, using=None):
????????? returnself.get_model().objects.all()
2.在templates下面新建目錄search/indexes/goods。
3.在商品的目錄下創建goodssku_text.txt。
4.在goodssku_text.txt中指定根據哪些字段建立索引。
5.在終端執行如下命令生成索引文件。
python manage.py rebuild_index
更改分詞方式
1.安裝jieba分詞包。
pip install jieba
2.進入haystack目錄。
/home/python/.virtualenvs/dailyfresh/lib/python3.5/site-packages/haystack/backends/
3.在上面的目錄中創建ChineseAnalyzer.py文件。
impor tjieba
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()
4.復制whoosh_backend.py文件為如下名稱。
? whoosh_cn_backend.py
5.打開whoosh_cn_backend.py,引入中文分析類,內部采用jieba分詞。
from .ChineseAnalyzer? import? ChineseAnalyzer
6.更改whoosh_cn_backend.py文件中使用的詞語分析類。
查找
analyzer=StemmingAnalyzer()
改為
analyzer=ChineseAnalyzer()
7.修改settings.py文件中的配置項。
8.重新創建索引數據。
python manage.py rebuild_index