question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to read the Partitionkey of a container using Cosmosclient

See original GitHub issue

One of the partameters of CreateItemStreamAsync is the partionkey value in current message. How do we access the current container’s partition key?

I see ContainerPropeties has the PartitionKeyPath property, but Container class doesn’t have a Resource properlty https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.containerproperties?view=azure-dotnet

Container container = await client.GetDatabase("dbName").Containers.CreateAsync("MyCollection", "/country", 50000);
ContainerProperties containerProperties = container.Resource;

Issue Analytics

  • State:closed
  • Created 6 months ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
NaluTripiciancommented, Apr 10, 2023

Hello @praveenbarli hopefully the following will help you with your problem.

A when creating a Container for ComsosDB, you must specify at minimum two things. First is the id of the container. The second is the PartitionKeyPath. The PartitionKeyPathPath tells Cosmos where to look for the partition key value of every item you add into a Cosmos Container. This path can have any value also long as the items you add to Cosmos have that property.

For instance, let’s say you will be adding many of the following records to a Cosmos Database.

public record DatabaseItem(
            string id,
            string city, 
            string state,
            string zipcode
            );

When creating the Container that will be used to store these items you can that any of these values are the PartitionKeyPath. For example:

Container container = await db.CreateContainerAsync(
                id: "test",
                partitionKeyPath: "/city"
            );

or

Container container = await db.CreateContainerAsync(
                id: "test",
                partitionKeyPath: "/state"
            );

are both valid (but not the only) ways to create the Container.

Once a Container is created and we want to populate it with items we must make sure that the items have a property that matches the ParitionKeyPath we specified in the creation of the Container. Finding the ParitionKeyPath of a Container can be done like this: await container.ReadContainerAsync().PartitionKeyPath. When using the CreateItemStreamAsync method, we must specify two things. First is the stream containing the payload of the item we are creating, and second is the ParitionKey of that item.

Let’s look at the following example that details the creation of three items using the CreateItemStreamAsync method:

client = new CosmosClient(
                accountEndpoint: endpoint,
                authKeyOrResourceToken: key
            );

db = await client.CreateDatabaseIfNotExistsAsync(
                id: "testDB"
            );

container = await db.CreateContainerAsync(
                id: "test",
                partitionKeyPath: "/thisIsThePartitionKeyPath"
            );

using (ResponseMessage response = await container.CreateItemStreamAsync(
                               partitionKey: new PartitionKey("/TheParitionKey"),
                                              streamPayload: new MemoryStream(Encoding.UTF8.GetBytes("{\"id\":\"document1\",\"thisIsThePartitionKeyPath\":\"/TheParitionKey\"}"))
                                                         ))
{
            Console.WriteLine(response.StatusCode);
}

using (ResponseMessage response = await container.CreateItemStreamAsync(
                               partitionKey: new PartitionKey("/TheOtherParitionKey"),
                                              streamPayload: new MemoryStream(Encoding.UTF8.GetBytes("{\"id\":\"document2\",\"thisIsThePartitionKeyPath\":\"/TheOtherParitionKey\"}"))
                                                         ))
{
             Console.WriteLine(response.StatusCode);
}

using (ResponseMessage response = await container.CreateItemStreamAsync(
                               partitionKey: new PartitionKey("/TheOtherParitionKey"),
                                              streamPayload: new MemoryStream(Encoding.UTF8.GetBytes("{\"id\":\"document3\",\"thisIsThePartitionKeyPath\":\"/TheOtherParitionKey\"}"))
                                                         ))
{
             Console.WriteLine(response.StatusCode);
}

Here you can see the difference in what the PartitonKeyPath and PartitionKey is. In both cases the PartitionKeyPath stays the same, thisIsThePartitionKeyPath, while the values of the PartitionKey can change from item to item. However, as seen in the second and third items, they can have the same value. In summary, the PartitionKeyPath tells Cosmos where to find the value of the PartitionKey within an item and stays the same for each Container, while the PartitionKey is the actual value the items are partitioned on.

Please let me know if you have any further questions, if not feel free to close this issue.

0reactions
bartelinkcommented, Apr 14, 2023

You should not call .Result - always use await to hop from a Task<X> to an X (you can search up an article on these sorts of things with .net Result await deadlock)

Read more comments on GitHub >

github_iconTop Results From Across the Web

c# - Programmatically find Partition Key Path of Cosmos ...
To retrieve the partition key of a container you have to use the GetContainerQueryIterator() method. Depending on what is already available ...
Read more >
Read an item in Azure Cosmos DB for NoSQL using .NET
However, Azure Cosmos DB requires both the unique identifier and the partition key value of an item to perform a quick point read...
Read more >
Creating a Partitioned Container with .NET SDK
Create CosmosClient Instance · Within the Program. · Locate the Program class and replace it with the following class: · Within the Program...
Read more >
Azure | Lenni's Technology Blog
You need to define a partition key for your container, which is a property the every document contains. The property is used to...
Read more >
Azure Cosmos DB Basics
You can query Cosmos DB using MongoDb API's , SQL Api , Graph API's and much more. ... You can not change the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found