[英]C# - Cosmos DB bulk upsert
I have an Azure function triggered by a timer in which I want to update documents inside CosmosDB.我有一个由计时器触发的 Azure 函数,我想在其中更新 CosmosDB 中的文档。 Now I'm using the function UpdateOneAsync
with option IsUpsert = true
to make the update (or insert if the document doesn't exist).现在我使用带有选项IsUpsert = true
的函数UpdateOneAsync
来进行更新(如果文档不存在则插入)。
However I'm doing the update operation inside a foreach loop, therefore an update operation is performed foreach item.但是,我在 foreach 循环中执行更新操作,因此对每个项目执行更新操作。 How can I do a bulk update (upsert), performing just one operation after the foreach loop finishes?如何进行批量更新(upsert),在 foreach 循环完成后只执行一个操作?
Here it is my code right now:这是我现在的代码:
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;
}
Instead I'd like to perform just one update after the loop.相反,我只想在循环后执行一次更新。 How can I do that?我怎样才能做到这一点?
2020 answer 2020 答案
Bulk support has been added to the .NET SDK: .NET SDK 中添加了批量支持:
Introducing Bulk support in the .NET SDK 在 .NET SDK 中引入批量支持
To use it, first enable bulk execution when you create your client:要使用它,请首先在创建客户端时启用批量执行:
CosmosClient client = new CosmosClientBuilder(options.Value.ConnectionString)
.WithConnectionModeDirect()
.WithBulkExecution(true)
.Build();
Then get your container as normal:然后像往常一样获取您的容器:
Container container = client.GetContainer("databaseName", "containerName");
Then do your bulk operation, eg upsert:然后进行批量操作,例如 upsert:
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);
}
You can use the method BulkUpdateAsync
from the BulkExecutor
,您可以使用BulkUpdateAsync
中的BulkExecutor
方法,
List<UpdateItem> updateList = initialDocuments.Select(d =>
new UpdateItem(
d.id,
d.AccountNumber,
new List<UpdateOperation> {
new SetUpdateOperation<string>(
"NewSimpleProperty",
"New Property Value"),
new SetUpdateOperation<dynamic>(
"NewComplexProperty",
new {
prop1 = "Hello",
prop2 = "World!"
}),
new UnsetUpdateOperation(nameof(FakeOrder.DocumentIndex)),
}))
.ToList();
var updateSetResult = BulkUpdatetDocuments(_database, _collection, updateList).GetAwaiter().GetResult();
and和
var executor = new BulkExecutor(_documentClient, collectionResource);
await executor.InitializeAsync();
return await executor.BulkUpdateAsync(updates);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.