在 Elasticsearch DSL DRF 上搜索嵌套字段

Search Nested Fields on Elasticsearch DSL DRF

这是document.py

@chapter_index.doc_type
class ChapterDocument(Document):
    subject = fields.ObjectField(properties={
        'name': fields.TextField(),
        'description': fields.TextField()
    })
    
    topics = fields.NestedField(properties={
        'name': fields.TextField(),
        'description': fields.TextField(analyzer=html_strip),
        'duration': fields.IntegerField()
    })

    class Django:
        model = Chapter
        fields = [
            'name',
            'description',
            'order_no'
        ]
        related_models = [Subject, Topic]

    def get_queryset(self):
        return super(ChapterDocument, self).get_queryset().select_related(
            'subject'
        )

    def get_instances_from_related(self, related_instance):
        if isinstance(related_instance, Subject):
            return related_instance.chapters.all()
        if isinstance(related_instance, Topic):
            return related_instance.chapter

这是 DocumentViewSet

class ChapterSearchViewSet(DocumentViewSet):
    document = ChapterDocument
    serializer_class = ChapterDocumentSerializer

    filter_backends = [
        SearchFilterBackend,
    ]

    search_fields = (
        'subject.name',
        'subject.description',
        'name',
        'description',
    )

    search_nested_fields = {
        'topics': ['description']
    }

search_fields 正在工作。当我想在 NestedField 上搜索时,search_nested_fields 不起作用。我收到这样的错误。这来自 'topics':search_nested_fields 中的 ['description']。



索引正在工作。我想按主题描述搜索章节。也许我在 search_nested_fields 中使用了错误的格式。我遵循了 elasticsearch-dsl-drf 文档。但是出现这个错误!

根据elasticsearch-dsl-drf documentation,声明search_nested_fields的新方法是这样的:

search_nested_fields = {
    'topics': {
        'path': 'topics',
        'fields': ['description'],
    }
}