Skip to content

Instantly share code, notes, and snippets.

@harshvb7
Created July 10, 2019 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harshvb7/8856a12bbd20dc0b41751fd32ac7a04d to your computer and use it in GitHub Desktop.
Save harshvb7/8856a12bbd20dc0b41751fd32ac7a04d to your computer and use it in GitHub Desktop.
"""
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