Django全文搜索框架haystack 和 drf_haystack

时间:2021-07-11
本文章向大家介绍Django全文搜索框架haystack 和 drf_haystack,主要包括Django全文搜索框架haystack 和 drf_haystack使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1、安装和配置

# 安装
pip install whoosh
pip install jieba
pip install django-haystack
pip install drf_haystack

配置

# 在INSTALL_APPS里加上 haystack (加在最后)
INSTALLED_APPS = [
    ...
    'haystack',
    ...
]
# 增加搜索引擎配置(有solr,whoosh,elastic search),这里选择whoosh
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
    },
}
# 配置自动更新索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
# 配置搜索结果的分页器的每页数量(rest-framework里面用不到)
# HAYSTACK_SEARCH_RESULTS_PER_PAGE = 10

2、指明要索引的字段


创建上图所示路径及文件

# 创建文件 templates/search/indexes/myapp/note_text.txt
# myapp是想要建立索引的app,note是你要建立缩印的那个模型名字(小写)
# txt文件内容:将title、content、和id三个字段添加到索引
{{ object.title }}
{{ object.content }}
{{ object.id }}

3、编辑search_indexes.py文件

# 在app中新建search_indexes.py文件,并编辑以下内容
from haystack import indexes

from .models import Article


class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
    """
    Article索引数据模型类
    """
    text = indexes.CharField(document=True, use_template=True)
    id = indexes.IntegerField(model_attr='id')
    title = indexes.CharField(model_attr='title')
    content = indexes.CharField(model_attr='content')
    # 下面的createtime字段并没有在上面加索引,写上是因为后面的过滤filter和排序order_by用到
    # 注意:这里修改的话一定要重新建立索引,才能生效。python manage.py rebuild_index
    createtime = indexes.DateTimeField(model_attr='createtime')

    def get_model(self):
        """返回建立索引的模型类"""
        return Article

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

4、编辑索引的serializer序列化器

# 在serializer.py文件中进行编辑
class ArticleIndexSerializer(HaystackSerializer):
    """
    Article索引结果数据序列化器
    """
    class Meta:
        index_classes = [ArticleIndex]
        fields = ('text', 'id', 'title', 'content', 'createtime')
        # 这里可以写ignore_fields来忽略搜索那个字段

5、编辑视图

class ArticleSearchViewSet(HaystackViewSet):
    """
    Article搜索
    """
    index_models = [Article]
    serializer_class = ArticleIndexSerializer

6、别忘了编辑路由

router.register('articles/search', views.ArticleSearchViewSet, base_name='articles_search')

参考了:https://blog.csdn.net/smartwu_sir/article/details/80209907

原文地址:https://www.cnblogs.com/kopok/p/14999533.html