本文介绍如何通过 .NET SDK 批量读取表格存储中的数据,支持查询多个表的数据。
注意事项
单次批量读取操作最多支持读取 100 行数据。
前提条件
方法说明
public BatchGetRowResponse BatchGetRow(BatchGetRowRequest request)异步方法:
public Task<BatchGetRowResponse> BatchGetRowAsync(BatchGetRowRequest request)示例代码
以下示例代码用于读取 test_table 表中主键值为 row1 和 row2 的两行数据。
try
{
List<PrimaryKey> primaryKeys = new List<PrimaryKey>
{
// 添加第 1 行主键信息
new PrimaryKey {{ "id", new ColumnValue("row1") }},
// 添加第 2 行主键信息
new PrimaryKey {{ "id", new ColumnValue("row2") }},
};
// 构造查询条件
BatchGetRowRequest batchGetRowRequest = new BatchGetRowRequest();
batchGetRowRequest.Add("test_table", primaryKeys);
// 调用 BatchGetRow 方法读取行数据
BatchGetRowResponse batchGetRowResponse = client.BatchGetRow(batchGetRowRequest);
// 返回结果处理
Console.WriteLine($"* RequestId: {batchGetRowResponse.RequestID}");
Console.WriteLine($"* Is all succeeded: {batchGetRowResponse.IsAllSucceed}");
foreach (var tableGroup in batchGetRowResponse.RowDataGroupByTable)
{
Console.WriteLine($"* Table: {tableGroup.Key}");
foreach (var item in tableGroup.Value)
{
if (item.IsOK)
{
if (item.Row != null)
{
Console.WriteLine($"Succeeded Row: {item.Row}");
}
else
{
Console.WriteLine("Succeeded Row: This row is not exist.");
}
}
else
{
Console.WriteLine($"Failed Row: {item.ErrorMessage}");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Batch get row failed, exception: {ex.Message}");
}您可以在批量读取数据时参考以下示例代码进行参数设置。
读取多张表的数据。批量读取支持一次读取多张表的数据,您需要为每张表指定一个MultiRowQueryCriteria。
// 构造第 2 个表的查询条件 List<PrimaryKey> primaryKeys1 = new List<PrimaryKey> { new PrimaryKey {{ "order_id", new ColumnValue("90fb478c-1360-11f0-a34d-00163e30a2a9") }} }; batchGetRowRequest.Add("orders_small", primaryKeys1);指定读取的属性列。
HashSet<string> columnsToGet = new HashSet<string> { "col2" }; batchGetRowRequest.Add("test_table", primaryKeys, columnsToGet);