如何在Python中生成完整待删Elasticsearch索引列表并单次询问确认
优化Elasticsearch空索引删除脚本:单次确认批量删除
修改后的完整脚本
content = json.loads(getRequestElasticSearch.text) indices_to_delete = [] # 先批量收集所有符合条件的待删除索引 for index in content: if int(index['docs.count']) == 0 and not index['index'].startswith("."): indices_to_delete.append(index['index']) # 统一处理用户确认与删除逻辑 if not indices_to_delete: print("没有符合条件的待删除索引。") else: print("待删除索引列表:") for idx in indices_to_delete: print(idx) proceed = input("是否确认删除以上索引?(y/n): ") if proceed.lower() == "y": # 此处添加实际的Elasticsearch索引删除代码 # 示例(需根据你的ES客户端调整): # from elasticsearch import Elasticsearch # es = Elasticsearch(...) # for idx in indices_to_delete: # es.indices.delete(index=idx) print("索引删除操作已执行完成。") else: print("用户已终止删除操作。")
核心改动说明
- 拆分逻辑:把索引筛选收集和用户交互确认完全分离,循环仅负责筛选符合条件的索引,不触发任何交互
- 空列表判断:如果没有找到待删索引,直接给出提示,避免无意义的确认步骤
- 单次交互:仅在收集完所有待删索引后,统一展示列表并发起一次确认请求,彻底解决多次询问的问题
- 预留删除逻辑:在确认通过的分支中预留了删除代码的位置,你可以直接对接自己的Elasticsearch客户端实现
内容的提问来源于stack exchange,提问作者JonH
相关产品推荐
相关产品推荐

