Django-全文搜索

1.创建app

python manage.py startapp booktest

2.安装富文本库

pip install django-haystack
pip install whoosh
pip install jieba

3.setting添加booktest,配置文件存放位置


INSTALLED_APPS = [
    'multi_captcha_admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest',
    # 'blog',
    'tinymce',
    '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'

4.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
    re_path(r'^search/', include('haystack.urls')),
]

5.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
re_path(r'^mysearch/$', views.mysearch),
]

注:最新版本2.0以上使用path 或者re_path

6.编写views

# coding=utf-8
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from .models import *
from django.views.decorators.cache import cache_page
from django.core.cache import cache
# 全文检索+中文分词
def mysearch(request):
    return render(request, 'booktest/mysearch.html')


7.编写全文搜索文件booktest/search_indexs.py

 

# coding=utf-8
from haystack import indexes
from .models import Test1


class Test1Index(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()



8.在目录“templates/search/indexes/应用名称/”下创建“模型类名称_text.txt”文件

{{ object.content }}

9.在目录“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>


10.建立ChineseAnalyzer.py文件

  • 保存在haystack的安装文件夹下,路径如“/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()

11.复制whoosh_backend.py文件,改名为whoosh_cn_backend.py

from .ChineseAnalyzer import ChineseAnalyzer 
查找
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()


12.生成索引

python manage.py rebuild_index

13.在模板中创建搜索栏

<!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>
<form action="/search/" target="_blank" method="get">
<input type="text" name="q"><input type="submit" value="搜索">
</form>
</body>
</html>

作者: 温先生

嗨,我是温国力 ,Gerry是我的英文名。一名热衷于编程的开发者,主要专注于PHP、Python、go、区块链的开发。此博客编写了开发心得、读书心得、生活娱乐,随时等待你的关注。

发表评论