[使用python elasticsearch创建索引时如何处理try catch异常?

问题描述 投票:0回答:1

如果索引已经存在,我尝试打印错误。我将python与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!!')

但是我收到以下错误:

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'

无论我的代码是否正确,我都不会收到此错误。我认为如果索引已经存在,这不是打印错误的正确代码。请有人可以纠正我吗?谢谢

python elasticsearch exception try-catch
1个回答
0
投票

简单替换

Elasticsearch.ElasticsearchException

作者

elasticsearch.exceptions.RequestError

在您的except子句中

© www.soinside.com 2019 - 2024. All rights reserved.