Django Elasticsearch DSL

9.0 · active · verified Wed Apr 15

django-elasticsearch-dsl is a Django application that wraps elasticsearch-dsl-py to provide an easy way to integrate Elasticsearch with Django models. It simplifies document definition, index management, and provides signal processors for automatic indexing of model changes. The current version is 9.0, and the project maintains an active release cadence with regular updates and support for new Django and Elasticsearch versions.

Warnings

Install

Imports

Quickstart

To get started, define your Elasticsearch settings in `settings.py`. Create a `Document` subclass for your Django model, register it with the `registry`, and define its fields using `elasticsearch_dsl.fields`. You can then rebuild your Elasticsearch index using the `search_index` management command and perform searches through the `Document`'s `.search()` method. Remember to configure a signal processor for real-time indexing.

import os

# models.py (example_app)
from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    published = models.BooleanField(default=False)

    def __str__(self):
        return self.title

# documents.py (example_app)
from django_elasticsearch_dsl import Document, Index
from django_elasticsearch_dsl.registries import registry
from elasticsearch_dsl import fields

from .models import Article

# Define a custom index
article_index = Index('articles')
article_index.settings(number_of_shards=1, number_of_replicas=0)

@registry.register_document
@article_index.document
class ArticleDocument(Document):
    id = fields.IntegerField(attr='id')
    title = fields.TextField(
        analyzer='english',
        fields={'raw': fields.KeywordField()}
    )
    body = fields.TextField(
        analyzer='english',
        fields={'raw': fields.KeywordField()}
    )
    published = fields.BooleanField()

    class Django:
        model = Article
        fields = ['title', 'body', 'published']

# In settings.py:
# ELASTICSEARCH_DSL = {
#     'default': {
#         'hosts': os.environ.get('ES_HOST', 'localhost:9200'),
#         'timeout': 60
#     }
# }
# ELASTICSEARCH_DSL_SIGNAL_PROCESSOR = 'django_elasticsearch_dsl.signals.RealTimeSignalProcessor'

# To rebuild index:
# python manage.py search_index --rebuild

# Example search query:
# from example_app.documents import ArticleDocument
# s = ArticleDocument.search().query('match', title='test article')
# response = s.execute()
# for hit in response:
#     print(hit.title)

view raw JSON →