为了账号安全,请及时绑定邮箱和手机立即绑定

django全文检索

标签:
Linux

-------------------linux下配置操作
1、在虚拟环境中依次安装包
1、pip install django-haystack
haystack:django的一个包,可以方便地对model里面的内容进行索引、搜索,设计为支持whoosh,solr,Xapian,Elasticsearc四种全文检索引擎后端,属于一种全文检索的框架
2、pip install whoosh
whoosh:纯Python编写的全文搜索引擎,虽然性能比不上sphinx、xapian、Elasticsearc等,但是无二进制包,程序不会莫名其妙的崩溃,对于小型的站点,whoosh已经足够使用

3、pip install jieba
一款免费的中文分词包。

2、修改settings.py文件
1、添加应用
INSTALLED_APPS = (
...
'haystack',
)
2、添加搜索引擎
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
}
}
3、添加自动生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
3、在项目的urls.py中添加url
1、
urlpatterns = [
...
url(r'^search/', include('haystack.urls')),
]

4、在应用目录下建立search_indexes.py文件

coding=utf-8

from haystack import indexes
from models import GoodsInfo
class NoteIndex(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()

5、在目录“templates/search/indexes/应用名称/”下创建“模型类名称_text.txt”文件
#goodsinfo_text.txt,这里列出了要对哪些列的内容进行检索
{{ object.gName }}
{{ object.gSubName }}
{{ object.gDes }}

6、在目录“templates/search/”下建立search.html
{% if query %}
<h3>搜索结果如下:</h3>
{% for result in page.object_list %}
<a href="/{{ result.object.id }}/">{{ result.object.gName }}</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 %}

7、建立ChineseAnalyzer.py文件
1、保存在haystack的安装文件夹下,路径如“/home/python/.virtualenvs/django_py2/lib/python2.7/site-packages/haystack/backends”
2、文件中编写的内容如下
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
1、
2、
from ChineseAnalyzer import ChineseAnalyzer
查找
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()

9、生成索引
1、
python manage.py rebuild_index
10、在模板中创建搜索栏
1、
<form method='get' action="/search/" target="_blank">
<input type="text" name="q">
<input type="submit" value="查询">
</form>
-------------------haystack的content回调数据的扩展操作
1、创建一个viewSearch.py文件

views.py

from datetime import date
from haystack.generic_views import SearchView
from shopping.models import
from ucenter.models import

#创建一个类MySearchView继承SearchView
class MySearchView(SearchView):
"""My custom search view."""
def get_context_data(self, *args, *kwargs):
context = super(MySearchView, self).get_context_data(
args, **kwargs)
context['username'] = self.request.session.get('username', default='')
sessionUserId = self.request.session.get('userId', default='')
cartList = UserInfo.objects.get(pk=sessionUserId).cartinfo_set.all()
cartCount = 0
for cartInfo in cartList:
cartCount += cartInfo.qty
context['cartCount'] = cartCount
print context #查看响应数据的结构

do something

return context
2、之后配置url
url(r'^search/',MySearchView.as_view()), #include('haystack.urls')
3、根据相应的数据进行模板页的编写

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消