Elasticsearch : How to delete an Index using python

PythonPython 2.7Elasticsearch

Python Problem Overview


Forgive me if this is quite basic but I have Python 2.7 and Elasticsearch 2.1.1 and I am just trying to delete an index using

es.delete(index='researchtest', doc_type='test')

but this gives me

return func(*args, params=params, **kwargs)
TypeError: delete() takes at least 4 arguments (4 given)

I also tried

es.delete_by_query(index='researchtest', doc_type='test',body='{"query":{"match_all":{}}}')

but I get

AttributeError: 'Elasticsearch' object has no attribute 'delete_by_query'

Any idea why? Has the api changed for 2.1.1 for python?

https://elasticsearch-py.readthedocs.org/en/master/api.html#elasticsearch.client.IndicesClient.delete

Python Solutions


Solution 1 - Python

For ES 8+ use:

from elasticsearch import Elasticsearch
es = Elasticsearch()

es.options(ignore_status=[400,404]).indices.delete(index='test-index')

For older versions use this notation:

from elasticsearch import Elasticsearch
es = Elasticsearch()

es.indices.delete(index='test-index', ignore=[400, 404])

Solution 2 - Python

If you have a document object (model) and you're using elasticsearch-dsl, specially with Python-3.X you can directly call the delete method of your model's _index attribute.

ClassName._index.delete()

Also as it's stated in documentation:

>The _index attribute is also home to the load_mappings method which will update the mapping on the Index from elasticsearch. This is very useful if you use dynamic mappings and want the class to be aware of those fields (for example if you wish the Date fields to be properly (de)serialized): > > Post._index.load_mappings()

Solution 3 - Python

Since passing transport options in the API method is deprecated in the Elasticsearch python client 8+, the way to specify HTTP status codes that should be ignored (e.g. to prevent errors in case the target index does not exist) would be by using Elasticsearch.options() now:

from elasticsearch import Elasticsearch
es = Elasticsearch()

es.options(ignore_status=[400,404]).indices.delete(index='test-index')

(see documentation).

Solution 4 - Python

If you're using elasticsearch-dsl, use

from elasticsearch_dsl import Index

index = Index('test-index')
index.delete(ignore=[400, 404])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbtPstView Question on Stackoverflow
Solution 1 - PythonferdyView Answer on Stackoverflow
Solution 2 - PythonMazdakView Answer on Stackoverflow
Solution 3 - PythonbuddematView Answer on Stackoverflow
Solution 4 - PythonNokadosView Answer on Stackoverflow