Django全文检索
全文检索不同于特定字段的模糊查询,使用全文检索的效率更高,并且能够对于中文进行分词处理。
- whoosh:纯Python编写的全文搜索引擎,虽然性能比不上sphinx、xapian、Elasticsearc等,但是无二进制包,程序不会莫名其妙的崩溃,对于小型的站点,whoosh已经足够使用,点击查看whoosh文档。
- haystack:全文检索的框架,支持whoosh、solr、Xapian、Elasticsearc四种全文检索引擎,点击查看官方网站。
- jieba:一款免费的中文分词包,如果觉得不好用可以使用一些收费产品。
开始使用
1.在虚拟环境中依次安装需要的包。
pip install django-haystackpip install whooshpip install jieba
2.在配置文件settings.py中添加应用 全文搜索框架haystack
添加到所有自己安装应用的前面
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'haystack', # 全文检索框架
'sp_user.apps.SpUserConfig', # 用户模块
'sp_goods.apps.SpGoodsConfig', # 商品模块
'ckeditor', # 添加ckeditor富文本编辑器
'ckeditor_uploader', # 添加ckeditor富文本编辑器上传部件
]
3.配置全文检索框架haystack支持whoosh搜索引擎
# 全文检索框架的配置
HAYSTACK_CONNECTIONS = {
'default': {
# 配置搜索引擎
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
# 配置索引文件目录
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
},
}
#当添加、修改、删除数据时,自动生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
4.在应用目录(goods)下,创建一个文件search_indexes.py文件
在该文件中定义一个索引类,全文检索框架根据该类生成索引
# 导入全文检索框架索引类
from haystack import indexes
from sp_goods.models import GoodsSKU
class GoodsSKUSearchIndex(indexes.SearchIndex, indexes.Indexable):
# 设置需要检索的主要字段内容 use_template表示字段内容在模板中
text = indexes.CharField(document=True, use_template=True)
# 获取检索对应对的模型
def get_model(self):
return GoodsSKU
# 设置检索需要使用的查询集
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.all()
5.创建模板文件,4 中检索的字段就定义在模板中
创建文件:templates/search/indexes/应用名/模型名小写_text.txt
例如:templates/search/indexes/sp_goods/goodssku_text.txt
在文件中定义需要检索的字段,object就代表get_model()方法返回的对象
# 指定搜索的字段
{{object.sku_name}}
{{object.brief}}
{{object.goods_spu.content}}
6.使用命令生成索引文件
python manage.py rebuild_index
7.在主路由中配置全文检索框架使用的子路由
urlpatterns = [
url(r'^admin/', admin.site.urls),
#全文搜索框架
url(r'^search/', include('haystack.urls')),
# 添加自己的应用的子路由
]
8.创建搜索表单
创建一个form表单,用于搜索,关键点在于:
– 搜索引擎默认接收一个GET方式传递q参数作为搜索关键字
– action 请求地址就是在主路由配置的地址 /search/
<form action="/search/" method="get">
<input type="text" name="q" value="" class="cate-input" placeholder="请输入您要的搜索的产品关键词"/>
<input type="submit" class="cate-btn" value=""/>
</form>
点击进行提交时,会通过haystack搜索数据
9.搜索的结果处理
搜索结果会自动传递给 templates/search/search.html模板页面,并且传递以下关键变量
– query 搜索的关键字
– page 当前页检索结果集----> 遍历后是一个一个的SearchResult对象—>SearchResult.object才是检索的模型(商品)对象
– paginator: 分页paginator对象(自己研究)
{% if query %}
<ul class="list-pro" style="margin-top: 20px">
{% for result in page %}
<li>
<a href="{% url 'sp_goods:detail' result.object.pk %}"><img src="{{ MEDIA_URL }}{{ result.object.logo }}" class="list-pic1"/></a>
<div class="shop-list-mid" style="width: 65%;">
<div class="tit">
<a href="{% url 'sp_goods:detail' result.object.pk %}">
{{ result.object.goods_spu.spu_name }}{{ result.object.sku_name }}
</a>
</div>
<div class="am-gallery-desc">¥{{ result.object.price }}</div>
<p>销量:{{ result.object.sale_num }}件</p>
</div>
</li>
{% empty %}
<li>没有找到您搜索的产品!</li>
{% endfor %}
</ul>
{% endif %}
10.whoosh自带的分词对中文不友好,使用免费的中文分词jieba
– 打开虚拟环境/Lib/site-packages/haystack/backends/
– 在上面的目录下创建ChineseAnalyzer.py文件
– 复制 whoosh_backend.py 改名为 whoosh_cn_backend.py
– 打开复制出来的新文件,引入中文分析类,内部采用jieba分词。
from jieba.analyse import ChineseAnalyzer
– 更改词语分析类
查找
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()
– 修改settings.py文件中的配置项
# 全文检索框架的配置
HAYSTACK_CONNECTIONS = {
'default': {
# 配置搜索引擎
# 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
# 中文分词 使用jieba的whoosh引擎
'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
# 配置索引文件目录
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
},
}
– 重新创建索引数据
python manage.py rebuild_index
– 重写搜索就可以对中文进行分词了
扩展
高亮
highlight
https://django-haystack.readthedocs.io/en/master/templatetags.html?highlight=highlight
每页显示条数:
https://django-haystack.readthedocs.io/en/master/settings.html?highlight=%20HAYSTACK_SEARCH_RESULTS_PER_PAGE#haystack-search-results-per-pagelts-per-page