如何在模型及相关模型中进行弹性搜索

2024-04-20 11:11:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是运行在9200端口号上的django_elasticsearch_dsl 我有两个模型。你知道吗

型号.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,这是不工作的(它没有给出任何结果)


Tags: instancenamefrompy模型truemodelmodels