Django项目之elasticsearch的使用方法

elasticsearch在django中使用

1. settings.py 配置文件

  • 在django框架中,使用haystack对接Elasticsearch
    我们首先主要安装django-haystack 到我们的python环境中
pip3 install django-haystack
pip3 install elasticsearch
  • django-haystack是专门给 django 提供搜索功能的。 django-haystack提供了一个统一的API搜索接口,底层可以根据自己需求更换搜索引擎( Solr, Elasticsearch, Whoosh, Xapian 等等),类似于 django 中的 ORM 插件,提供了一个操作数据库接口,但是底层具体使用哪个数据库是可以在配置文件中进行设置的。

  • 在django中可以通过使用haystack来调用Elasticsearch搜索引擎。而在drf框架中,也有一个对应的drf-haystack模块,是django-haystack进行封装处理的。

  • settings.py

# 注册apps
INSTALLED_APPS = [
    'haystack',
]
# Haystack
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        # elasticsearch运行的服务器ip地址,端口号默认为9200
        'URL': 'http://192.168.252.168:9200/', # 配置 IP:port
        # elasticsearch建立的索引库的名称,一般使用项目名作为索引库
        'INDEX_NAME': 'object_name',
    },
}
# 设置在Django运行时,如果有数据产生变化(添加、修改、删除),
# haystack会自动让Elasticsearch实时生成新数据的索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

2. indexes_search.py创建索引模型类

  • 创建索引模型类,在对应的app下创建索引文件indexes_search.py(注:必须是这个名字,否则无法索引)
from haystack import indexes
from .models import Article

class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
    """
    文章索引数据模型类
    """
    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')

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

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

在ArticleIndex建立的字段,都可以借助haystack由elasticsearch搜索引擎查询。

其中text字段我们声明为document=True,表名该字段是主要进行关键字查询的字段, 该字段的索引值可以由多个数据库模型类字段组成,具体由哪些模型类字段组成,我们用use_template=True表示后续通过模板来指明。其他字段都是通过model_attr选项指明引用数据库模型类的特定字段。

在REST framework中,索引类的字段会作为查询结果返回数据的来源。

  • 在templates目录中创建text字段使用的模板文件
    配置settings.py
# 模板引擎
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, "templates"),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

templates/search/indexes/article/article_text.txt文件中新建article_text.txt文本文件

{{ object.title }}
{{ object.content }}
{{ object.id }}

作用:此模板指明当将关键词通过text参数名传递时,可以通过article的title、content、id来进行关键字索引查询。
手动重建索引

python manage.py rebuild_index

3. django视图类、序列化器、路由等配置

  • 创建序列化器serializers.py
from drf_haystack.serializers import HaystackSerializer

class ArticleIndexSerializer(HaystackSerializer):
    """
    文章索引结果数据序列化器
    """
    class Meta:
        index_classes = [ArticleIndex]
        fields = ('text', 'id', 'title', 'content')
  • 创建视图类views.py
from drf_haystack.viewsets import HaystackViewSet

class ArticleSearchViewSet(HaystackViewSet):
    """
    文章搜索
    """
    index_models = [Article]

    serializer_class = ArticleIndexSerializer
    pagination_class = ArticleSearchPageNumberPagination
  • 创建路由url.py
from django.urls import path,re_path
from . import views
# 。。。。

from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('search', views.ArticleSearchViewSet, base_name='article_search')
router.register("", views.ArticleAPIView)
urlpatterns += router.urls
  • 创建分页器paginations.py
from rest_framework.pagination import PageNumberPagination
class ArticleSearchPageNumberPagination(PageNumberPagination):
    """文章搜索分页器"""
    page_size = 2
    max_page_size = 20
    page_size_query_param = "size"
    page_query_param = "page"

完成以上配置,通过postman测试接口

  • 1
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值