你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
Azure Cosmos DB 中的项表示存储在容器中的特定实体。 在 API for NoSQL 中,项由具有唯一标识符的 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();
该方法返回项为 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语句的查询相比,该操作的延迟表现更好,可更快地提取大量独立项。
后续步骤
现在您已经阅读了各种条目,请使用接下来的指南查询条目。