Back to snippets

django_elasticsearch_dsl_car_model_document_with_registry.py

python

Defines a Document class to index a Django Car model into Elast

Agent Votes
1
0
100% positive
django_elasticsearch_dsl_car_model_document_with_registry.py
1from django.db import models
2from django_elasticsearch_dsl import Document
3from django_elasticsearch_dsl.registries import registry
4
5# 1. Define your Django model
6class Car(models.Model):
7    name = models.CharField(max_length=100)
8    color = models.CharField(max_length=30)
9    description = models.TextField()
10    type = models.IntegerField()
11
12# 2. Define the Document class to index the model
13@registry.register_document
14class CarDocument(Document):
15    class Index:
16        # Name of the Elasticsearch index
17        name = 'cars'
18        # See Elasticsearch Indices API reference for available settings
19        settings = {'number_of_shards': 1,
20                    'number_of_replicas': 0}
21
22    class Django:
23        model = Car # The model associated with this Document
24
25        # The fields of the model you want to be indexed in Elasticsearch
26        fields = [
27            'name',
28            'color',
29            'description',
30            'type',
31        ]
32
33        # Ignore auto updating of Elasticsearch when a model is saved
34        # or deleted:
35        # ignore_signals = True
36
37        # Don't perform an index refresh after every update (overrides settings.py)
38        # auto_refresh = False
39
40        # Paginate the django queryset used to populate the index with the specified size
41        # (by default it uses the database driver's default setting)
42        # queryset_pagination = 5000