如何优化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("No indices meet the deletion criteria.") return # 一次性展示所有待删索引并发起确认 print("Indices to be deleted:") for idx in indices_to_delete: print(idx) proceed = input("Do you want to proceed with the deletion of these indices? (y/n): ") if proceed.lower() != "y": print("Deletion aborted by user.") return # 在这里添加你的ES索引删除逻辑,示例: # for idx in indices_to_delete: # call_es_delete_api(idx) print("Deletion completed successfully.")
关键修改说明:
- 彻底拆分索引收集与交互确认:循环仅负责筛选并添加符合条件的索引,不执行任何打印或询问操作
- 增加空列表判断:如果没有符合条件的索引,直接提示并退出,避免无意义的交互
- 确认逻辑仅执行一次:所有索引收集完成后统一展示,再发起一次确认请求,完全解决重复打印和提问的问题
你之前把确认移到循环外出现问题,大概率是没处理空列表的情况,或是删除逻辑的位置不合理。按照上述结构,先收集、再判断、再确认、最后执行删除,逻辑会清晰很多。
内容的提问来源于stack exchange,提问作者JonH
相关产品推荐
相关产品推荐

