首页 > 解决方案 > 如何在 Django 中的模型和相关模型中进行弹性搜索

问题描述

我正在使用在端口号django_elasticsearch_dsl上运行的,我有两个模型。9200

模型.py

class Category(models.Model):
        name = models.CharField(max_length=255, blank=True, null=True)

class Book(models.Model):
        name = models.CharField(max_length=255, blank=True, null=True)
        categories = models.ManyToManyField('Category')

文件.py

@posts.doc_type
class PostDocument(DocType):

    class Meta:
        model = Book
        fields = [
            'id',
            'name'
        ]
        related_models = [Category]

        def get_instances_from_related(self, related_instance):
            """If related_models is set, define how to retrieve the book instance(s) from the related model."""
            if isinstance(related_instance, Category):
                return related_instance.book_set.all()

搜索.py

from elasticsearch_dsl.query import Q
p = Q("multi_match", query=request.GET.get('q'), fields=['name','categories__name'],
                  type='phrase_prefix')
s = PostDocument.search().query(p)
result = s.execute()

此搜索代码仅适用于书籍模型,我无法使用相关类别模型检索

我需要的输出应该就像我有两本书,比如junglecuop 丛林书链接到 Category模型(类别名称是sport

所以如果搜索?q=ju输出应该只显示jungle(使用上面的代码)并且如果搜索 ?q=sport输出应该只显示jungle不起作用(它没有给出任何结果)

标签: pythondjangoelasticsearchelasticsearch-dsl

解决方案


推荐阅读