Search code examples
pythonazure-cosmosdb

Unable to retrieve the item from cosmos db container


It is not able to retrieve the item from container using item_id and partition_key.

Here is code snippet

from azure.cosmos import CosmosClient, PartitionKey

cosmos_client = CosmosClient(url=cosmos_endpoint, credential=cosmos_key)
database = cosmos_client.create_database_if_not_exists(id="database")
container = database.create_container_if_not_exists(id="container", partition_key=PartitionKey(path="/partition"))

container.create_item(body={"id": "id-1"})
container.read_item(item="id-1", partition_key="/partition")

response from api:

 ResourceType: Collection, OperationType: Read
, SDK: Microsoft.Azure.Documents.Common/2.14.0
Code: NotFound
Message: Message: {"Errors":["Resource Not Found. Learn more: https:\/\/aka.ms\/cosmosdb-tsg-not-found"]}

I tried with different values for partition_key, for instance,

container.read_item(item="id-1", partition_key=PartitionKey(path="/partition"))

which gave error of bad request.

container.read_item(item="id-1", partition_key="id-1")

which is not able retrieve the item.

Here is information I gathered for container from database client:

>>>database.list_containers().next()
{'_conflicts': 'conflicts/',
 '_docs': 'docs/',
 '_etag': '"0000fb09-0000-0c00-0000-647453610000"',
 '_rid': 'zOBqAK0Az6I=',
 '_self': 'dbs/zOBqAA==/colls/zOBqAK0Az6I=/',
 '_sprocs': 'sprocs/',
 '_triggers': 'triggers/',
 '_ts': 1685345121,
 '_udfs': 'udfs/',
 'conflictResolutionPolicy': {'conflictResolutionPath': '/_ts',
                              'conflictResolutionProcedure': '',
                              'mode': 'LastWriterWins'},
 'geospatialConfig': {'type': 'Geography'},
 'id': 'container',
 'indexingPolicy': {'automatic': True,
                    'excludedPaths': [{'path': '/"_etag"/?'}],
                    'includedPaths': [{'path': '/*'}],
                    'indexingMode': 'consistent'},
 'partitionKey': {'kind': 'Hash', 'paths': ['/partition'], 'version': 2}}

Solution

  • It seems you are not explicitly setting the partition key value when you are creating the document. If that happens, Cosmos DB automatically puts the documents in a special partition.

    Because point read queries require both document id and partition key, when reading such documents you would need to specify partition key as an empty javascript object ({}).

    Please try something like:

    container.read_item(item="id-1", partition_key={})
    

    Generally speaking, you must explicitly set the partition key value in creating the document. For example, if you had done something like:

    container.create_item(body={"id": "id-1", "partition": "id-1"})
    

    You could have read the same document using your code:

    container.read_item(item="id-1", partition_key="id-1")