生活随笔
收集整理的這篇文章主要介紹了
Django搜索工具——全文检索
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 全文檢索不同于特定字段的模糊查詢,使用全文檢索的效率更高,并且能夠對于中文進行分詞處理
- haystack:全文檢索的框架,支持whoosh、solr、Xapian、Elasticsearc四種全文檢索引擎,點擊查看官方網站
- whoosh:純Python編寫的全文搜索引擎,雖然性能比不上sphinx、xapian、Elasticsearc等,但是無二進制包,程序不會莫名其妙的崩潰,對于小型的站點,whoosh已經足夠使用,點擊查看whoosh文檔
- jieba:一款免費的中文分詞包,如果覺得不好用可以使用一些收費產品,點擊查看jieba文檔
- 在虛擬環境中依次安裝需要的包
pip install django-haystack
pip install whoosh
pip install jieba
- 修改test6/settings.py文件,安裝應用haystack
INSTALLED_APPS = (...'haystack',
)
- 在test6/settings.py文件中配置搜索引擎
#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')),
創建引擎及索引
- 在booktest目錄下創建search_indexes.py文件
#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 GoodsInfodef index_queryset(self, using=None):return self.get_model().objects.all()
- 在templates目錄下創建“search/indexes/booktest/”目錄
- 在上面的目錄中創建“goodsinfo_text.txt”文件
#指定索引的屬性
{{object.gcontent}}
- 找到虛擬環境py_django下的haystack目錄
/home/python/.virtualenvs/py_django/lib/python2.7/site-packages/haystack/backends/
- 在上面的目錄中創建ChineseAnalyzer.py文件
import jieba
from whoosh.analysis import Tokenizer, Tokenclass 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 = wt.boost = 1.0if 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 tdef ChineseAnalyzer():return ChineseTokenizer()
- 復制whoosh_backend.py文件,改為如下名稱
- 注意:復制出來的文件名,末尾會有一個空格,記得要刪除這個空格
whoosh_cn_backend.py
- 打開復制出來的新文件,引入中文分析類,內部采用結巴分詞
from .ChineseAnalyzer import ChineseAnalyzer
查找
analyzer=StemmingAnalyzer()
改為
analyzer=ChineseAnalyzer()
python manage.py rebuild_index
使用
- 按照配置,在admin管理中添加數據后,會自動為數據創建索引,可以直接進行搜索,可以先創建一些測試數據
- 在booktest/views.py中定義視圖query
def query(request):return render(request,'booktest/query.html')
url(r'^query/', views.query),
- 在templates/booktest/目錄中創建模板query.html
- 參數q表示搜索內容,傳遞到模板中的數據為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>
- 自定義搜索結果模板:在templates/search/目錄下創建search.html
- 搜索結果進行分頁,視圖向模板中傳遞的上下文如下
- query:搜索關鍵字
- page:當前頁的page對象
- paginator:分頁paginator對象
- 視圖接收的參數如下:
- 參數q表示搜索內容,傳遞到模板中的數據為query
- 參數page表示當前頁碼
<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/
總結
以上是生活随笔為你收集整理的Django搜索工具——全文检索的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。