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