- 什么是全文检索?
全文检索不同于特定字段的模糊查询,使用全文检索的效率更高,并且能够对于中文进行分词处理 - 常用的全文检索的包
haystack:django的一个包,可以方便地对model里面的内容进行索引、搜索,设计为支持whoosh,solr,Xapian,Elasticsearc四种全文检索引擎后端,属于一种全文检索的框架
whoosh:纯Python编写的全文搜索引擎,虽然性能比不上sphinx、xapian、Elasticsearc等,但是无二进制包,程序不会莫名其妙的崩溃,对于小型的站点,whoosh已经足够使用
jieba:一款免费的中文分词包
- 使用
#安装包
pip install django-haystack
pip install whoosh
pip install jieba
INSTALLED_APPS = (
'haystack',
)
#添加搜索引擎
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
}
}
#自动生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
#在项目的urls.py添加(注意不是应用)
urlpatterns = [
...
url(r'^search/', include('haystack.urls')),
]
#在应用目录下建立search_indexes.py文件
# coding=utf-8
from haystack import indexes
from models import GoodsInfo
class GoodsInfoIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
return GoodsInfo
def index_queryset(self, using=None):
return self.get_model().objects.all()
#在目录“templates/search/indexes/应用名称/”下创建“模型类名称_text.txt”文件
#goodsinfo_text.txt,这里列出了要对哪些列的内容进行检索
{{ object.gName }}
{{ object.gSubName }}
{{ object.gDes }}