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.x Django 4.2 Django 3.2 Elasticsearch Django Elasticsearch DSL
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.