Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"""
Assume the structure of the document looks like this
{
"user": {
"first_name": "Foo",
"last_name": "Bar",
"age": "30",
"city": {
"id": 5,
"name": "Cologne",
"slug": "cologne",
"country": {
"id": 1,
"name": "Germany",
"slug": "germany"
}
}
},
"tweet": "Some awesome tweet",
"created_at": "2019-10-07 12:00"
... and some more data
}
What if the user changed his age and the city he lives in.
So we will update only the user node in the structure with the User model instance
and we don't need the rest of the model instances.
The resulting sub-json structure with new data should look like
{
"user": {
"age": "31",
"city": {
"id": 6,
"name": "Hamburg",
"slug": "hamburg",
}
}
}
"""
from elasticsearch_dsl.connections import connections
# How a simple function would look like
def update_current_document(id, instance, fields_changed=[]):
"""
Arguments:
id: {integer} -- id of the document. Ideally should be the id of the root object in the document
instance {Model instance} -- The updated user model object
fields_changed {list} -- list of the model fields changed
"""
sub_data = generate_sub_dictionary(instance, fields_changed)
client = connections.create_connection()
client.update(index='tweets', doc_type='doc', id=id, body={'doc': sub_data})
def generate_sub_dictionary(instance, fields_changed=[]):
"""
This method assumes you have the structure of the Elasticsearch document saved somewhere
as a dictionary and you are generating a sub dictionary with values using a recursive backtracking algorithm.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment