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