.net-core - 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我认为这可行。
谢谢。
解决方案
在您提供的代码中,您似乎发送的是分区键名称“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 实例的语句。
推荐阅读
- java - 如何返回具有相同输入的调用之间的函数调用计数?
- linux - 如果在 Linux 主机而不是 Windows 上安装 VxWorks 6.9,则 DCOM 库丢失
- mysql - 相同的查询在 mysql 工作台和 nodejs 中针对相同的查询给出不同数量的结果
- c# - HttpException 请求超时
- javascript - 动漫js动画问题
- javascript - 使用 TMDb 和 axios npm 的电影搜索网站
- mapbox-ios - z-index MGLAnnotationView mapbox IOS
- json - InDesign Socket HTTP 响应缺少部分
- javascript - 控制台上的 chrome.runtime.sendMessage 不起作用
- assembly - 控制台中的 NASM 汇编器问号