1.首先安装haystack、whoosh、jieba,
pip install django-haystack
pip install whoosh
pip install jieba
haystack: django的一个包,可以方便地对model里面的内容进行索引、搜索。设计为支持whoosh,soir,Xapian,Elasticsearc四种全文检索引擎后端,属于一种全文检索的框架
whoosh: 纯Python编写的全文搜索引擎,虽然性能比不上sphix、xapian、Elasticsearc等,但是无二进制包,程序不会莫名其妙的奔溃,对于小型的站点,whoosh已经足够使用
jieba:一款免费的中文分词包
2.在settings中进行配置
在INSTALLED_APPS添加 haystack
INSTALLED_APPS = (
'haystack',
)
3.添加搜索引擎
在settings中进行配置
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
}
}
4.在应用目录(即要设为检索关键字的应用目录下)下新建一个search_indexes.py文件(名字是固定的不能改)
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
# 检索 Goodsinfo 中所有内容,即商品表所有内容
def index_queryset(self,using=None):
return self.get_model().objects.all()
在目录”templates/search/indexes/应用名称/”下创建”模型类名称_text.txt”文件(我建立的是goodsinfo_text.txt),格式如下
{{object.gname}}
{{object.gjianjie}}
{{object.gdescribe}}
txt中的内容根据模型类本身的属性进行添加
5.在url中配置检索结果返回的地址
urlpatterns = [
url(r'^search/', include('haystack.urls')),
]
6.在目录”templates/search/”下建立search.html作为检索结果返回的页面
<ul class="goods_type_list clearfix" id="search">
{% if query %}
{%for goods in page %}
<li>
<a href="/user/{{goods.object.id}}"><img src="/static/{{goods.object.gpic}}"></a>
<h4> <a href="/user/{{goods.id}}">{{goods.object.gname}}</a> </h4>
<div class="operate">
<span class="prize">¥{{goods.object.gprice}}</span>
<span class="unit">{{goods.object.gprice}}/{{goods.object.gdanwei}}</span>
<a href="javascript:;" class="add_goods" title="加入购物车" id="{{goods.object.id}}" ></a>
</div>
</li>
{% empty %}
<li> 没有匹配到搜索结果 </li>
{%endfor%}
{% endif %}
</ul>
7.建立ChineseAnalyzer.py文件
保存在haystack的安装文件夹下,路径如“D:\Lib\site-packages\haystack\backends”下
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()
8.复制whoosh_backend.py文件,改名为whoosh_cn_backend.py
#添加
from .ChineseAnalyzer import ChineseAnalyzer
# 将文件中的
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()
9.执行命令生成索引
python manage.py rebuild_index
生成成功后在根目录下会生成一个whoosh_index的文件夹
10,这个时候,当你点击搜索按钮时,会自动跳转到自己定义的搜索页面显示。
11,这些配置跟操作,都是定死的,只要我们能按部就班的把每一步做好,实现全文检索不是什么问题。
希望能增加自己印象,同时对别人有所帮助。