共用方式為


在 Azure Cosmos DB for NoSQL 中使用 .NET 讀取一個項目

Azure Cosmos DB 中的項目代表儲存在容器中的特定實體。 在 NoSQL API 中,項目是由具有唯一識別碼的 JSON 格式資料所組成。

讀取具有唯一識別碼的項目

Azure Cosmos DB for NoSQL 中的每個項目都有由屬性指定的 id 唯一識別碼。 在容器的範圍內,兩個項目不能共享相同的唯一識別碼。 然而,Azure Cosmos DB 需要同時提供項目的唯一識別碼和分割鍵值,才能快速 讀取 該項目。 如果只有唯一識別碼,你就必須執行效率較低的 查詢 ,才能跨多個邏輯分割查找該項目。 欲了解更多點讀取與查詢,請參閱 「優化讀取資料的請求成本」。

讀取項目

備註

本文中的範例假設您已經定義 C# 類型來代表名為 Product 的資料:

// C# record type for items in the container
public record Product(
    string id,
    string category,
    string name,
    int quantity,
    bool sale
);

要執行項目的點讀取,請呼叫以下其中一種方法:

非同步讀取項目

下列範例點會以非同步方式讀取單一項目,並使用提供的泛型型別傳回還原序列化項目:

// Read existing item from container
Product readItem = await container.ReadItemAsync<Product>(
    id: "68719518388",
    partitionKey: new PartitionKey("gear-surf-surfboards")
);

Database.ReadItemAsync<> 方法會讀取項目並傳回 ItemResponse<> 類型的物件。 ItemResponse<> 型別繼承自Response<>型別,該型別包含一個隱含的轉換運算子,用以將物件轉換為通用型別。 若要深入瞭解隱含運算子,請參閱使用者定義的轉換運算子

或者,你也可以回傳 ItemResponse<> 的通用型別,並明確取得該資源。 更一般的 ItemResponse<> 類型也包含關於底層 API 操作的有用元資料。 在此範例中,透過 RequestCharge 屬性收集關於此操作請求單元費用的元資料。

// Read existing item from container
ItemResponse<Product> readResponse = await container.ReadItemAsync<Product>(
    id: "68719518388",
    partitionKey: new PartitionKey("gear-surf-surfboards")
);

// Get response metadata
double requestUnits = readResponse.RequestCharge;
HttpStatusCode statusCode = readResponse.StatusCode;

// Explicitly get item
Product readItemExplicit = readResponse.Resource;

非同步讀取一個項目作為串流

此範例將項目直接讀取為資料流:

// Read existing item from container
using ResponseMessage readItemStreamResponse = await container.ReadItemStreamAsync(
    id: "68719518388",
    partitionKey: new PartitionKey("gear-surf-surfboards")
);

// Get stream from response
using StreamReader readItemStreamReader = new(readItemStreamResponse.Content);

// (optional) Get stream content
string content = await readItemStreamReader.ReadToEndAsync();

方法Container.ReadItemStreamAsync將項目回傳為一個Stream,且不會將內容反序列化。

如果你不打算直接反序列化項目,使用 stream API 可以提升效能,因為它能將項目作為串流直接交接給應用程式的下一個元件。 想了解更多如何優化 SDK 以符合高效能情境的建議,請參見 SDK 效能提示

非同步讀取多個項目

在此範例中,包含唯一識別碼與分割鍵對的元組清單用於查找與檢索多個項目:

// Create partition key object
PartitionKey partitionKey = new("gear-surf-surfboards");

// Create list of tuples for each item
List<(string, PartitionKey)> itemsToFind = new()
{
    ("68719518388", partitionKey),
    ("68719518381", partitionKey)
};

// Read multiple items
FeedResponse<Product> feedResponse = await container.ReadManyItemsAsync<Product>(
    items: itemsToFind
);

foreach (Product item in feedResponse)
{
    Console.WriteLine($"Found item:\t{item.name}");
}

Container.ReadManyItemsAsync<> 會回傳一份根據你提供的獨特識別碼和分割鍵的項目清單。 此操作旨在比使用 IN 語句查詢大量獨立項目的延遲效率更好。

後續步驟

現在你已經閱讀了各種文章,請使用下一份指南來查詢商品。