Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

陈占占
• 阅读 634

Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

1、Django安装 haystack + whoosh + jieba

haystack是django的开源搜索框架,该框架支持Solr,Elasticsearch,Whoosh, 搜索引擎量。 Whoosh是一个搜索引擎使用,这是一个由纯Python实现的全文搜索引擎,没有二进制文件等,比较小巧,配置比较简单,性能略低。 Jieba是由Whoosh自带的是英文分词,对中文的分词支持不是太好,故用jieba替换whoosh的分词组件。

pip install django-haystack
pip install whoosh
pip install jieba

Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

2、创建项目app,配置settings.py文件

# 全文检索框架haystack的配置
HAYSTACK_CONNECTIONS = {
    "default": {
        # 指定使用的搜索引擎
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        # 'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
        # 指定索引文件存放位置
        'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
        'INCLUDE_SPELLING': True,
    }
}
# 当添加、删除、修改数据时,自动生成索引
HAYSTACK_SIGNAL_PROCESSOR = "haystack.signals.RealtimeSignalProcessor"
# 每页显示条数
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 6

Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

3、创建索引

在项目目录下创建​​search_indexes.py​​文件,文件名不能修改。

from haystack import indexes
# 对应模型
from .models import Blog


# 类名:模型名字 + Index
class BlogIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)  # 创建一个text字段
    # blog_title = indexes.CharField(model_attr="blog_title")
    # blog_content = indexes.CharField(model_attr="blog_content")

    def get_model(self):
        # 返回对应模型
        return Blog

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()

Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

4、创建数据模板路径

blog/templates/search/indexes/blog/Blog_text.txt(模型名字 + _text.txt) 模板的作用是让text字段包含的内容,后面有搜索模板会用到。 txt中的内容根据模型类中需要进行搜索的字段进行设置。如我的models.py下的: Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题 博客文章的标题和内容(blog_title、blog_content)就是我搜索的字段。 Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

5、配置路由

from django.contrib import admin
from django.urls import path, include
from blog.views import *

urlpatterns = [
    # path('admin/', admin.site.urls),
    path('blog_index/', blog_index, name="blog_index"),
    path('search/', include('haystack.urls')),
]

Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

6、创建search.html

在目录"templates/search/"下建立search.html作为检索结果返回的页面(可自己进行定制)

{% extends 'Conventional_Template.html' %}
{% load static %}

{% block title %}
    <title>搜索页面</title>
{% endblock %}

{% block section %}

    <section id="bricks">
        <div class="row masonry">
            <div style="display: flex;justify-content: center;align-items: center;">
                <h1>含关键字 -{{ query }}- 的博客文章</h1>
            </div>
            <!-- brick-wrapper -->
            <div class="bricks-wrapper">
                <div class="grid-sizer"></div>
                {% if query %}
                    {% for result in page.object_list %}
                        <article class="brick entry animate-this">
                            <div class="entry-thumb">
                                <a href="#" class="thumb-link">
                                    <img src="{% static 'images/thumbs/liberty.jpg' %}" alt="Liberty">
                                </a>
                            </div>
                            <div class="entry-text">
                                <div class="entry-header">
                                    <div class="entry-meta">
                                    <span class="cat-links">
                                        <a>标签</a>
                                    </span>
                                        <span class="cat-links">
                                        <a>标签</a>
                                    </span>
                                    </div>
                                    <h1 class="entry-title"><a href="#">{{ result.object.blog_title }}</a></h1>
                                </div>
                                <div class="entry-excerpt">
                                    {% autoescape off %}
                                        {{ result.object.blog_content|striptags|truncatechars:150 }}
                                    {% endautoescape %}
                                </div>
                            </div>
                        </article>
                    {% endfor %}
                {% endif %}
            </div> <!-- end brick-wrapper -->
        </div> <!-- end row -->

        <!-- 分页功能 -->
        <div class="row">
            <nav class="pagination">
                {% if page.has_previous %}
                    <span class="page-numbers prev">
                        <a href="?q={{ query }}&page={{ page.previous_page_number }}">Prev</a>
                    </span>
                {% else %}
                {% endif %}

                {% for pindex in paginator.page_range %}
                    {% if pindex == page.number %}
                        <a href="?q={{ query }}&page={{ pindex }}" class="page-numbers">{{ pindex }}</a>
                    {% else %}
                        <a href="?q={{ query }}&page={{ pindex }}" class="page-numbers">{{ pindex }}</a>
                    {% endif %}
                {% endfor %}

                {% if page.has_next %}
                    <a href="?q={{ query }}&page={{ page.next_page_number }}" class="page-numbers next">Next</a>
                {% else %}
                {% endif %}
            </nav>
        </div>
    </section>

{% endblock %}

要注意修改路由路径,name="q"是固定的。 Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

7、创建ChineseAnalyzer.py文件

chenzhanxu_blog\Lib\site-packages\haystack\backends (虚拟环境中-找到haystack下的backends 然后创建ChineseAnalyzer.py文件)

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

chenzhanxu_blog\Lib\site-packages\haystack\backends (虚拟环境中-找到haystack下的backends目录下的whoosh_backend.py,然后复制(复制的文件名末尾有个空格,记得删除)到当前目录下改名whoosh_cn_backend.py) 记得在whoosh_cn_backend.py文件中添加ChineseAnalyzer.py文件。

from haystack.backends.ChineseAnalyzer
import ChineseAnalyzer

然后查找whoosh_cn_backend.py文件中schema_fields[field_class.index_fieldname] = TEXT()。

#schema_fields[field_class.index_fieldname] = TEXT(
#     stored=True,
#     analyzer=field_class.analyzer or 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,
)

Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

9、生成索引

python manage.py rebuild_index
# (可选更新索引)python manage.py update_index

如果在settings.py添加了​​HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'​就不用手动更新索引,系统会自动更新。 生成成功后在根目录下会生成一个whoosh_index的文件夹。 Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

配置 haystack 搜索引擎的问题

1、search.html搜索页面无法返回数据问题

问题原因:可能是PyCharm创建Django是定义templates为模板文件,导致 haystack 无法自动找到templates文件夹,也就无法找到templates文件夹下的search.html模板,无法渲染成功。 解决方法:PyCharm创建Django项目时会把templates文件夹定义成为模板文件,要改成普通文件夹。 Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

成品效果图 Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题 Django 配置搜索引擎 haystack 与 搜索页面无法返回数据问题

个人博客:https://www.chenzhanxu.top/

点赞
收藏
评论区
推荐文章
Irene181 Irene181
3年前
手把手教你使用Flask搭建ES搜索引擎(预备篇)
/1前言/Elasticsearch是一个开源的搜索引擎,建立在一个全文搜索引擎库ApacheLucene™基础之上。那么如何实现Elasticsearch和Python的对接成为我们所关心的问题了(怎么什么都要和Python关联啊)。/2 Python交互/所以,Python也就提供了可以对接Elasti
桃浪十七丶 桃浪十七丶
3年前
新版Chrome如何更换搜索引擎
一、地址栏更换搜索引擎SettingsSearchEngineManageserchenginesDefaultsearchengines或者Othersearchengines.由于我的Chrome是英文版,因此写成英文版本,对应中文设置搜索管理搜索引擎其他搜索引擎二、更换网页搜索引擎单击搜索引擎图标,点击添加/Add,输入http://
ES的索引结构与算法解析
提到ES,大多数爱好者想到的都是搜索引擎,但是明确一点,ES不等同于搜索引擎。不管是谷歌、百度、必应、搜狗为代表的自然语言处理(NLP)、爬虫、网页处理、大数据处理的全文搜索引擎,还是有明确搜索目的的搜索行为,如各大电商网站、OA、站内搜索、视频网站的垂直搜索引擎,他们或多或少都使用到了ES。
Elasticsearch Head插件使用小结
ElasticSearchhead就是一款能连接ElasticSearch搜索引擎,并提供可视化的操作页面对ElasticSearch搜索引擎进行各种设置和数据检索功能的管理插件,如在head插件页面编写RESTful接口风格的请求,就可以对ElasticSearch中的数据进行增删改查、创建或者删除索引等操作。类似于使用navicat工具连接MySQL这种关系型数据库,对数据库做操作
Stella981 Stella981
3年前
Elasticsearch与Solr优缺点比较
Elasticsearch简介Elasticsearch是一个实时的分布式搜索和分析引擎。它可以帮助你用前所未有的速度去处理大规模数据。它可以用于全文搜索,结构化搜索以及分析,也可以将这三者进行组合。Elasticsearch是一个建立在全文搜索引擎ApacheLucene™基础上的搜索引擎,可以说Lucen
Stella981 Stella981
3年前
ElasticSearch学习汇总
什么是ElasticSearch?ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTfulweb接口。Elasticsearch是用Java语言开发的,并作为Apache许可条款下的开放源码发布,是一种流行的企业级搜索引擎。ElasticSearch能够做到实时搜索并且稳定,
Stella981 Stella981
3年前
Chrome浏览器配置&小技巧(面向非技术人员)
注:本文仅面向电脑小白或者非技术人员分享一些常用的Chrome浏览器配置和小技巧一、管理搜索引擎进入搜索引擎管理界面:可以直接在地址栏右键修改搜索引擎,或者进入设置页面选择搜索引擎条目进入设置页面:单击浏览器右上角三点标志选择设置菜单,或者直接在地址栏输入:chrome://settings(chrome://settings
Wesley13 Wesley13
3年前
Java搜索使用引擎
1、Java全文搜索引擎框架Lucene毫无疑问,Lucene是目前最受欢迎的Java全文搜索框架,准确地说,它是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎。Lucene为开发人员提供了相当完整的工具包,可以非常方便地实现强大的全文检索功能。下面有几款搜索引擎框架也是基于Lucene实现的。官方网站:http:
Stella981 Stella981
3年前
Joomla搜索引擎优化
无需其他扩展程序的Joomla核心系统已经为优化搜索引擎系统提供了广泛的可能性。在本文中,我们解释了如何优化Joomla网站(页面优化)。什么是页面优化?页面优化是用于描述搜索引擎优化领域的术语,该领域负责改善网站本身。页面上的优化分为以下几个方面:技术,内容,结构和可用性。随着这些领域的改善,应该实现搜索引擎中位置的持久改善。
Stella981 Stella981
3年前
MQ异步同步搜索引擎ElasticSearch数据踩坑
业务背景  在大型网站中,为了减少DB压力、让数据更精准、速度更快,将读拆分出来采用搜索引擎来为DB分担读的压力,ElasticSearch就是目前市面上比较流行的搜索引擎,他的检索速度奇快、支持各种复杂的全文检索,在各种场景下对比其他的搜索引擎的检索速度都显得尤为出众。这篇就先不介绍ElasticSearch了,后续我会出一个ElasticS