我正在尝试从名为 Articles
的容器中获取单个文章项目,它具有分区键 /slug
public async Task<Article> GetArticle(string slug)
{
try
{
var response = await _container.ReadItemAsync<Article>(slug, new PartitionKey(slug));
return response.Resource;
}
catch (CosmosException) //For handling item not found and other exceptions
{
return null;
}
}
This是我获取示例代码的链接。
就我而言,它返回No Content
,但我确信有一篇文章包含该slug。
我想知道问题是否与我的容器或查询有关?!
最佳答案
ReadItemAsync
使用点查找 - 即 id
AND partitionKey
它基本上是在说“给我带有分区键 x 和 id x 的文档”
我猜你的Article
类型看起来像这样
public class Item
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "slug")]
public string Slug { get; set; }
}
Id 属性与 slug 不同。
您需要将文档的 ID 设置为 slug,或者使用查询。 如果 slug 是不可变的,并且保证是唯一的,那么它可能可用于 ID。
使用 ReadItemAsync
进行点读取仅成本 1 RU,因此更可取。
或者,您需要使用查询,类似这样的东西。
var slug = "some-slug";
using (FeedIterator<Article> feedIterator = _container.GetItemQueryIterator<Article>(
$"select * from Article a where a.slug == {slug}",
null,
new QueryRequestOptions { PartitionKey = new PartitionKey(slug)}))
{
while (feedIterator.HasMoreResults)
{
foreach(var item in await feedIterator.ReadNextAsync())
{
//do something with Article
}
}
}
关于c# - CosmosDb 按 slug 获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72632518/