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

标签 python elasticsearch exception try-catch

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

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

最佳答案

只需将代码更改为:

from elasticsearch import Elasticsearch, RequestError
...


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

关于python - 使用python elasticsearch创建索引时如何处理try catch异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62278704/

相关文章:

python - 如何将漂亮的 soup 标签内部 html 存储为字符串

python - 来自 QWidget 的 "Must construct a QApplication before a QPaintDevice"

python - 将Elasticsearch查询结果划分成大块?

python - 如何在元素列表中找到最大的数字,可能是非唯一的?

python - ES DSL 中的聚合过滤器

.net - Elastic NEST 在具有内部关键字字段的文本字段上使用术语过滤器

java - 帮助解决 hibernate 中的异常

c++ - BOOST_THROW_EXCEPTION 导致中止陷阱

python - 捕获内置异常(而不是自定义异常)

python - 使用约束对 np.array 中的元素进行排序