【问题标题】:CosmosDb get item by slugCosmosDb 通过 slug 获取项目
【发布时间】:2022-06-15 21:58:38
【问题描述】:

我正在尝试从名为 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,但我确信有一篇文章与那个蛞蝓有关。 我想知道问题是否与我的容器或查询有关?!

【问题讨论】:

  • 它使用 /id=slug 和 /slug=slug 搜索项目。你必须做一个查询。例如。 GetItemQueryIterator
  • 查询返回一个数组,对吗?
  • 你的Article类型是什么样的?

标签: azure-cosmosdb .net-6.0


【解决方案1】:

ReadItemAsync 正在使用点查找 - 即 id AND partitionKey

它基本上是在说“给我带有 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
        }
    }
}

【讨论】:

  • 没错,它们不一样。在这种情况下,我应该改用查询?
  • 与往常一样,这取决于 - 文档数量、分区大小等...就我个人而言,如果它是不可变的,我会考虑使用 slug 作为 ID?
猜你喜欢
  • 2022-12-06
  • 2015-02-01
  • 1970-01-01
  • 2017-11-26
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
相关资源
最近更新 更多