gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:16:39 26 4
gpt4 key购买 nike

如果索引已经存在,我会尝试打印错误。我在 Elasticsearch 中使用 python。

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com