Django haystack實現全文搜尋程式碼示例
一、使用的工具
haystack是django的開源搜尋框架,該框架支援Solr,Elasticsearch,Whoosh,*Xapian*搜尋引擎,不用更改程式碼,直接切換引擎,減少程式碼量。
搜尋引擎使用Whoosh,這是一個由純Python實現的全文搜尋引擎,沒有二進位制檔案等,比較小巧,配置比較簡單,當然效能自然略低。
中文分詞Jieba,由於Whoosh自帶的是英文分詞,對中文的分詞支援不是太好,故用jieba替換whoosh的分片語件。
其他:Python 3.4.4,Django 1.8.3,Debian 4.2.6_3
二、配置說明
現在假設我們的專案叫做Project,有一個myapp的app,簡略的目錄結構如下。
- Project
- Project
- settings.py
- blog
- models.py
此models.py的內容假設如下:
from django.db import models from django.contrib.auth.models import User class Note(models.Model): user = models.ForeignKey(User) pub_date = models.DateTimeField() title = models.CharField(max_length=200) body = models.TextField() def __str__(self): return self.title
1. 首先安裝各工具
pipinstall whoosh django-haystack jieba
2. 新增 Haystack 到Django的INSTALLED_APPS
配置Django專案的settings.py裡面的INSTALLED_APPS新增Haystack,例子:
INSTALLED_APPS = [ 'django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.sites',# Added. haystack先新增, 'haystack',# Then your usual apps... 自己的app要寫在haystakc後面 'blog',]
點我看英文原版
3. 修改 你的settings.py,以配置引擎
本教程使用的是Whoosh,故配置如下:
import os HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine','PATH': os.path.join(os.path.dirname(__file__),'whoosh_index'),},}
其中顧名思義,ENGINE為使用的引擎必須要有,如果引擎是Whoosh,則PATH必須要填寫,其為Whoosh 索引檔案的存放資料夾。
其他引擎的配置見官方文件
4.建立索引
如果你想針對某個app例如mainapp做全文檢索,則必須在mainapp的目錄下面建立search_indexes.py檔案,檔名不能修改。內容如下:
import datetime from haystack import indexes from myapp.models import Note class NoteIndex(indexes.SearchIndex,indexes.Indexable): text = indexes.CharField(document=True,use_template=True) author = indexes.CharField(model_attr='user') pub_date = indexes.DateTimeField(model_attr='pub_date') def get_model(self): return Note def index_queryset(self,using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())
每個索引裡面必須有且只能有一個欄位為document=True,這代表haystack 和搜尋引擎將使用此欄位的內容作為索引進行檢索(primary field)。其他的欄位只是附屬的屬性,方便呼叫,並不作為檢索資料。
注意:如果使用一個欄位設定了document=True,則一般約定此欄位名為text,這是在SearchIndex類裡面一貫的命名,以防止後臺混亂,當然名字你也可以隨便改,不過不建議改。
並且,haystack提供了use_template=True在text欄位,這樣就允許我們使用資料模板去建立搜尋引擎索引的檔案,使用方便(官方推薦,當然還有其他複雜的建立索引檔案的方式,目前我還不知道),資料模板的路徑為yourapp/templates/search/indexes/yourapp/note_text.txt,例如本例子為blog/templates/search/indexes/blog/note_text.txt檔名必須為要索引的類名_text.txt,其內容為
{{ object.title }}
{{ object.user.get_full_name }}
{{ object.body }}
這個資料模板的作用是對Note.title,Note.user.get_full_name,Note.body這三個欄位建立索引,當檢索的時候會對這三個欄位做全文檢索匹配。
5.在URL配置中新增SearchView,並配置模板
在urls.py中配置如下url資訊,當然url路由可以隨意寫。
(r'^search/',include('haystack.urls')),
其實haystack.urls的內容為,
from django.conf.urls import url from haystack.views import SearchView urlpatterns = [ url(r'^$',SearchView(),name='haystack_search'),]
SearchView()檢視函式預設使用的html模板為當前app目錄下,路徑為myapp/templates/search/search.html
所以需要在blog/templates/search/下新增search.html檔案,內容為
{% extends 'base.html' %} {% block content %} <h2>Search</h2> <form method="get" action="."> <table> {{ form.as_table }} <tr> <td> </td> <td> <input type="submit" value="Search"> </td> </tr> </table> {% if query %} <h3>Results</h3> {% for result in page.object_list %} <p> <a href="{{ result.object.get_absolute_url }}" rel="external nofollow" >{{ result.object.title }}</a> </p> {% empty %} <p>No results found.</p> {% endfor %} {% if page.has_previous or page.has_next %} <div> {% if page.has_previous %}<a href="?q={{ query }}&page={{ page.previous_page_number }}" rel="external nofollow" >{% endif %}« Previous{% if page.has_previous %}</a>{% endif %} | {% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}" rel="external nofollow" >{% endif %}Next »{% if page.has_next %}</a>{% endif %} </div> {% endif %} {% else %} {# Show some example queries to run,maybe query syntax,something else? #} {% endif %} </form> {% endblock %}
很明顯,它自帶了分頁。
6.最後一步,重建索引檔案
使用python manage.py rebuild_index或者使用update_index命令。
好,下面執行專案,進入該url搜尋一下試試吧。
三、下面要做的,使用jieba分詞第一步
將檔案whoosh_backend.py(該檔案路徑為python路徑/lib/python3.4/site-packages/haystack/backends/whoosh_backend.py
)拷貝到app下面,並重命名為whoosh_cn_backend.py,例如blog/whoosh_cn_backend.py。修改如下
新增from jieba.analyse import ChineseAnalyzer
修改為如下
schema_fields[field_class.index_fieldname] =
TEXT(stored=True,analyzer=ChineseAnalyzer(),
field_boost=field_class.boost)
第二步
在settings.py中修改引擎,如下
import os HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'blog.whoosh_cn_backend.WhooshEngine','PATH': os.path.join(BASE_DIR,'whoosh_index' },}
第三步
重建索引,在進行搜尋中文試試吧。
索引自動更新
如果沒有索引自動更新,那麼每當有新資料新增到資料庫,就要手動執行update_index命令是不科學的。自動更新索引的最簡單方法在settings.py新增一個訊號。
HAYSTACK_SIGNAL_PROCESSOR =
"haystack.signals.RealtimeSignalProcessor"
官方文件
看了這入門篇,你現在應該大概能配置一個簡單的全文搜尋了吧,如果想自定義怎麼辦? 建議閱讀官方文件和github的原始碼。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。