Friday 24 July 2020

Deleting Documents from Azure CosmosDB using Python

I had a hell of a time trying to delete documents from an Azure Cosmos DB using the Azure Cosmos library in PyPI today. Thought I'd write down what I did to get it working.

The problem occured because the database in question doesn't any partitions defined. Although I could successfully query the database and get the document, I couldn't delete it. The fix was to specify NonePartionKeyValue as the partitiion key argument to delete_item() . I didn't find any documentation on this, and clearly it's a bit of a hack, but it worked!

So here's what worked:

from azure.cosmos.partition_key import NonePartitionKeyValue
from azure.cosmos import exceptions, CosmosClient, PartitionKey
import config #my stuff

guid = #the id of the document I'm trying to delete
db_name = #the id of the database
db_coll = #the name of the database collection

url = config.COSMOS_URL
key = config.COSMOS_KEY
client = CosmosClient(url, credential=key)

database = client.get_database_client(db_name)

container = database.get_container_client(db_coll)

for item in container.query_items(query='select * from o where o.id = \''+ guid + '\'', enable_cross_partition_query=True):
    container.delete_item(item, NonePartitionKeyValue)

1 comment: