Hi! Not sure this is the correct place but I was curious about how an ID gets set/created when saving a doc. I've been digging through the code but nothing jumps out at me. I was going in with the thought that perhaps elasticsearch-dsl-py created a hash of to_dict and used that when calling save?
class Package(DocType):
name = String()
class Meta:
doc_type = 'package'
pkg = Package()
pkg.name = 'foo'
pkg.save(index='bar) <--- no `id` defined
Hi @quasiben, if no id is supplied, by either passing in _id=VALUE or setting .meta.id on the pkg object, then we will rely on elasticsearch to create a random one (see [0]).
Ah, apologies!
@HonzaKral Can you explain how setting id works with regard to the model-like API? For example, how do I call save on a Document with an existing ID field, say my_id? Your link only explains how the REST API works.
@zhanwenchen I am not sure I understand the question properly so please let me know if the following doesn't answer your concerns.
If you have a Document instance that you either passed a value (via _id or setting .meta.id attribute) or retrieved from Elasticsearch (either via get or search) then that document object has an id and calling save() will cause the document to be updated.
You can also pass in the id while calling save(): my_doc.save(id="my_doc") which will cause the document to be stored under that id regardless of whether it had an id before or not.
If you create a document instance, do not set an id, and call .save() on it then a random id will be assigned by elasticsearch.
after calling .save() the current instance's metadata will be update to include the _id used by elasticsearch, regardless of which approach was used to set it (explicit, via save(), or assigned by elasticsearch).
Hope this helps!
Most helpful comment
@zhanwenchen I am not sure I understand the question properly so please let me know if the following doesn't answer your concerns.
If you have a
Documentinstance that you either passed a value (via_idor setting.meta.idattribute) or retrieved from Elasticsearch (either viagetorsearch) then that document object has anidand callingsave()will cause the document to be updated.You can also pass in the
idwhile callingsave():my_doc.save(id="my_doc")which will cause the document to be stored under that id regardless of whether it had an id before or not.If you create a document instance, do not set an id, and call
.save()on it then a random id will be assigned by elasticsearch.after calling
.save()the current instance's metadata will be update to include the_idused by elasticsearch, regardless of which approach was used to set it (explicit, via save(), or assigned by elasticsearch).Hope this helps!