问题
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