haystack是django開源的全文搜索框架 全文檢索:標題能夠檢索,內容也能夠檢索 支持solr ,elasticsearch,whoosh
在setting.py的app中註冊"haystack"
將配置文件放在setting文件中 在你的`settings.py`中,你須要添加一個設置來指示站點配置文件正在使用的後端,以及其它的後端設置。 `HAYSTACK——CONNECTIONS`是必需的設置,而且應該至少是如下的一種: Solr示例 HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://127.0.0.1:8983/solr' # ...or for multicore... # 'URL': 'http://127.0.0.1:8983/solr/mysite', }, } # Elasticsearch示例 HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', }, } Whoosh示例 #須要設置PATH到你的Whoosh索引的文件系統位置 import os HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'), }, } # 自動更新索引 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' # Xapian示例 #首先安裝Xapian後端(http://github.com/notanumber/xapian-haystack/tree/master) #須要設置PATH到你的Xapian索引的文件系統位置。 import os HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'xapian_backend.XapianEngine', 'PATH': os.path.join(os.path.dirname(__file__), 'xapian_index'), }, }
class User(Model): name = CharField(max_length=16) desc = CharField(max_length=255) addr = CharField(max_length=32) makemigrations migrate
若是你想針對某個app例如blog作全文檢索,則必須在blog的目錄下面創建`search_indexes.py`文件,文件名不能修改 建立類UserIndex(給數據加索引) from haystack import indexes from htest.models import User #給表作索引 class UserIndex(indexes.SearchIndex, indexes.Indexable): #類名必須爲須要檢索的Model_name+Index text = indexes.CharField(document=True, use_template=True)#建立一個text字段 #其它字段 # desc = indexes.CharField(model_attr='desc') # addr = indexes.CharField(model_attr='addr') def get_model(self):#重載get_model方法,必需要有! return User def index_queryset(self, using=None): return self.get_model().objects.all()
(肯定搜索範圍,在名稱和標題和內容中查找) text.txt {{object.name}} {{object.title}} {{object.content}}
from django.conf.urls import url,include url(r'^search/', include('haystack.urls'))
<!DOCTYPE html> <html> <head> <title></title> <style> span.highlighted { color: red; } </style> </head> <body> {% load highlight %} {% if query %} <h3>搜索結果以下:</h3> {% for result in page.object_list %} {# <a href="/{{ result.object.id }}/">{{ result.object.title }}</a><br/>#} <a href="/{{ result.object.id }}/">{% highlight result.object.name with query max_length 2%}</a><br/> <p>{{ result.object.desc|safe }}</p> <p>{% highlight result.addr with query %}</p> {% empty %} <p>啥也沒找到</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 %}« 上一頁 {% if page.has_previous %}</a>{% endif %} | {% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}">{% endif %}下一頁 » {% if page.has_next %}</a>{% endif %} </div> {% endif %} {% endif %} </body> </html> #html中顯示的字段要跟表的字段同樣
切換到項目根目錄,運行 python3 manage.py rebuild_index
①創建ChineseAnalyzer.py文件html
#創建ChineseAnalyzer.py文件 #保存在haystack的安裝文件夾下,路徑如「D:\python3\Lib\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_backend.py文件(文件路徑:「D:\python3\Lib\site-packages\haystack\backends」)python
一.在文件的__future__後增長一行(不能夠加在其前): from __future__ import absolute_import, division, print_function, unicode_literals from .ChineseAnalyzer import ChineseAnalyzer #注意 ChineseAnalyzer後有個空格,需去掉 二.查找 analyzer=StemmingAnalyzer() 三.改成 analyzer=ChineseAnalyzer()
③在模板目錄下(templates)新建測試index.html文件,配置路由和視圖函數(測試使用)git
#index.html #搜索欄 <form method='get' action="/search/" target="_blank"> <input type="text" name="q"> <input type="submit" value="查詢"> </form> #urls urlpatterns = [ #url(r'^admin/', admin.site.urls), #url(r'^search/', include('haystack.urls')), url(r'^$',views.index ) ] #views def index(request): return render(request,"index.html")
from haystack.views import SearchView from .models import * class MySeachView(SearchView): def extra_context(self): #重載extra_context來添加額外的context內容 context = super(MySeachView,self).extra_context() side_list = Topic.objects.filter(kind='major').order_by('add_date')[:8] context['side_list'] = side_list return context #路由修改 url(r'^search/', search_views.MySeachView(), name='haystack_search'),
{% highlight result.summary with query %} # 這裏能夠限制最終{{ result.summary }}被高亮處理後的長度 {% highlight result.summary with query max_length 40 %} #html中 <style> span.highlighted { color: red; } </style>