Microsoft Azure CosmosDB Unique Key Policy

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.

private static async Task CreateCollectionIfNotExistsAsync(string db, string collection, string keyName, string columnName)
{
    try
    {
        Uri link = UriFactory.CreateDocumentCollectionUri(db, collection);
        await client.ReadDocumentCollectionAsync(link);
    }
    catch (DocumentClientException e) when (e.StatusCode == System.Net.HttpStatusCode.NotFound)
    {
        // Define Collection
        DocumentCollection dc = new DocumentCollection();
        dc.Id = collection;

        // Set PK
        dc.PartitionKey.Paths.Add("/" + keyName);
        dc.UniqueKeyPolicy = new UniqueKeyPolicy
        {
            UniqueKeys =
            new Collection<UniqueKey>
            {
                new UniqueKey { Paths = new Collection<string> { "/" + columnName}}
            }
        };

        // Create Cllection
        await client.CreateDocumentCollectionAsync(
            UriFactory.CreateDatabaseUri(db),
            dc,
            new RequestOptions { OfferThroughput = 1000 });
 
    }

Also you can enforce unqiue key policies to existing collection:

private static async Task EnforceUniqueKeyPolicy(string db, string collection, string keyName, string columnName)
{

    UniqueKeyPolicy policy = new UniqueKeyPolicy
        {
            UniqueKeys =
                new Collection<UniqueKey>
                {
                    new UniqueKey { Paths = new Collection<string> { "/" + columnName }}
                }
        }

    Uri link = UriFactory.CreateDocumentCollectionUri(db, collection);
    DocumentCollection dc = client.ReadDocumentCollectionAsync(link);

    dc.UniqueKeyPolicy = policy;

    await client.ReplaceDocumentCollectionAsync(dc);