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