0
votes

I am using .Net Core with Microsoft.Azure.DocumentDB.Core package from nuget while tried to retrieve item, I found the outdated documentation on how to read an item from cosmos db by including the PartitionKey with following method e,g:

public static async Task<T> GetItemAsync(string id, string category)
{
     await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id),new RequestOptions { PartitionKey = new PartitionKey(category) });
}

So what does the parameter category stand for? Should it represent the value of a specific item's partition key or should it just be a format for that collection items' partition key?

If my partition key is undefined, I've tried with using Undefined.Value as Partition Key option, but got exception as Partition key provided either doesn't correspond to definition in the collection or doesn't match partition key field values specified in the document.

new RequestOptions { PartitionKey = new PartitionKey(Undefined.Value) });

In addition, why would we need both value for id and partition key when retrieving a single item from collection? Why couldn't we just use id as it's unique key? If I don't know the partition key, can I still use the ReadDocumentAsync method to get my item?

1

1 Answers

0
votes

In Cosmos DB the id is not a unique value withing a partitioned collection. In fact you can have unlimited documents with the exact same id as long as the partition key value is different. This is because a document id is only unique within it's own partition.

What the category represents in the example is the partition key value that this document is expected to live in. You need the partition key value in partitioned collections in order to read documents. This is why Cosmos DB is so fast. If your partition key was also your id then the id would be unique within the collection since every document would be in different logical partitions.