SchwabenCode Blog Post

Microsoft Azure CosmosDB Unique Key Policy

If you want to create custom unique keys inside a collections, you can simply create a UniqueKeyPolicy while creating your collection.

 1private static async Task CreateCollectionIfNotExistsAsync(string db, string collection, string keyName, string columnName)
 2{
 3    try
 4    {
 5        Uri link = UriFactory.CreateDocumentCollectionUri(db, collection);
 6        await client.ReadDocumentCollectionAsync(link);
 7    }
 8    catch (DocumentClientException e) when (e.StatusCode == System.Net.HttpStatusCode.NotFound)
 9    {
10        // Define Collection
11        DocumentCollection dc = new DocumentCollection();
12        dc.Id = collection;
13
14        // Set PK
15        dc.PartitionKey.Paths.Add("/" + keyName);
16        dc.UniqueKeyPolicy = new UniqueKeyPolicy
17        {
18            UniqueKeys =
19            new Collection<UniqueKey>
20            {
21                new UniqueKey { Paths = new Collection<string> { "/" + columnName}}
22            }
23        };
24
25        // Create Cllection
26        await client.CreateDocumentCollectionAsync(
27            UriFactory.CreateDatabaseUri(db),
28            dc,
29            new RequestOptions { OfferThroughput = 1000 });
30 
31    }

Also you can enforce unqiue key policies to existing collection:

 1private static async Task EnforceUniqueKeyPolicy(string db, string collection, string keyName, string columnName)
 2{
 3
 4    UniqueKeyPolicy policy = new UniqueKeyPolicy
 5        {
 6            UniqueKeys =
 7                new Collection<UniqueKey>
 8                {
 9                    new UniqueKey { Paths = new Collection<string> { "/" + columnName }}
10                }
11        }
12
13    Uri link = UriFactory.CreateDocumentCollectionUri(db, collection);
14    DocumentCollection dc = client.ReadDocumentCollectionAsync(link);
15
16    dc.UniqueKeyPolicy = policy;
17
18    await client.ReplaceDocumentCollectionAsync(dc);

Comments

Twitter Facebook LinkedIn WhatsApp