Django积木块十——全文检索

全文检索

全文检索效率更高,对中文可以进行分词

<!--# 1.安装包-->
pip install django-haystack
pip install whoosh
pip install jieba

<!--# 2.生成一个新的app或者之前的app也可以,setting中的配置-->
'haystacktest',
'haystack',
<!--# 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'

<!--# 3. url-->
# golbal search
    url(r'sea/',include('haystacktest.urls',namespace='search')),
    # 这个URL是必须要写的
	url(r'^search/', include('haystack.urls')),

<!--# 4. 在当前的app中新建一个search_indexes.py 文件-->
# -*- coding:utf-8 -*-
from haystack import indexes
from .models import Test1

class TestIndex(indexes.SearchIndex,indexes.Indexable):
    text = indexes.CharField(document=True,use_template=True)

    def get_model(self):
        return Test1
    # 对哪个表的哪个数据进行检索,可以在后面写上过滤条件
    def index_queryset(self, using=None):
        return self.get_model().objects.all()

<!--# 5. 在目录templates/search/indexes/上面那个文件所在的app的名字/模型类名字_text.txt-->
<!--# 注意 object是必须要写的-->
{{ object.name }}
{{ object.age }}
{{ object.sex }}

<!--# 6.在目录templates/search中建立一个search.html-->
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
{% if query %}
    <h3>搜索结果如下:</h3>
    {% for result in page.object_list %}
        {{ result.object.id }}
        <br>
        {{ result.object.content|safe }}
        <hr>
    {% empty %}
        <p>啥也没找到</p>
    {% endfor %}

    {% if page.has_previous or page.has_next %}
        <div>
            {% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; 上一页{% if page.has_previous %}</a>{% endif %}
        |
            {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}下一页 &raquo;{% if page.has_next %}</a>{% endif %}
        </div>
    {% endif %}
{% endif %}
</body>
</html>

<!--# 7.在C:Python27Libsite-packageshaystackackends中新建一个文件-->
<!--# ChineseAnalyzer.py 下面的代码是使用jieba必须的-->
import jieba
from whoosh.analysis import RegexAnalyzer
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):
        #assert isinstance(value, text_type), "%r is not unicode" % value
        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.复制C:Python27Libsite-packageshaystackackends中的whoosh_backend.py 把它改为whoosh_cn_backend.py-->

from .ChineseAnalyzer import ChineseAnalyzer
将原来的analyzer=StemmingAnalyzer()
改为analyzer=ChineseAnalyzer()

<!--# 9.生成索引之后会自动生成之前设置中设置的文件夹 whoosh_index-->
python manage.py rebuild_index

<!--# 10 创建搜索 -->
<!--# 在模版中创建搜索栏-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
</head>
<body>
<!--/search/对应url(r'^search/', include('haystack.urls')),-->
<form action="/search/" target="_blank" method="get">
{#    这里的name必须是q   #}
    <input type="text" name="q">
    <input type="submit" value="搜索">
</form>
</body>
</html>

<!---->
urlpatterns = [
    url(r'^$',mysearch)
 ]

<!---->
def mysearch(request):
    return render(request,'mysearch.html')
 

注意

还可以自定义搜索结果出现的上下文,需要先注释掉总的URL中的search然后在搜索所在的app的view中重新写视图,在当前的urls中新增一个链接,具体的查看Django-haystack文档

# view
from haystack.views import SearchView
class MySearchView(SearchView):
    def extra_context(self):
        context = super(MySearchView,self).extra_context()
        context['new'] = 'a'
        return context

# url 这里和一般的视图类的写法不一样哦。
url(r'^search',MySearchView())
原文地址:https://www.cnblogs.com/NeedEnjoyLife/p/6991276.html