C# - Cosmos DB 批量更新插入

标签 c# azure-cosmosdb upsert bulk

我有一个由计时器触发的 Azure 函数,我想在其中更新 CosmosDB 中的文档。现在,我使用函数 UpdateOneAsync 和选项 IsUpsert = true 进行更新(如果文档不存在则插入)。

但是我在 foreach 循环内执行更新操作,因此对每个项目执行更新操作。如何进行批量更新(upsert),在 foreach 循环完成后只执行一个操作?

这是我现在的代码:

foreach (var group in GetGroups(date, time, hour))
{
    dic = new MyDictionary<string>();

    //... some operations

    List<BsonElement> documents = new List<BsonElement>();
    documents.Add(new BsonElement("$inc", new BsonDocument(dic)));
    documents.Add(new BsonElement("$set", new BsonDocument(new Dictionary<string, string>() { { "c", key }, { "d", date } })));

    var doc = clicksDoc.UpdateOneAsync(t => t["_id"] == "c-" + key + "-" + date, new BsonDocument(documents), new UpdateOptions() { IsUpsert = true }).Result;
}

相反,我只想在循环后执行一次更新。我该怎么做?

最佳答案

2020 年答案

批量支持已添加到 .NET SDK:
Introducing Bulk support in the .NET SDK

要使用它,首先在创建客户端时启用批量执行:

CosmosClient client = new CosmosClientBuilder(options.Value.ConnectionString)
    .WithConnectionModeDirect()
    .WithBulkExecution(true)
    .Build();

然后像往常一样获取容器:

Container container = client.GetContainer("databaseName", "containerName");

然后进行批量操作,例如更新:

public async Task BulkUpsert(List<SomeItem> items)
{
    var concurrentTasks = new List<Task>();

    foreach (SomeItem item in items)
    {
        concurrentTasks.Add(container.UpsertItemAsync(item, new PartitionKey(item.PartitionKeyField)));
    }

    await Task.WhenAll(concurrentTasks);
}

关于C# - Cosmos DB 批量更新插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56255336/

相关文章:

javascript - 当发生写入数据库的并发 API 调用时(或者当服务器速度缓慢时),防止竞争情况

sql - 替换为 postgresql 的等价物,然后自动递增一个 int

c# - 如何顺利开发C#/.NET的C库?

azure - 处理 cosmos sql 查询中 ARRAY_CONTAINS 搜索中的特殊字符

azure - 在迭代数组 cosmos db 之前过滤分区键

php - Azure 函数应用程序 - PHP $_GET/$_POST/$_REQUEST

php - 我尝试实现 UPSERT 时遇到的问题

c# - 事件 'Command.CanExecuteChanged' 只能出现在 += 或 -= 的左侧

c# - 如何在返回 View 之前修改 Controller 中的查询字符串

c# - 模板控件中的 ContentPresenter 不起作用