Skip to content

Instantly share code, notes, and snippets.

@tmarki
Created May 15, 2024 22:21
Show Gist options
  • Save tmarki/e5cc602713c3379b2f45aad1cf848fcd to your computer and use it in GitHub Desktop.
Save tmarki/e5cc602713c3379b2f45aad1cf848fcd to your computer and use it in GitHub Desktop.
Bulk delete items from a CosmosDB container by query (cross partition key)
from azure.cosmos import CosmosClient
url = "YOUR_DB_URL"
key = "YOUR_DB_KEY"
database = "YOUR_DB_NAME"
container = "YOUR_CONTAINER"
query = input("Please input the query:")
# For example:
# SELECT * FROM c WHERE c.Data.Time>"2024-05-15"
if not query.startswith("SELECT"):
print("Query must start with SELECT")
exit()
client = CosmosClient(url, key)
db = client.get_database_client(database=database)
container = db.get_container_client(container=container)
items = container.query_items(
query=query,
enable_cross_partition_query=True)
toDelete = []
cnt = 0
for i in items:
cnt += 1
toDelete.append(i)
z = input(f"Delete {cnt} items (y = yes)?")
if z != 'y':
print("Aborted")
exit()
for i in toDelete:
container.delete_item(item=i['id'], partition_key=i['partitionKey'])
print("Done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment