Jacobian Jacobian - 6 months ago 533
Python Question

How to delete documents from Elasticsearch

I can't find any example of deleting documents from

Elasticsearch
in Python. Whay I've seen by now - is definition of
delete
and
delete_by_query
functions. But for some reason documentation does not provide even a microscopic example of using these functions. The single list of parameters does not tell me too much, if I do not know how to correctly feed them into the function call. So, lets say, I've just inserted one new doc like so:

doc = {'name':'Jacobian'}
db.index(index="reestr",doc_type="some_type",body=doc)


Who in the world knows how can I now delete this document using
delete
and
delete_by_query
?

Answer

Since you are not giving a document id while indexing your document, you have to get the auto-generated document id from the return value and delete according to the id. Or you can define the id yourself, try the following:

 db.index(index="reestr",doc_type="some_type",id=1919, body=doc)

 db.delete(index="reestr",doc_type="some_type",id=1919)

In the other case, you need to look into return value;

 r = db.index(index="reestr",doc_type="some_type", body=doc)
 # r = {u'_type': u'some_type', u'_id': u'AU36zuFq-fzpr_HkJSkT', u'created': True, u'_version': 1, u'_index': u'reestr'}

 db.delete(index="reestr",doc_type="some_type",id=r['_id'])

Another example for delete_by_query. Let's say after adding several documents with name='Jacobian', run the following to delete all documents with name='Jacobian':

 db.delete_by_query(index='reestr',doc_type='some_type', q={'name': 'Jacobian'})