一:使用的工具
- 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
- Project
此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. 首先安裝各工具
pip install 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 }}">{{ 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 }}">{% endif %}« Previous{% if page.has_previous %}</a>{% endif %} | {% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}">{% 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
分詞
1 將文件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)
2 在settings.py
中修改引擎,如下
import os HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'blog.whoosh_cn_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index' }, }
3 重建索引,在進行搜索中文試試吧。
索引自動更新
如果沒有索引自動更新,那么每當有新數據添加到數據庫,就要手動執行update_index
命令是不科學的。自動更新索引的最簡單方法在
settings.py
添加一個信號。
HAYSTACK_SIGNAL_PROCESSOR =
"haystack.signals.RealtimeSignalProcesso"