Django的全文检索

1,下载django-haystack

pip install django-haystack

2,注册应用

‘ haystack ’,

3,配置whoosh搜索引擎(在主应用settings.py下方)

HAYSTACK_CONNECTIONS = {
    'default': {  'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH':  BASE_DIR / 'whoosh_index'
    },
}

4,在应用(需要检索)应用下方新建search_indexes.py

内容为:

from haystack import indexes

from .models import News(模型名)


class NewsIndex(indexes.SearchIndex, indexes.Indexable):

    text = indexes.CharField(document=True, use_template=True)



    def get_model(self):

        return News


    
    def index_queryset(self, using=None):

        """Used when the entire index for model is updated."""

        return self.get_model().objects.all()

5,新建搜索模板  项目下方templates中创建嵌套文件夹

templates/ search /indexes / myapp / 应用名_text.txt

在  应用名_text.txt 写可以用来检索的内容:{{ object.title }}
                                                                      {{ object.content}}

6,在项目路由下添加      path('search/',include('haystack.urls')),

7,设置搜索结果模板(搜索成功后的html页面)

(1)在 templates 下方 search 文件夹下方创建 search.html文件

(2)内容:

{% extends 'base.html' %}

{% block title %}

<title> 新闻网搜索结果 </title>

{% endblock %}


{% block main %}

    {% if query %}

        <h3>搜索结果</h3>

            {% for result in page.object_list %}

            <p>

                <a href="{% url 'news:detail' result.object.id %}">{{ result.object.title }}</a>

            </p>

            {% endfor %}

    {% endif %}

{% endblock %}

8,安装whoosh

pip install whoosh

9,使用jieba 中文分词

(1)下载jieba:pip install jiaba

(2)配置使用中文检索:

(2.1)将haystack.backends.whoosh_backend的内容复制应用下方 改名为whoosh_cn_backend

(2.2) 替换47行内容:from jieba.analyse import ChineseAnalyzer

(2.3)替换232行内容: analyzer=field_class.analyzer orChineseAnalyzer(),

(2.4)替换793行内容: sa = ChineseAnalyzer()

10,从新配置引擎

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': '应用名.whoosh_cn_backend.WhooshEngine',
        'PATH': BASE_DIR / 'whoosh_index',
    },
}

11,针对内容构建索引

python .\manage.py rebuild_index

12, 配置搜索表单

(1)action = '/search/’

(2)method = 'get'

  (3) name = " q "

  注:固定不可变

<form class="navbar-form navbar-left"  action="/search/"  method="get">
        <div class="form-group">
          <input type="text" name="q"  class="form-control" placeholder="输入搜索内容">
        </div>
        <button type="submit"   class="btn btn-default">搜索</button>
</form>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值