全文检索不同于特定字段的模糊查询,使用全文检索的效率更高,并且能够对于中文进行分词处理
haystack:django的一个包,属于一种全文检索的框架,可以方便地对model里面的内容进行索引、搜索,完成了对 Solr, Elasticsearch, Whoosh, Xapian, 等等的使用封装,让我们在使用过程中只需更改settings.py中的引擎即可方便切换方法,不用更改其他代码。
安装
pip install django-haystack
配置settings.py文件:
添加应用:
INSTALLED_APPS = (
...
'haystack',
)
添加搜索引擎:
HAYSTACK_CONNECTIONS = {
'default': {
# For Solr:
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://localhost:9001/solr/example',
'TIMEOUT': 60 * 5,
'INCLUDE_SPELLING': True,
},
'whoosh': {
# For Whoosh:
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
'INCLUDE_SPELLING': True,
},
'simple': {
# For Simple:
'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
},
'xapian': {
# For Xapian (requires the third-party install):
'ENGINE': 'xapian_haystack.xapian_backend.XapianEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'xapian_index'),
}
}
在项目的urls.py中添加url:
urlpatterns = [
...
url(r'^search/', include('haystack.urls')),
]