本文介绍如何通过 .NET SDK 迭代读取表格存储中的数据。
前提条件
方法说明
public IEnumerable<Row> GetRangeIterator(GetIteratorRequest request)示例代码
以下示例代码使用迭代方式读取 test_table 表中从主键值 row1 开始的数据。
try
{
// 设置查询起始主键
PrimaryKey inclusiveStartPrimaryKey = new PrimaryKey()
{
{ "id", new ColumnValue("row1") }
};
// 设置查询结束主键(返回结果不包含结束主键)
PrimaryKey exclusiveEndPrimaryKey = new PrimaryKey()
{
{ "id", ColumnValue.INF_MAX }
};
// 构造CapacityUnit(记录迭代过程中消耗的CU值)
CapacityUnit capacityUnit = new CapacityUnit(0, 0);
// 构造迭代查询条件
GetIteratorRequest getIteratorRequest = new GetIteratorRequest("test_table", GetRangeDirection.Forward, inclusiveStartPrimaryKey, exclusiveEndPrimaryKey, capacityUnit);
// 调用 GetRangeIterator 获取迭代器
IEnumerable<Row> iterator = client.GetRangeIterator(getIteratorRequest);
foreach (var row in iterator)
{
Console.WriteLine(row);
}
}
catch (Exception ex)
{
Console.WriteLine($"Get range iterator failed, exception: {ex.Message}");
}您可以在迭代读取数据时参考以下示例代码进行参数设置。
设置数据读取方向。
// 设置查询起始主键(反向读取数据时,起始主键要大于结束主键) PrimaryKey inclusiveStartPrimaryKey = new PrimaryKey() { { "id", ColumnValue.INF_MAX } }; // 设置查询结束主键(返回结果不包含结束主键) PrimaryKey exclusiveEndPrimaryKey = new PrimaryKey() { { "id", new ColumnValue("row1") } }; // 构造迭代查询条件(设置反向读取数据) GetIteratorRequest getIteratorRequest = new GetIteratorRequest("test_table", GetRangeDirection.Backward, inclusiveStartPrimaryKey, exclusiveEndPrimaryKey, capacityUnit);设置最大迭代读取行数。
int limit = 20; // 构造迭代查询条件 GetIteratorRequest getIteratorRequest = new GetIteratorRequest("test_table", GetRangeDirection.Forward, inclusiveStartPrimaryKey, exclusiveEndPrimaryKey, capacityUnit, null, limit);指定读取的属性列。
HashSet<string> columnsToGet = new HashSet<string> { "col2" }; // 构造迭代查询条件 GetIteratorRequest getIteratorRequest = new GetIteratorRequest("test_table", GetRangeDirection.Forward, inclusiveStartPrimaryKey, exclusiveEndPrimaryKey, capacityUnit, columnsToGet);