很多的搜索引擎对中的支持不友好,jieba作为一个中文分词器就是加强对中文的检索功能
pip3 install django-haystack
pip3 install whoosh
pip3 install jieba
'''注册app '''
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# haystack要放在应用的上面
'haystack',
'myapp', # 这个jsapp是自己创建的app
]
'''配置haystack '''
# 全文检索框架配置
HAYSTACK_CONNECTIONS = {
'default': {
# 指定whoosh引擎
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
# 'ENGINE': 'myapp.whoosh_cn_backend.WhooshEngine', # whoosh_cn_backend是haystack的whoosh_backend.py改名的文件为了使用jieba分词
# 索引文件路径
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
}
}
# 添加此项,当数据库改变时,会自动更新索引,非常方便
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name = models.CharField(max_length=254)
age = models.IntegerField()
class ArticlePost(models.Model):
author = models.ForeignKey(UserInfo,on_delete=models.CASCADE)
title = models.CharField(max_length=200)
desc = models.SlugField(max_length=500)
body = models.TextField()
在子应用的目录下,创建一个名为 myapp/search_indexes.py 的文件
from haystack import indexes
from .models import ArticlePost
# 修改此处,类名为模型类的名称+Index,比如模型类为GoodsInfo,则这里类名为GoodsInfoIndex(其实可以随便写)
class ArticlePostIndex(indexes.SearchIndex, indexes.Indexable):
# text为索引字段
# document = True,这代表haystack和搜索引擎将使用此字段的内容作为索引进行检索
# use_template=True 指定根据表中的那些字段建立索引文件的说明放在一个文件中
text = indexes.CharField(document=True, use_template=True)
# 对那张表进行查询
def get_model(self): # 重载get_model方法,必须要有!
# 返回这个model
return ArticlePost
# 建立索引的数据
def index_queryset(self, using=None):
# 这个方法返回什么内容,最终就会对那些方法建立索引,这里是对所有字段建立索引
return self.get_model().objects.all()
创建文件路径命名必须这个规范:templates/search/indexes/应用名称/模型类名称_text.txt
如:
templates/search/indexes/myapp/articlepost_text.txt
{{ object.title }}
{{ object.author.name }}
{{ object.body }}
python manage.py rebuild_index # 建立索引文件
'''1.复制源码中文件并改名 '''
将 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/
site-packages/haystack/backends/whoosh_backend.py文件复制到项目中
并将 whoosh_backend.py改名为 whoosh_cn_backend.py 放在APP中如:
myapp\whoosh_cn_backend.py
'''2.修改源码中文件'''
# 在全局引入的最后一行加入jieba分词器
from jieba.analyse import ChineseAnalyzer
# 修改为中文分词法
查找
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()
from django.shortcuts import render
# Create your views here.
import json
from django.conf import settings
from django.core.paginator import InvalidPage, Paginator
from django.http import Http404, HttpResponse,JsonResponse
from haystack.forms import ModelSearchForm
from haystack.query import EmptySearchQuerySet
RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 20)
def basic_search(request, load_all=True, form_class=ModelSearchForm, searchqueryset=None, extra_context=None, results_per_page=None):
query = ''
results = EmptySearchQuerySet()
if request.GET.get('q'):
form = form_class(request.GET, searchqueryset=searchqueryset, load_all=load_all)
if form.is_valid():
query = form.cleaned_data['q']
results = form.search()
else:
form = form_class(searchqueryset=searchqueryset, load_all=load_all)
paginator = Paginator(results, results_per_page or RESULTS_PER_PAGE)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
result = {"code": 404, "msg": 'No file found!', "data": []}
return HttpResponse(json.dumps(result), content_type="application/json")
context = {
'form': form,
'page': page,
'paginator': paginator,
'query': query,
'suggestion': None,
}
if results.query.backend.include_spelling:
context['suggestion'] = form.get_suggestion()
if extra_context:
context.update(extra_context)
jsondata = []
print(len(page.object_list))
for result in page.object_list:
data = {
'pk': result.object.pk,
'title': result.object.title,
'content': result.object.body,
}
jsondata.append(data)
result = {"code": 200, "msg": 'Search successfully!', "data": jsondata}
return JsonResponse(result, content_type="application/json")