标签:att tac form empty search als ops 项目 dex
官方文档:
http://django-haystack.readthedocs.io/en/v2.4.1/tutorial.html
安装全文检索管理模块haystack、全文搜索引擎模块whoosh和中文分词jieba
pip install django-haystack
pip install whoosh
pip install jieba
全文检索搜索过程是由haystack模块进行操作的,所以搜索路由操作交给haystack进行处理,修改路由配置如下:
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‘
#
配置全文检索路由
urlpatterns = [
...
re_path(r‘^search/‘, include(‘haystack.urls‘)),
]
#
管理搜索的数据模型
# coding=utf-8
from haystack import indexes
from shopadmin import Good
class GoodIndex(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()
#_text.txt
,这里列出了要对哪些列的内容进行检索
编辑可搜索内容
{{ object.name }}
{{ object.description }}
#
构建索引展示页面
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% if query %}
<h3>
搜索结果如下:
</h3>
{% for result in page.object_list %}
<a href="/{{ result.object.id }}/">{{ result.object.name }}</a><br/>
{% empty %}
<p>
啥也没找到
</p>
{% endfor %}
{% if page.has_previous or page.has_next %}
<div>
{% if page.has_previous %}<a href="?q={{ query }}&page={{ page.previous_page_number }}">{% endif %}«
上一页
{% if page.has_previous %}</a>{% endif %}
|
{% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}">{% endif %}
下一页
»{% if page.has_next %}</a>{% endif %}
</div>
{% endif %}
{% endif %}
</body>
</html>
whoosh作为一个全文搜索模块,分词功能和检索功能已经非常强大,但是针对中文的处理还是比较欠缺,所以通过jieba模块重写分词操作,支持whoose对中文的强大操作
打开安装的whoosh模块目录,在python安装目录的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()
from .ChineseAnalyzer import ChineseAnalyzer
查找
analyzer=StemmingAnalyzer() #
搜索查询赋值参数
改为
analyzer=ChineseAnalyzer() #
将分析器对象更改为我们自定义的中文分词分析器
python manage.py rebuild_index
<form method=‘get‘ action="/search/" target="_blank">
<input type="text" name="q">
<input type="submit" value="
查询
">
</form>
标签:att tac form empty search als ops 项目 dex
原文地址:https://www.cnblogs.com/canhun/p/11056420.html