
This article was written in 2018. Versions, tools and recommendations may have changed since then. Newer posts are collected under Azure.
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);Related articles

- 17 min read
Automatic TTL in Azure Cosmos DB with .NET
Temporary data is easy to create and surprisingly difficult to remove reliably. Sessions, idempotency keys, import buffers, transient …

- 8 min read
Run Hono on Azure Static Web Apps: managed Functions APIs for static frontends
Azure Static Web Apps is primarily a host for static frontend assets, but it can also deploy a small HTTP API alongside the frontend. That …

- 14 min read
Run Hono on Azure: Container Apps, Functions, App Service and AKS compared
Hono is often associated with Cloudflare Workers and for good reason. Its small routing model, Web Standard API surface and direct fetch …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.
