[英]Partition Key for Cosmos DB
I am building an restful API using ASP.NET Core with Cosmos DB. 我正在使用带有Cosmos DB的ASP.NET Core构建一个宁静的API。 There's a GetItemById request that needs a partition key.
有一个需要分区键的GetItemById请求。
public static async Task<T> GetItemAsync(string itemId, string name)
{
try
{
Document document =
await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, itemId),
new RequestOptions() { PartitionKey = new PartitionKey(name) });
return (T)(dynamic)document;
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
else
{
throw;
}
}
}
The GetByIdAsync() function calls this GetItemAsync() method. GetByIdAsync()函数调用此GetItemAsync()方法。
[HttpGet("{itemId}")]
public async Task<IActionResult> GetByIdAsync(string itemId, string name)
{
var item = await DocumentDBRepository<TodoItem>.GetItemAsync(itemId, name);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
The URL would be http://localhost:54084/api/todo/f323307b-142f-46f3-9072-12f41cc74e87 该URL为http:// localhost:54084 / api / todo / f323307b-142f-46f3-9072-12f41cc74e87
My Azure CosmosDB container looks like this: 我的Azure CosmosDB容器如下所示:
But when I run this, it gave me an error with 但是当我运行它时,它给我一个错误
{Microsoft.Azure.Documents.DocumentClientException: Partition key provided either doesn't correspond to definition in the collection or doesn't match partition key field values specified in the document.
{Microsoft.Azure.Documents.DocumentClientException:提供的分区键与集合中的定义不对应,或者与文档中指定的分区键字段值不匹配。
In Cosmos DB, the primary key is the combination of partition key and the row key ("id"). 在Cosmos DB中,主键是分区键和行键(“ id”)的组合。 The combination of the two uniquely identifies a row - not the "id" alone.
两者的组合唯一地标识一行-而不是单独的“ id”。 So you need to specify the value of Name in the partition key to find the item (not null).
因此,您需要在分区键中指定Name的值以查找该项(不为null)。
If your app doesn't have a natural PK, then you should consider setting "/id" as the partition key (and pass the value for both id and partition key) 如果您的应用没有自然的PK,则应考虑将“ / id”设置为分区键(并同时传递ID和分区键的值)
I figured it out. 我想到了。 The reason why I got this error is because I didn't have partition key set up in my collection.
我收到此错误的原因是因为我没有在集合中设置分区键。 That's why I should remove
这就是为什么我应该删除
new RequestOptions() { PartitionKey = new PartitionKey(name) }
After I remove it, it is working properly. 删除它后,它可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.