我有一个由计时器触发的 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/