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

网站实现全文搜索,并对中文进行分词搜索

开发环境: Python3.7 Django3.2

需求:

网站内有商品、求购2个模块, 搜索栏输入 塑料玩具 时,希望优先搜索出匹配 塑料玩具 的信息, 并同时匹配出 塑料玩具等信息,按照匹配度排序。同时当输入 玩具塑料塑料玩巨 错别字时,同样能匹配到 塑料玩具 类的信息 。

匹配英文大小写

分析

1.django orm 的模糊匹配 icontains 表示 Mysql的like,不满足业务分词需求,并且随着数据量增大,消耗的资源和时间都会线性增长。
2.Elasticsearch 符合业务需求,但是部署时对服务器性能要求较高,网站的业务数据量预期不超过10万条。

选择 jieba 中文分词器 + whoosh 全文搜索引擎 + haystack搜索框架

代码实现
django   settings.py  配置

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

######################################
# haystack配置
######################################
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'apps.framework.whoosh_cn_backend.WhooshEngine',
        'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
    },
}
# 当添加、修改、删除数据时,自动生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
# 默认查询加载数据大小
HAYSTACK_ITERATOR_LOAD_PER_QUERY = 500

注意:
HAYSTACK_ITERATOR_LOAD_PER_QUERY 默认是10, 当索引库过大时,会导致频繁切词,影响查询速度。

jieba中文分词组件

import jieba
from whoosh.analysis import Tokenizer,Token



class ChineseTokenizer(Tokenizer):
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = object.__new__(cls)
        return cls._instance
    
    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

复制 django-haystack 库中的 haystack.backends.backends.whoosh_backend.py 文件

引入上面的分词模块
from framework.chinese_analyzer import ChineseAnalyzerInstance

此时的匹配模式是分词  AND 匹配,如果想 OR 匹配,找到这行代码 改为:

self.parser = QueryParser(self.content_field_name, schema=self.schema, group=OrGroup)

接下来在创建索引
在模块中创建 search_index.py

from haystack import indexes
from business.models import Quotation

class QuotationIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)

    def get_model(self):
        return Quotation

    def index_queryset(self, using=None):
        """返回要建立索引的数据查询集"""
        return self.get_model().objects.filter(is_delete=0)

在templates 下创建 txt
对应模块路径
templates/serach/indexes/business/quotation_text.txt

{{ object.title  }}

使用manager 命令生成 索引

python manage.py rebuild_index

最后,在view中使用吧

class VisitorQuotationView(viewsets.GenericViewSet):
    # 列表数据
    def list(self, request, *args, **kwargs):
        key = request.GET.get('key', "")
        all_results = SearchQuerySet().auto_query(key).models(Quotation)
        return Response({'data': all_results }, status=status.HTTP_200_OK)

到这里,一个简单的全文搜索就完成了。

当输入key是英文+数字时,whoosh将会使用全词匹配,不使用切词 + 模糊搜索

你可能感兴趣的:(django-haystack + whoosh + jieba 实现全文搜索)