How to create a container with the specific parameters in Azure cosmosdb

139 Views Asked by At

I am trying to create a container in my testdatabase (Azure cosomosdb) with the following parameters. using python.However i am get the below error and failing to create the container. Would you please help to correct me if i am doing something wrong.

location_container_name = "locations"
try:
    container = database.create_container(
        id=location_container_name, partition_key=PartitionKey(path=["/state", "/city", "/zipcode"], kind="MultiHash")
    )
except exceptions.CosmosResourceExistsError:
    container = database.get_container_client(container_name)

Error details:-

azure.cosmos.exceptions.CosmosHttpResponseError: (BadRequest) The specified document collection is invalid.
ActivityId: b0e78b5f-abe8-479e-9005-606370644a78, Microsoft.Azure.Documents.Common/2.14.0
Code: BadRequest
Message: The specified document collection is invalid.
ActivityId: b0e78b5f-abe8-479e-9005-606370644a78, Microsoft.Azure.Documents.Common/2.14.0

expecting the output as below:-

I need the container with the name "locations" and with the path as below.

id      /state    /city    /zipcode

item1   WA      Redmond    98052
1

There are 1 best solutions below

0
On

By using the below code I have created a database and a container within it. Also, I have added an item in the container as well.

In your code partition key is not in string format and also used MultiHash. As mentioned in this MS_DOC, partition key is specified in string format in the below code partition_key_path = "/state/city/zipcode" and given kind as Hash.

Using below code an Item inserted successfully into the container:

from azure.cosmos import exceptions, CosmosClient, PartitionKey

endpoint = "*****"
key = "*****"
client = CosmosClient(endpoint, key)
database_name = "FirstDb"
database = client.get_database_client(database_name)

location_container_name = "locations"

partition_key_path = "/state/city/zipcode"

try:
    container = database.create_container(
        id=location_container_name,
        partition_key=PartitionKey(path=partition_key_path, kind="Hash")
    )
except exceptions.CosmosResourceExistsError:
    container = database.get_container_client(location_container_name)

item1 = {
    "id": "item1",
    "state": "AP",
    "city": "Hyderabad",
    "zipcode": "500032"
}

container.upsert_item(item1)

print(f"Container '{location_container_name}' created.")
print(f"Sample item inserted: {item1}")

Output:

Container 'locations' created.
Sample item inserted: {'id': 'item1', 'state': 'AP', 'city': 'Hyderabad', 'zipcode': '500032'}

enter image description here