How to handle try catch exception when creating an index with python elasticsearch?

Viewed 2632

I try to print an error if the index is already exist. I use python with Elasticsearch.

import time,schedule
import requests
from elasticsearch import Elasticsearch 
import sys
import logging
import json
from datetime import datetime

es = elasticsearch.Elasticsearch('http:/ip:port',timeout=600)
settings = { "settings": {
                 "number_of_shards":1,
                  'number_of_replicas':0
                 },
      "mappings" : { 
           "document" : {
                "properties":{
                    "geo": {
                       "type": "geo_point"
                            }
                          }
                        } 
                     } 
                  }
try:
 es.indices.create(index = "spacestation", body=settings)
except Elasticsearch.ElasticsearchException as es1:
 print('Index already exists!!')

But I got following error:

elasticsearch.exceptions.RequestError: RequestError(400, 'resource_already_exists_exception', 'index [spacestation/IlVCpABTSYmWVDVrGmTRMA] already exists')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "__main__.py", line 42, in <module>
except Elasticsearch.ElasticsearchException as es1:
AttributeError: type object 'Elasticsearch' has no attribute 'ElasticsearchException'

I don't get this error, whether my code is correct or not. I think this is not correct code to print error if already exist the index. Please some one can correct me? Thanks

1 Answers

Simply change your code to this:

from elasticsearch import Elasticsearch, RequestError
...


try:
  es.indices.create(index = "spacestation", body=settings)
except RequestError as es1:
  print('Index already exists!!')
  sys.exit(1)
Related