赞
踩
pip install django-haystack
全文检索的框架
pip install whoosh
全文检索的引擎
pip install jieba
中文分词器包
INSTALLED_APPS = [ ... 'haystack' ]
HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), } }
HAYSTACK_SIGNAL_PROCESSOR='haystack.signals.RealtimeSignalProcessor'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 10
在需要检索的应用下
from django.db import models class User(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=32) class Meta: db_table = "t_user"
应用下新增索引类
模块名 search_indexes.py (固定的,不能有错误)
from haystack.indexes import SearchIndex, Indexable, CharField
from .models import User
class UserSearchIndex(SearchIndex, Indexable):
查询的域名、必须提供、并且设置 document=True
text = CharField(document=True, use_template=True)
def get_model(self):
return User
def index_queryset(self, using=None):
return self.get_model().objects.all()
在 templates 模板 中,新建如下目录
--templates
--search
--indexes
--appName
--模型名_text.txt
{{ object.username }}
{{ object.password }}
username , password 为 模型中对应的属性,该文件中定义要全文
检索的属性,不需要将 模型中的所有属性都进行定义
url(’^search/’, include(‘haystack.urls’))
<form action="/search/" method="get"> <input type="text" name="q" />
<input type="submit" value="搜索"/>
</form>
name = q 是必须的, 不能修改
q 会从 索引库中 查找要查询的内容,要查询的内容包含的字段为 索
引字段定义的 {{object.xxx}} 决定
提交的地址为 搜索接口路由 配置的 地址, 请求的方式为 GET
处理检索的结果
templates
-- search
-- search.html
在 search.html 中, 获取查询到的数据
后台返回的模板中,包含的常见Key如下
{'page': page,
'paginator': paginator,
'query': query,
}
page : Django 分页插件的page对象
paginator : 分页对象
query : 查询参数
{{ page.object_list }} 返回一个列表,可以对其进行遍历并显示相关信
息
{% for p in page.object_list %}
{{ p.object }}
{% endfor %}
通过 p.object 获取模型对象
处理高亮显示
{% load hightlight %}
{% for p in page.object_list %}
{% highlight p.object.username with query %}
{% endfor %}
添加样式:
<style>
span.highlighted { color: red;}
</style>
默认采用 span 标签,可以进行修改,
{% highlight p.object.username with query html_tag 'em' %}
高亮显示 显示 … 省略了部分内容
解决方案:
修改 haystack.utils.hightlighting.py
160行左右:
源码:
highlighted_chunk = '%s' % highlighted_chunk
更改为:
highlighted_chunk = '%s%s' % (self.text_block [:start_offset] ,highlighted_chunk)
CTRL+N搜索haystack.backends.whoosh_backend.py
拷贝 haystack.backends.whoosh_backend.py 到项目中,并重命名为
whoosh_cn_backend.py
修改 whoosh_cn_backend.py 文件
from jieba.analyse import ChineseAnalyzer
从最下面导入
schema_fields[field_class.index_fieldname] = TEXT(stored=True, analyzer=StemmingAnalyzer(), field_boost=field_class.boost, sortable=True)
修改为
schema_fields[field_class.index_fieldname] = TEXT(stored=True, analyzer=ChineseAnalyzer(), field_boost=field_class.boost, sortable=True)
HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': '项目名.whoosh_cn_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), } }
python manage.py rebuild_index
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。