Create and delete an elasticsearch index in Python

Last updated 4 months, 2 weeks ago | 274 views 75     5

Python | Create and delete an index in Elasticsearch

To use the elastic search we need to import the Elasticsearch package

>>> from elasticsearch import Elasticsearch

now create an object of Elasticsearch search class by providing HOST and PORT number, these parameters are essential to locate the instance where it is running

>>> es = Elasticsearch(HOST="http://localhost", PORT=9200)

and for local instance, there no need to proved HOST name and PORT number

>>> es = Elasticsearch()

Next, we create an empty index by using the indices.create function.

>>> es.indices.create(index="first_index", ignore=400)
{'acknowledged': True, 'shards_acknowledged': True, 'index': 'first_index'}

When we do that we get an acknowledgment from the ES that first_index is created with acknowledgment key True

To check ES has created use indices.exists function it will return True if it's created.

>>> es.indices.exists(index="first_index")

To delete an index use the indices.delete function. if the index deleted successfully It will return with the acknowledgment key True

>>> es.indices.delete(index="first_index")
{'acknowledged': True}

To check the index is deleted or not use the indices.exists function. this time its return False as it deleted

>>> es.indices.exists(index="first_index")