簡體   English   中英

Cosmos DB的分區鍵

[英]Partition Key for Cosmos DB

我正在使用帶有Cosmos DB的ASP.NET Core構建一個寧靜的API。 有一個需要分區鍵的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;
            }
        }
    }

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

該URL為http:// localhost:54084 / api / todo / f323307b-142f-46f3-9072-12f41cc74e87

我的Azure CosmosDB容器如下所示: 在此處輸入圖片說明

但是當我運行它時,它給我一個錯誤

{Microsoft.Azure.Documents.DocumentClientException:提供的分區鍵與集合中的定義不對應,或者與文檔中指定的分區鍵字段值不匹配。

在Cosmos DB中,主鍵是分區鍵和行鍵(“ id”)的組合。 兩者的組合唯一地標識一行-而不是單獨的“ id”。 因此,您需要在分區鍵中指定Name的值以查找該項(不為null)。

如果您的應用沒有自然的PK,則應考慮將“ / id”設置為分區鍵(並同時傳遞ID和分區鍵的值)

我想到了。 我收到此錯誤的原因是因為我沒有在集合中設置分區鍵。 這就是為什么我應該刪除

new RequestOptions() { PartitionKey = new PartitionKey(name) }

刪除它后,它可以正常工作。

暫無
暫無

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

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