stored-procedures - 我可以检查唯一性并在 Cosmos DB 存储过程中写入文档吗

标签 stored-procedures azure-cosmosdb

我有一个 Cosmos DB 存储过程,如果新文档尚不存在,它会创建一个新文档并返回现有文档或新文档。该过程可以从不同的进程调用。即使多个客户端尝试同时创建该文档,我能否确保该文档仅创建一次?

function createIfNotExists(param1, param2) {
    var collection = getContext().getCollection();

    // Query documents and take 1st item.
    var query = 'SELECT * FROM c WHERE c.Param1="' + param1 + '" AND c.Param2="' + param2 + '"';
    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        query,
        function (err, items, options) {
            if (err) throw err;

            var response = getContext().getResponse();
            if (!items || !items.length) {
                var accepted = collection.createDocument(collection.getSelfLink(),
                {
                    Param1: param1,
                    Param2: param2
                },
                function (err, itemCreated) {
                    if (err) throw err;
                    response.setBody(itemCreated);
                });

                if (!accepted) throw new Error('Could not create document');
            }
            else {
                response.setBody(items[0]);
            }
        });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

最佳答案

Can I be sure that the document is only created once even if several clients are trying to create it at the same time?

Hein,关于你关心的问题,你可以深入研究这个document其中阐述了 Cosmos DB 中的 ACID。

In Azure Cosmos DB, JavaScript runtime is hosted inside the database engine. Hence, requests made within the stored procedures and the triggers execute in the same scope as the database session. This feature enables Azure Cosmos DB to guarantee ACID properties for all operations that are part of a stored procedure or a trigger. For examples.

所以,我认为你的问题的答案是肯定的,因为原子性保证事务内完成的所有操作都被视为一个单元,并且要么全部提交,要么全部不提交。

顺便说一句,您还可以在创建集合之前设置一个或多个唯一键,请引用此blog .

关于stored-procedures - 我可以检查唯一性并在 Cosmos DB 存储过程中写入文档吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54443220/

相关文章:

azure - 使用 EF 的 Cosmos DB 中的字典属性

执行 Postgresql 存储过程时出现 VB.NET 错误

javascript - 无法使用sequelize 创建存储过程

java - java 调用中的过程调用不起作用

asp.net - 我无法使用 "host.docker.internal:some-port"将我的 ASP .NET 应用程序从 Docker 容器连接到我的计算机主机数据库

Azure Cosmos DB 与 Firebase firestore 或 firebase 实时数据库相同吗?

由于Java中的多线程,Mysql过程更新错误值

c# - 调用存储过程时处理 SQL 注入(inject)的最佳实践

mongodb - 在使用 CLI 创建的 MongoDB 分片集合中插入文档时出错

mongodb - CosmosDB - Mongodb IsUpsert 不适用于批量更新