How to create a unique index with documentDB

三世轮回 提交于 2019-12-22 06:57:47

问题


Im coming from using mongoDB so will use this as an example, in it I can do something like.

collection.ensureIndex('id', {unique: true, dropDups: true });

And then whenever I try to insert data with the same id, I will get a duplicate key error and it wont work. great!

But can a similar thing be done with documentDB?

Currently I have the following code written with node.js to insert data:

client.createDocument(collection_id, data_to_insert, function (err, doc) {
    callback(err, doc);
});

回答1:


DocumentDB does not have native support for defining unique constraints. The id property is a special exception in which it is the primary key for a document and must be unique.

You can leverage DocumentDB's triggers to implement a unique constraint on other document properties. I have a sample trigger on Github here.

From an indexing perspective - every attribute in every document is automatically indexed by default. If you wish to tune specifically which paths get indexed and which do not, you can define a custom index policy on a collection level.




回答2:


Support for unique constraints is there now: https://docs.microsoft.com/en-us/azure/cosmos-db/unique-keys.




回答3:


Its pretty easy actually. But you'll have to do it on collection create time.

DocumentCollection myCollection = new DocumentCollection();
myCollection.Id = "ClientCollection";
myCollection.UniqueKeyPolicy = new UniqueKeyPolicy
{
    UniqueKeys =
    new Collection<UniqueKey>
    {
        new UniqueKey { Paths = new Collection<string> { "/name" , "/country" }}
        new UniqueKey { Paths = new Collection<string> { "/users/title" } },
    }
};
await client.CreateDocumentCollectionAsync(
    UriFactory.CreateDatabaseUri(dataBase),
    myCollection,
    new RequestOptions { OfferThroughput = 400 });

When you violate an uniquekey constraint then check for this exception

try
{
    response = await client.CreateDocumentAsync(collectionUri, document, requestOptions);
}
catch (Microsoft.Azure.Documents.DocumentClientException ex)
{
    if ( ex.StatusCode == System.Net.HttpStatusCode.Conflict )
    {
        // Unique key constraint violation ...
    }
}

For more information visit my blog



来源:https://stackoverflow.com/questions/31519768/how-to-create-a-unique-index-with-documentdb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!