Cosmos DB 更新插入失败

Cosmos DB Upsert Failure

正在尝试使用 C# 从 Windows10 上的 .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"));
}

文件不多,需要逐个更新。

错误信息是:

Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: 9c545c05-102f-4ed5-9c6c-e5092ae1671b; Reason: (Message: {"Errors":["One of the specified inputs is invalid"]}....

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

谢谢。

在您提供的代码中,您发送的似乎是分区键名称“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 实例。