Home > database >  how do i add a partition key using Azure.ResourceManager.CosmosDB c#
how do i add a partition key using Azure.ResourceManager.CosmosDB c#

Time:03-12

I can create a database and container without an issue on both gremlin and sql, ut I can't seem to set the partition key.

I would expect to do

/// var containerParams = new SqlContainerCreateUpdateParameters ( new SqlContainerResource(databaseName) {

                    PartitionKey = new ContainerPartitionKey()
                    {
                        Paths = new List<string>{partialKey}
                    }
                },
                new CreateUpdateOptions()
            )

///

I would expect to do something like this, but the Paths field is readonly, and I can't see any other option to set it.

[Update] i got it working with creating an object then converting to json and back to ContainerPartitionKey

CodePudding user response:

You can create using ContainerProperties

 private static readonly string databaseName = "DemoDB";
 private static readonly string containerName = "SalesOrders";
 private static readonly string containerPartitionKey = "/AccountNumber";

ContainerProperties containerProperties = new ContainerProperties(containerName, containerPartitionKey);
ContainerRequestOptions containerRequestOptions = new ContainerRequestOptions { PopulateQuotaInfo = true };
ContainerResponse containerResponse = await database.CreateContainerIfNotExistsAsync(
containerProperties: containerProperties,
throughputProperties: ThroughputProperties.CreateAutoscaleThroughput(autoscaleMaxThroughput: 4000),
containerRequestOptions
 );

CodePudding user response:

Here is the syntax for creating the partition key using Cosmos DB Azure Management SDK.

SqlContainerCreateUpdateParameters sqlContainerCreateUpdateParameters = new SqlContainerCreateUpdateParameters
{
    Resource = new SqlContainerResource
    {
        Id = containerName,
        DefaultTtl = -1, //-1 = off, 0 = on no default, >0 = ttl in seconds
        AnalyticalStorageTtl = -1,
        PartitionKey = new ContainerPartitionKey
        {
        Kind = "Hash",
        Paths = new List<string> { "/myPartitionKey" },
        Version = 1 //version 2 for large partition key
    }
}

You can find a complete SqlContainer create example here. You can also find a complete set of examples for how to use the Azure Management SDK for Cosmos DB in GitHub. Please note, it is out of date but should still work for illustrating how to use to manage Cosmos resources.

  • Related