ZZZSharePoint
ZZZSharePoint

Reputation: 1341

How to have your own partition key while writing data in Cosmos DB

I am using below code to write my content in Cosmos Db, however in Cosmos Db I see the Partition Key is automatically generated and it is for Id which I have kept as default. My requirement is to have my Own Partition Key . from my below json I would like TypeId to be my partition Key How can I do that in my below code?

content is of JObject Type and is of below format {{

"Classes": {
    "Subjects": {
      "Name": "testA",
      "TypeId": "AS88QW",
      "Public": "No"
    },
    "Sections": {
      "Scopes": true
    }
  }

C# code:

// initialized database settings and read json file as string....
 var content = JsonConvert.DeserializeObject<JObject>( lines );

            var client = new DocumentClient( new Uri(Instance ), Key );
            await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(
                Database, Collection ),
                content);   
        }

Upvotes: 0

Views: 738

Answers (2)

Utkarsh Pal
Utkarsh Pal

Reputation: 4544

You can form a partition key by concatenating multiple property values into a single artificial partitionKey property.

Please follow the steps given in below page: https://www.c-sharpcorner.com/article/understanding-partitioning-and-partition-key-in-azure-cosmos-db/

Upvotes: 1

Gaurav Mantri
Gaurav Mantri

Reputation: 136126

When you create the container, you can specify the partition key which is path to a property in your JSON document. My guess is that when you (or someone else) created the container, /id was chosen as the partition key.

Considering partition key for a container can't be changed, what you need to do is create a new container. When you create the new container, ensure that the partition key property is set as /Classes/Subjects/TypeId.

Upvotes: 2

Related Questions