C#-Cosmos DB批量上传

时间:2019-05-22 11:00:43

标签: 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;
}

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

2 个答案:

答案 0 :(得分:1)

您可以使用 BulkExecutor 中的 BulkUpdateAsync 方法,

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();

var executor = new BulkExecutor(_documentClient, collectionResource);
await executor.InitializeAsync();
return await executor.BulkUpdateAsync(updates);

SAMPLE

答案 1 :(得分:0)

2020年答案

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

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

class UserPermissionsViewModel(application: Application) : AndroidViewModel(application) {

    private val userPermissionsRepo = UserPermissionsRepo(application)

}

然后按正常方式放置容器:

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

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

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