django-haystack+whoosh+jieba实现中文全文搜索

django-haystack+whoosh+jieba实现中文全文搜索


附上个人网站:https://liyuankun.cn

安装依赖库

注意:这里我们不安装django-haystack,因为要添加中文分词的功能很麻烦,所以我直接集成了一个中文的django-haystack包
下载地址:https://github.com/PythonerKK/django-haystack-chinese/
pip安装以下:

pip install whoosh jieba 项目配置

新建一个名为extra_apps的目录,把django-haystack包复制进去:

django-haystack+whoosh+jieba实现中文全文搜索

把这个目录设置为项目搜索根目录,修改settings.py文件

import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))

添加到install_app中,修改settings.py文件

INSTALLED_APPS = [ ... 'haystack', ]

继续修改settings.py,添加haystack配置项

HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), } } # 每页显示搜索结果数目为10 HAYSTACK_SEARCH_RESULTS_PER_PAGE = 10 # 自动生成索引 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

然后在项目的urls.py中加入:

urlpatterns = [ ... path('search/', include('haystack.urls')) ] 集成到自己的app中

在自己的app中添加search_indexes.py文件

django-haystack+whoosh+jieba实现中文全文搜索

search_indexes.py文件内容

from haystack import indexes from .models import Post class IdeaIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): # 这里修改成你自己的数据库模型 return Post def index_queryset(self, using=None): return self.get_model().objects.all()

在templates文件下新增一个目录search/indexes/(你的app名)/(你的app名)_text.txt:

django-haystack+whoosh+jieba实现中文全文搜索

{{ object.title }}
{{ object.content }}
添加后修改search.htmlhtml
<!DOCTYPE html>





{% if query %}
搜索结果如下:
{% for result in page.object_list %}
{{ result.object.title }}

{% empty %}

啥也没找到


{% 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 %}


# 关键字高亮 这个非常简单,直接在模板中引入如下字段即可search.html```

{% load highlight %} <style> span.highlighted { color: red; } </style> ... {% highlight query with xxx.object.title %}

如上所示,query就是代表搜索关键字,只需要一句代码就可以完成高亮

重建索引

按照上述步骤,应该就能成功了,接下来我们来重建索引

python manage.py rebuild_index

运行后选择y,然后就会提示建立索引成功

django-haystack+whoosh+jieba实现中文全文搜索

注意事项

django-haystack+whoosh+jieba实现中文全文搜索

这里必须严格按照这个结构创建,需要注意.txt文件名要全部小写!!

效果图

django-haystack+whoosh+jieba实现中文全文搜索

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyydps.html