首页 > 解决方案 > Cosmos DB Upsert 失败

问题描述

尝试在使用 C# 的 Windows 10 上从 .NET Core 3.1 控制台应用程序将项目更新插入 Cosmos DB。

JSON 文档如下所示:

{
        "id": "25217f96-d399-4bb7-b8f1-4a7365cca76c",
        "title": "my title",
        "eventUtc": "2020-09-04T14:16:04+0000" ,
        "listOne":
                        [
                                {"person1" : "james" , "contributorContact" : "" , "contributorTtype" : "contributor"} ,
                                {"person2" : "veena" , "contributorContact" : "" , "contributorTtype" : "contributor"}
                        ]
        ,
        "listTwo" :
                        [
                                "lorem" , "ipsum"  , "dolor" 
                        ] ,
        "synopsis" : "abcdefghi."  }

该文档在容器中不存在,但该容器已经与另一个文档一起存在。分区键是“id”。

此代码失败:...

foreach (var fileOne in Directory.GetFiles(fileLoc))
{
    MemoryStream stream = new MemoryStream();
    await System.Text.Json.JsonSerializer.SerializeAsync(stream, File.ReadAllText(fileOne));
    var response = await cosmosContainer.UpsertItemStreamAsync(stream, new PartitionKey("id"));
}

文件不多,因此需要单独更新它们。

错误信息是:

响应状态码不表示成功:BadRequest(400);子状态:0;活动ID:9c545c05-102f-4ed5-9c6c-e5092ae1671b;原因:(消息:{“错误”:[“指定的输入之一无效”]} ....

代码中的错误在哪里?基于https://github.com/Azure/azure-cosmos-dotnet-v3/issues/1463我认为这可行。

谢谢。

标签: .net-coreazure-cosmosdbazure-cosmosdb-sqlapi

解决方案


在您提供的代码中,您似乎发送的是分区键名称“id”而不是id项目的。它应该看起来像:

foreach (var fileOne in Directory.GetFiles(fileLoc))
{
    MemoryStream stream = new MemoryStream();
    await System.Text.Json.JsonSerializer.SerializeAsync(stream, File.ReadAllText(fileOne));
    string itemId = // Extract ID from item
    var response = await cosmosContainer.UpsertItemStreamAsync(stream, new PartitionKey(itemId));
}

itemId请注意在提供分区键时使用已解析。此外,您可能需要一个using带有 MemoryStream 实例的语句。


推荐阅读