下面小编就为大家带来一篇python django使用haystack:全文检索的框架(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
haystack:全文检索的框架
whoosh:纯python编写的全文搜索引擎
jieba:一款免费的中文分词包
首先安装这三个包
pip install django-haystack
pip install whoosh
pip install jieba
1.修改settings.py文件,安装应用haystack,
2.在settings.py文件中配置搜索引擎
haystack_connections = {
'default': {
# 使用whoosh引擎
'engine': 'haystack.backends.whoosh_cn_backend.whooshengine',
# 索引文件路径
'path': os.path.join(base_dir, 'whoosh_index'),
}
}
# 当添加、修改、删除数据时,自动生成索引
haystack_signal_processor = 'haystack.signals.realtimesignalprocessor'
3. 在templates目录下创建“search/indexes/blog/”目录 采用blog应用名字下面创建一个文件blog_text.txt
#指定索引的属性
{{ object.title }}
{{ object.text}}
{{ object.keywords }}
4.在需要搜索的应用下面创建search_indexes
from haystack import indexes
from models import post #指定对于某个类的某些数据建立索引
class goodsinfoindex(indexes.searchindex, indexes.indexable):
text = indexes.charfield(document=true, use_template=true)
def get_model(self):
return post #搜索的模型类
def index_queryset(self, using=none):
return self.get_model().objects.all()
5.
1. 修改haystack文件
2. 找到虚拟环境py_django下的haystack目录 这个目录根据自己使用的python环境不同,路径也不一样。
3. site-packages/haystack/backends/ 创建一个文件名为chineseanalyzer.py文件写入下面代码,用于中文分词
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()
6.
1. 复制whoosh_backend.py文件,改为如下名称
whoosh_cn_backend.py
在复制出来的文件中导入中文分词模块
from .chineseanalyzer import chineseanalyzer
2. 更改词语分析类 改成中文
查找analyzer=stemminganalyzer()改为analyzer=chineseanalyzer()
7. 最后一步就是建初始化索引数据
python manage.py rebuild_index
8. 创建搜索模板 在templates/indexes/ 创建search.html模板
搜索结果进行分页,视图向模板中传递的上下文如下
query:搜索关键字
page:当前页的page对象
paginator:分页paginator对象
9. 在自己的应用视图中导入模块
from haystack.generic_views import searchview
定义一个类重写get_context_data 方法,这样就可以往模板中传递自定义的上下文。
class goodssearchview(searchview):
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['iscart']=1
context['qwjs']=2
return context
应用的urls文件中添加这条url 将类当一个视图的方法使用 .as_view()
url('^search/$', views.blogsearchview.as_view())
以上就是python中如何django使用haystack:全文检索的框架的实例讲解的详细内容。