About Nested Levels at Elasticsearch Index

You can create structures with multiple levels in Elasticsearch indexes. Here is an example of Django Elasticsearch DSL document combining NestedField (for lists) and ObjectField (for single-object relations) for nested structures:

books/documents.py

from django.conf import settings
from django_elasticsearch_dsl.registries import registry
from django_elasticsearch_dsl import Document, fields
from .models import Book

@registry.register_document
class BookDocument(Document):
    authors = fields.NestedField(
        properties={
            "uuid": fields.KeywordField(),
            "first_name": fields.TextField(),
            "last_name": fields.TextField(),
            "photo": fields.ObjectField(
                properties={
                    "image_url": fields.TextField(),
                    "copyright": fields.TextField(),
                }
            ),
        }
    )

    class Index:
        name = f"{settings.PROJECT_NAME}_{settings.ENVIRONMENT}_books"
        settings = {
            "number_of_shards": 1,
            "number_of_replicas": 0,
        }

    class Django:
        model = Book

        fields = ["uuid", "title"]

        ignore_signals = False
        auto_refresh = True
        queryset_pagination = 5000

    def prepare_authors(self, instance):
        return [{
            "uuid": author.uuid,
            "first_name": author.first_name,
            "last_name": author.last_name,
            "photo": {
                "image_url": author.photo.image.url,
                "copyright": author.photo.copyright,
            }
        } for author in instance.authors.all()]

Tips and Tricks Programming Development Django 5.2 Django 4.2 Django 3.2 Elasticsearch Django Elasticsearch DSL

Django/Python Consulting

If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.