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

適用於:NoSQL

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,而不還原序列化內容。

如果您不打算直接還原序列化項目,使用串流 API 可以將項目作為資料流程直接交給應用程式的下一個元件,以改善效能。 如需如何針對高效能案例優化 SDK 的更多秘訣,請參閱 SDK 效能秘訣

以非同步方式讀取多個項目

在此範例中,包含唯一識別碼和資料分割索引鍵組的 Tuple 清單可用來查閱和擷取多個項目:

// 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 陳述式擷取大量獨立項目的查詢,此作業在延遲方面的表現會更好。

下一步

現在您已閱讀各種項目,請使用下一個指南來查詢項目。