c# - 事务批处理 cosmos - 如果在分区中读取特定值则写入

标签 c# azure azure-cosmosdb azure-cosmosdb-sqlapi

在 cosmos 中使用事务批处理,是否可以查询集合中的分区(Select * frompartition where openOrder=1),然后如果查询返回没有未结订单,则添加收藏中的一个项目。

或者您可以先进行写入,然后进行条件读取(从 openOrder=1 和 id={刚刚写入的唯一 GUID} 的分区中选择 *),然后如果第二次读取失败,写入将被反转(?)。

希望在一个原子操作中完成此操作,因为我不想认为没有未结订单,然后另一个进程在此进程之前写入未结订单。

如果没有,是否可以通过其他方式做到这一点?

**编辑 PT 9/16 下午 3:30,尝试使用在测试时编写文档的解决方案 **

function checkOpenOrder(inputDocString, query){
    console.log("Stored Procedure Starting")
    var context = getContext(); 
    var container = context.getCollection();
    var containerLink = container.getSelfLink();
    var response = context.getResponse(); 

    var isAccepted = container.queryDocuments(
        container.getSelfLink(), 
        query,
        function (err, items, options) {
            if (err) throw err;
            // Query would be fed in such that if there is no open order, no items would return in the collection 

            if (items.length == 0){ 
                var docCreated = container.createDocument(containerLink, inputDocString, 
                    function (err2, itemWritten) {
                        if (err2) throw err2;
                        // else was successfully able to write document?
                        response.setBody("Wrote document");
                    });

            }
            else { 
               
                response.setBody("Order currently open");
            }
            

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

    
}

编辑:最后一个问题 9/17 我是否要将最大并行度设置为 1 以确保存储过程不能同时在同一分区中运行 2 次? (如果它发现没有未结订单,则可能会产生竞争条件 -> 创建一个文档,然后我们有 2 个未结订单)。我想我想禁用跨分区查询(而且我不需要它)。 enter image description here

最佳答案

恐怕答案是否定的。 TransactionalBatch 仅支持写入操作。如果您想要像您的情况一样进行跨文档读写事务,您只有两个选择:

  1. 在存储过程中执行事务。仅当您在单个分区中工作时,这才有效,并且您不需要在事务中执行任何非 Cosmos 相关操作。从你的描述来看,应该没问题。

  2. 通过某种锁定在客户端实现事务。

关于c# - 事务批处理 cosmos - 如果在分区中读取特定值则写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63907852/

相关文章:

Azure SQL Server - 管理备份 - 未保存长期保留配置

c# - 如何为用 C# 编写的 Azure Function App 编写单元测试?

azure - 有人可以解释一下 Azure AD 应用程序访问和刷新 token 的超时和验证吗?

azure - Azure 中的 DocumentDB(通过 MongoDB 协议(protocol))集合大小限制

azure - 访问 Cosmos DB 文档的授权 token

c# - NET Core 5 如何覆盖 Controller 上的操作

c# - 获取创建类的对象的实例

c# - ProgressBar 值中的标签未出现

c# - double 格式 - 显示零位或两位小数

azure - 如果 Azure COSMOS 容器用完 RU,会发生什么情况?