我正在尝试通过 azure 函数从 Cosmos DB 数据库容器中删除项目。 但我收到此错误 必须为此操作提供 PartitionKey 值。 我还调查了 this但没有从那里得到任何运气。
下面是我的代码 -
public class Item{
public Item(){}
public string id {get; set;}
}
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
DocumentClient client = new DocumentClient(new Uri("https://***.documents.azure.com:443/"), Environment.GetEnvironmentVariable("key"));
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var updated = JsonConvert.DeserializeObject<Item>(requestBody);
var option = new FeedOptions { EnableCrossPartitionQuery = true };
var collectionUri = UriFactory.CreateDocumentCollectionUri("Test_DB", "Test_Table");
var document = client.CreateDocumentQuery(collectionUri, option).Where(t => t.Id == updated.id)
.AsEnumerable().FirstOrDefault();
log.LogInformation("Total Incentive : " + document.GetPropertyValue<string>("id"));
if (document == null)
{
return new NotFoundResult();
}
log.LogInformation("Total Incentive : " + document.SelfLink);
log.LogInformation("Total Incentive : " + document.Id);
await client.DeleteDocumentAsync(document.SelfLink);
//await client.ReplaceDocumentAsync(document);
return new OkObjectResult("Deleted");
}
经过谷歌搜索后,我意识到我需要提供一个分区键值作为 DeleteDocumentAsync() 中的第二个参数,如下所示。但我正在修复如何向该函数提供该分区键值。
await client.DeleteDocumentAsync(document.SelfLink,
new Requestoptions
{
PartitionKey = new Microsoft.Azure.Documents.PartitionKey("33333")
}
)
数据库名称: Test_DB
表名称: Test_Table
分区键:/testCategory
我尝试删除的 Test_Table 的示例元素是:
{
"id": "3f614t4e-q85f-4357-8393-a0b3542db4e1",
"Email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a0e1f090e0f091f083a0e1f090e54191517" rel="noreferrer noopener nofollow">[email protected]</a>",
"Name": "Test User",
"_rid": "XNMBANxVc8oIAAAAAAAAAA==",
"_self": "dbs/XNMOXA==/colls/TNMNANyVc9o=/docs/XNMBANxVc8oIZZAAAAAAPP==/",
"_etag": "\"450031d4-0000-0300-0000-60cb36470000\"",
"_attachments": "attachments/",
"_ts": 1623930439
}
任何人都可以帮助我如何将该分区键放入 azure 功能代码中吗?或者说如何调整数据库的表?
提前致谢。
最佳答案
如评论中所述,当文档中未指定分区键时,可以使用 Microsoft.Azure.Documents.PartitionKey.None
作为删除和更新的分区键值。
在 Cosmos DB 中,创建文档时,每个文档都必须为分区键属性(在您的情况下为 testCategory
)指定一个值。但是,如果您不指定值,Cosmos DB 不会提示。它只是将此类文档放在一个特殊的分区中,可以通过在需要的方法中指定 Microsoft.Azure.Documents.PartitionKey.None
来访问该分区。
关于c# - 必须在使用 DocumentClient 的 CosmosDB 删除操作中为此操作提供 PartitionKey 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68022195/