簡體   English   中英

CosmosDb 通過 slug 獲取項目

[英]CosmosDb get item by slug

我正在嘗試從名為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;
        }
    }

是我獲得示例代碼的鏈接。

就我而言,它返回No Content ,但我確信有一篇文章帶有那個蛞蝓。 我想知道問題是否與我的容器或查詢有關?!

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
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM