djangoelasticsearchdjango-rest-frameworkelasticsearch-dslelasticsearch-dsl-py

Search Nested Fields on Elasticsearch DSL DRF


This is 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

This is 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 is working. When I want to search on NestedField, search_nested_fields is not working. I'm getting errors like this. This is coming from 'topics': ['description'] in search_nested_fields.

error



Indexing is working. I want to search chapter by topic description. Maybe I'm using the wrong format in the search_nested_fields. I followed elasticsearch-dsl-drf documentation. But getting this error!


Solution

  • According to the elasticsearch-dsl-drf documentation, the new way to declare search_nested_fields is like this :

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