搜索能夠使用最原始的模糊匹配的like方式進行搜索。固然這種搜索方式對於一些小量的數據是很是合適的。可是隨着數據量愈來愈大。這時候咱們就須要使用搜索引擎了。搜索引擎會將全部須要搜索的數據使用算法作一個索引,之後搜索的時候就只須要根據這個索引便可找到相應的數據。搜索引擎作索引的過程會比較慢,甚至佔用空間,可是一旦索引創建完成,那麼之後再搜索的時候就會很快了。html
這個插件是專門給Django提供搜索功能的。django-haystack提供了一個搜索的接口,底層能夠根據本身的需求更換搜索引擎。他其實有點相似於Django中的ORM插件,提供了一個操做數據庫的接口,可是底層具體使用哪一個數據庫是能夠本身設置的。python
django-haystack支持的搜索引擎有Solr、Elasticsearch、Whoosh、Xapian等。Whoosh是基於純Python的搜索引擎,檢索速度快,集成方便。正則表達式
1 pip3 install django-haystack 2 pip3 install whoosh
1.在項目中安裝django-haystack,在settings.py算法
1 INSTALLED_APPS = [ 2 'django.contrib.admin', 3 'django.contrib.auth', 4 'django.contrib.contenttypes', 5 'django.contrib.sessions', 6 'django.contrib.sites', 7 8 # 添加 9 'haystack', 10 ]
2.設置搜索引擎,在settings中數據庫
1 HAYSTACK_CONNECTIONS = { 2 'default': { 3 # 設置haystack的搜索引擎 4 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 5 # 設置索引文件的位置 6 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), 7 } 8 }
3.建立索引類 django
在模型所屬的app下建立一個search_indexes.py文件,而後建立索引類。假如要給News app建立索引,代碼以下:api
1 class NewsIndex(indexes.SearchIndex,indexes.Indexable): 2 text = indexes.CharField(document=True,use_template=True) 3 4 def get_model(self): 5 return News 6 7 def index_queryset(self, using=None): 8 return self.get_model().objects.all()
4.添加url映射 session
1 urlpatterns = [ 2 path('',views.index,name='index'), 3 # 添加search的url映射 4 path('search/',include('haystack.urls')), 5 path('news/', include("apps.news.urls")), 6 ]
5.添加模板app
在templates文件夾下建立如下結構的目錄:ui
1 templates 2 search 3 indexes 4 news(app的名字) 5 news(模型的名字)_text.txt
而後在news_text.txt中添加須要被索引的字段
1 # 根據標題和內容文本 2 {{ object.title }} 3 {{ object.content }}
緊接着templates文件下建立search.html模板文件,haystack會自動在templates文件下尋找這個模板文件渲染,而且會給這個模板傳入page/paginator/query等參數,django內置的分頁與查詢的關鍵字。咱們能夠經過page.object_list獲取到查詢出來的數據。
<ul class="recommend-list"> {% for result in page.object_list %} {% with result.object as news %} <li> <div class="thumbnail-group"> <a href="#"> <img src="{{ news.thumbnail }}" alt=""> </a> </div> <div class="news-group"> <p class="title"> <a href="#">{{ news.title }}</a> </p> <p class="desc"> {{ news.desc }} </p> <p class="more"> <span class="category">{{ news.caetgory.name }}</span> <span class="pub-time">{{ news.pub_time }}</span> <span class="author">{{ news.author.username }}</span> </p> </div> </li> {% endwith %} {% endfor %} </ul>
6.創建索引
1 python manage.py rebuild_index
若是不想每次數據操做後都要手動的建立索引,能夠在settings中配置:
1 # 增刪改查後自動建立索引 2 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
7.使用jieba分詞替換Whoosh默認的分詞
Whoosh默認是採用正則表達式進行分詞的,這對於英文詞彙適用,可是中文支持的很差,這裏替換爲jieba分詞,jieba分詞庫對中文卻支持的好。
安裝
1 pip3 install jieba
安裝完成後,拷貝D:\python\Lib\site-packages\haystack\backends\whoosh_backend.py其中的代碼,將他放在項目的其餘包中,而後建立一個名叫whoosh_cn_backend.py文件,把剛剛複製的代碼粘貼進去,而後再添加如下代碼:
1 import jieba 2 from whoosh.analysis import Tokenizer, Token 3 4 class ChineseTokenizer(Tokenizer): 5 def __call__(self, value, positions=False, chars=False, 6 keeporiginal=False, removestops=True, 7 start_pos=0, start_char=0, mode='', **kwargs): 8 t = Token(positions, chars, removestops=removestops, mode=mode, 9 **kwargs) 10 seglist = jieba.cut(value, cut_all=True) 11 for w in seglist: 12 t.original = t.text = w 13 t.boost = 1.0 14 if positions: 15 t.pos = start_pos + value.find(w) 16 if chars: 17 t.startchar = start_char + value.find(w) 18 t.endchar = start_char + value.find(w) + len(w) 19 yield t 20 21 def ChineseAnalyzer(): 22 return ChineseTokenizer()
而後再將以前的代碼中的分析器analyzer=StemmingAnalyzer()替換爲analyzer=ChineseAnalyzer()就好了。
瞭解更多:http://django-haystack.readthedocs.io/en/master/tutorial.html