Aminenima
Aminenima

Reputation: 43

PYTHON - Delete items from a collection in Azure Cosmos DB

I'm new at developping with Azure. I hope you can help with this code. My gol is to delete the items from a collection in Azure Cosmos DB. but I get http error : 400 if I use this value 'partionKey' = '/Structures' and 404 if the value is ''. The Error Message = "The partition key supplied in x-ms-partitionkey header has fewer components than defined in the the collection"

client = cosmos_client.CosmosClient("https://....documents.azure.com:443/", {'masterKey': '...'})

options = {}

options['enableCrossPartitionQuery'] = True
options['maxItemCount'] = 5
options['partitionKey'] = '/Structures'

client.DeleteItem("dbs/.../colls/.../docs/.../", options)

Upvotes: 3

Views: 6641

Answers (2)


import datetime as datetime

import pandas as pd

import json

import os


URL = 'https://resouceName.documents.azure.com:443/'
KEY = 'YourKey'
DATABASE_NAME = 'resourceName'
CONTAINER_NAME = 'ContainerName'

client = CosmosClient(URL, credential=KEY)
database = client.get_database_client(DATABASE_NAME)
container = database.get_container_client(CONTAINER_NAME)

items = container.query_items(
        query=f'SELECT * FROM {CONTAINER_NAME} c ',
        enable_cross_partition_query=True)
      
documents = []
for i in items:
    delete = container.delete_item(i["id"],i["partitionKey"]) ```

#The parameter above for delete_item should be your Id and PartitonKey which runs in a loop and all the records will be deleted

Upvotes: 0

Jay Gong
Jay Gong

Reputation: 23782

The error is cause by this line:

options['partitionKey'] = '/Structures'

You need to specify the specific value of partition key here, not the column name.For example,my partition key is '/name',and the specific value in this document is 'A'.

enter image description here

Then your code looks like :

from azure.cosmos import cosmos_client

client = cosmos_client.CosmosClient("https://***.documents.azure.com:443/", {'masterKey': '***'})

options = {}

options['enableCrossPartitionQuery'] = True
options['maxItemCount'] = 5
options['partitionKey'] = 'A'

client.DeleteItem("dbs/db/colls/coll/docs/2", options)

Upvotes: 6

Related Questions