Jay*_*Jay 1 azure azure-cosmosdb
我正在尝试使用 Azure Cosmos DB 设置一个简单的控制台项目。我对分区键用法感到困惑。
请注意,我已经看过这个解决方案,但我相信我的情况略有不同。
我正在像这样设置容器。
private string PartitionKeyPath = "/ProductPartitionKey";
this.container = await this.database.CreateContainerIfNotExistsAsync(containerId, PartitionKeyPath);
Run Code Online (Sandbox Code Playgroud)
这是一个示例 JSON,因为它存储在容器中。所以,我成功地添加了项目。
{
"Name": "Super Curtain",
"UnitPrice": 500,
"id": "124BBC08-F51C-4ED4-B961-8DD0C966F66F",
"ProductPartitionKey": "Hello",
"_rid": "m2VTANekt8ACAAAAAAAAAA==",
"_self": "dbs/m2VTAA==/colls/m2VTANekt8A=/docs/m2VTANekt8ACAAAAAAAAAA==/",
"_etag": "\"0500753f-0000-1800-0000-5f735ac70000\"",
"_attachments": "attachments/",
"_ts": 1601395399
}
Run Code Online (Sandbox Code Playgroud)
我可以使用以下两种用法进行插入。
var tempPartitionKey = new PartitionKey(tempProduct.ProductPartitionKey);
ItemResponse < Product > tempProductResponse = await this.container.CreateItemAsync < Product > (tempProduct, tempPartitionKey);
ItemResponse < Product > tempProductResponse = await this.container.CreateItemAsync < Product > (tempProduct);
Run Code Online (Sandbox Code Playgroud)
问题是,为什么下面的工作不起作用?
var tempPartitionKey2 = new PartitionKey("/ProductPartitionKey");
ItemResponse < Product > tempProductResponse = await this.container.CreateItemAsync < Product > (tempProduct, tempPartitionKey2);
Run Code Online (Sandbox Code Playgroud)
或这个。
var tempPartitionKey3 = new PartitionKey("ProductPartitionKey");
ItemResponse<Product> tempProductResponse = await this.container.CreateItemAsync<Product>(tempProduct, tempPartitionKey3);
Run Code Online (Sandbox Code Playgroud)
我在链接堆栈问题中遇到了同样的错误。
PartitionKey extracted from document doesn't match the one specified in the header
Run Code Online (Sandbox Code Playgroud)
所以,最终,我试图理解,我可以使用 new PartitionKey() 使用什么字符串文字?
或者,
是不是这样,在当前时间点,这是设置和使用分区键的唯一方法,我不应该尝试使用直接的字符串文字值设置分区键?或许,这不是一个好办法,蔚蓝宇宙图书馆已经停止或移除了那个能力。
var tempPartitionKey2 = new PartitionKey("/ProductPartitionKey");
ItemResponse < Product > tempProductResponse = await this.container.CreateItemAsync < Product > (tempProduct, tempPartitionKey2);
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为您没有传递分区键值,而是传递配置为容器中分区键路径的属性的名称。
当后端收到您的项目 Json 并看到该值与项目 Json 所具有的值不对应时,就会出现错误。
创建项目时,该操作需要项目内容,以及该文档的分区键路径值,即分区键值。这就是为什么这有效:
var tempPartitionKey = new PartitionKey(tempProduct.ProductPartitionKey);
ItemResponse < Product > tempProductResponse = await this.container.CreateItemAsync < Product > (tempProduct, tempPartitionKey);
Run Code Online (Sandbox Code Playgroud)
因为您正在传递该属性的值。
如果您未指定 PartitionKey 参数,则 SDK 需要从项目负载中提取它,这会对性能/CPU 造成影响。所以建议,如果可以,将值指定为 PartitionKey 参数。
| 归档时间: |
|
| 查看次数: |
516 次 |
| 最近记录: |