INSTALLED_APPS = ( ... 'haystack', )
pip install django-haystack pip install whoosh pip install jieba
#coding=utf-8 ... HAYSTACK_CONNECTIONS = { 'default': { #使用whoosh引擎 'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine', #索引文件路徑 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), } } #當添加、修改、刪除數據時,自動生成索引 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
url(r'^search/', include('haystack.urls')),
#coding=utf-8 from haystack import indexes from models import GoodsInfo #指定對於某個類的某些數據創建索引 class GoodsInfoIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return GoodsInfo def index_queryset(self, using=None): return self.get_model().objects.all()
#指定索引的屬性 {{object.gcontent}}
找到虛擬環境py_django下的haystack目錄
/home/python/.virtualenvs/py_django/lib/python2.7/site-packages/haystack/backends/
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()
whoosh_cn_backend.py
from .ChineseAnalyzer import ChineseAnalyzer
查找 analyzer=StemmingAnalyzer() 改成 analyzer=ChineseAnalyzer()
python manage.py rebuild_index
def query(request): return render(request,'booktest/query.html')
url(r'^query/', views.query),
<html> <head> <title>全文檢索</title> </head> <body> <form method='get' action="/search/" target="_blank"> <input type="text" name="q"> <br> <input type="submit" value="查詢"> </form> </body> </html>
<html> <head> <title>全文檢索--結果頁</title> </head> <body> <h1>搜索 <b>{{query}}</b> 結果以下:</h1> <ul> {%for item in page%} <li>{{item.object.id}}--{{item.object.gcontent|safe}}</li> {%empty%} <li>啥也沒找到</li> {%endfor%} </ul> <hr> {%for pindex in page.paginator.page_range%} {%if pindex == page.number%} {{pindex}} {%else%} <a href="?q={{query}}&page={{pindex}}">{{pindex}}</a> {%endif%} {%endfor%} </body> </html>
http://127.0.0.1:8000/query/