如何修复 Python 中的 elasticsearch.exceptions.RequestError: RequestError(400, resource_already_exists_exception)
问题:
你想在 Python 中使用类似这样的代码创建 ElasticSearch 索引
es_create_index_example.py
es.indices.create("nodes") # 创建名为 "nodes" 的索引但你看到以下错误消息:
es_traceback.txt
Traceback (most recent call last):
File "estest.py", line 22, in <module>
es.indices.create("nodes")
File "/usr/local/lib/python3.8/dist-packages/elasticsearch/client/utils.py", line 168, in _wrapped
return func(*args, params=params, headers=headers, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/elasticsearch/client/indices.py", line 123, in create
return self.transport.perform_request(
File "/usr/local/lib/python3.8/dist-packages/elasticsearch/transport.py", line 415, in perform_request
raise e
File "/usr/local/lib/python3.8/dist-packages/elasticsearch/transport.py", line 381, in perform_request
status, headers_response, data = connection.perform_request(
File "/usr/local/lib/python3.8/dist-packages/elasticsearch/connection/http_urllib3.py", line 277, in perform_request
self._raise_error(response.status, raw_data)
File "/usr/local/lib/python3.8/dist-packages/elasticsearch/connection/base.py", line 330, in _raise_error
raise HTTP_EXCEPTIONS.get(status_code, TransportError)(
elasticsearch.exceptions.RequestError: RequestError(400, 'resource_already_exists_exception', 'index [nodes/mXAiBt0wTKK4Y31HpshVbw] already exists')解决方案
错误消息告诉你你尝试创建的索引已存在!
最简单的解决方案是使用我们关于如何在 Python 中创建不存在的 ElasticSearch 索引的文章中的代码:
es_create_index_helper.py
def es_create_index_if_not_exists(es, index):
"""创建给定的 ElasticSearch 索引,如果已存在则忽略错误"""
try:
es.indices.create(index)
except elasticsearch.exceptions.RequestError as ex:
if ex.error == 'resource_already_exists_exception':
pass # 索引已存在。忽略。
else: # 其他异常 - 抛出它
raise ex并使用该函数创建你的索引:
es_create_index_usage.py
es_create_index_if_not_exists(es, "nodes") # 创建 "nodes" 索引;如果已存在则不会失败Check out similar posts by category:
Databases, ElasticSearch, Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow