c# - CosmosDb 按 slug 获取项目

标签 c# azure azure-cosmosdb azure-cosmosdb-sqlapi

我正在尝试从名为 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/

相关文章:

Azure DevOps 自托管代理 VMSS : Unable to locate executable file: 'unzip'

azure - DocumentDB 和仅插入架构

c# - 如何识别 Cosmos db 中记录级别的漂移?

c# - 异常 "Cannot access a disposed object"来自非用户代码

c# - 通用函数无法比较数组值和标准值

c# - 在 C# 中,如何根据在 gridview 行中单击的按钮引用特定产品记录

c# - WebApplication 在 IIS Express 上运行良好,但在本地 IIS 上运行不正常

azure - 消费层上 Azure Function App 的允许列表 IP

azure - 将 mvc 5 应用程序连接到 Azure 中的 ACS?

entity-framework - 使用 Cosmos 文档数据库的最佳方式是什么? EF Core 与 Cosmos SDK