Search code examples
pythonfor-loopindexingprompt

How to produce one long list of indices


I have written a Python script that deletes indices on ElasticSearch.

I have added a section to list the specific indices that will be deleted (doc count 0 and index name can't start with ".") I added a user prompt to approve the list before deletion begins.

However the output of this is not user friendly:

Indices to be deleted:
test-index-000001
Do you want to proceed with the deletion of these indices? (y/n): y
Indices to be deleted:
test-index-000001   
test-index-000002   
Do you want to proceed with the deletion of these indices? (y/n): y
Indices to be deleted:
test-index-000001
test-index-000002
test-index-000003

I want the output to be:

Indices to be deleted:
  test-index-000001
  test-index-000002
  test-index-000003
Do you want to proceed with the deletion of these indices? (y/n): y

Here is my code for this section:

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'])
        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

I have tried moving the prompt outside the loop, but then it keeps repeating the question over and over again without progressing to the rest of the code. Can you help me please?


Solution

  • Move everything except the code to fill indices_to_delete outside of your loop.

    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'])
       
    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.")
    else DeletionCode()
    

    This fills your array with all items you want to delete, then prints them all and asks 1 time if you want to proceed.