如何在 Python 中创建不存在的 ElasticSearch 索引
以下实用程序将通过忽略任何 resource_already_exists_exception 在索引不存在时创建它
es_create_index_if_not_exists.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
# 示例用法:创建 "nodes" 索引
es_create_index_if_not_exists(es, "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