Indexing Documents¶
The StretchIndex
class connects a Django model and an Elasticsearch index. Together with the management commands you
Creating an Index¶
The minimum settings for an index are at least one field and to specify which model it is associated with.
from stretch.indices import StretchIndex
from elasticsearch_dsl import Text
from yourapp.models import Foo
class FooIndex(StretchIndex):
"""
Index the Foo model in Elasticsearch
"""
name = Text(source='name')
class Meta:
model = Foo
Tracking Updates¶
Stretch uses signal handlers to update Elasticsearch documents when a model instance is saved or deleted. There are no signal handlers set up by default, but adding one is really easy.
There are two signal handlers available by default in Stretch: the RealtimeSignalHandler
which will update your documents synchronously in Elasticsearch and CelerySignalHandler
which will asynchronously update the documents (you must install and configure celery separately).
Warning
Queryset update
methods do not trigger the save signal and will not be tracked by default.
...
from stretch.signals import RealtimeSignalHandler
class FooIndex(StretchIndex):
...
class Meta:
...
signal_handler = RealtimeSignalHandler
Fields¶
Stretch uses the field classes from Elasticsearch DSL library and accepts all the same arguments, with the addition of the source
keyword. The source
keyword should be either a model attribute or a method on the StretchIndex
class which is used to populate the Elasticsearch field from the model.
from elasticsearch_dsl import Text
class FooIndex(StretchIndex):
name = String(source='name')
custom_field = String(source='get_custom_value')
def get_custom_value(self, obj):
return obj.first_name + obj.last_name