本文介绍如何通过.NET SDK创建表格存储的数据表。
注意事项
创建数据表后,请等待数据表加载完成后再进行数据操作,否则数据操作会失败,这个过程通常需要几秒钟。
前提条件
方法说明
public CreateTableResponse CreateTable(CreateTableRequest request)
异步方法:
public Task<CreateTableResponse> CreateTableAsync(CreateTableRequest request)
示例代码
以下示例代码创建了一张test_table表,该表包含1个 String类型的主键。
try
{
// 创建数据表至少需要添加一个主键
PrimaryKeySchema primaryKeySchema = new PrimaryKeySchema
{
{ "id", ColumnValueType.String }
};
// 构造数据表的结构信息
TableMeta tableMeta = new TableMeta("test_table", primaryKeySchema);
// 创建数据表时必须设置预留读写吞吐量(仅CU模式高性能实例支持设置数据表的预留读写吞吐量为非零值)
CapacityUnit reservedThroughput = new CapacityUnit(0, 0);
// 构造request并发起请求
CreateTableRequest request = new CreateTableRequest(tableMeta, reservedThroughput);
client.CreateTable(request);
Console.WriteLine("Create table succeeded.");
}
catch (Exception ex)
{
Console.WriteLine($"Create table failed, exception:{ex.Message}");
}
您也可以在创建数据表的同时参考示例代码进行以下设置。
添加预定义列
DefinedColumnSchema definedColumnSchema = new DefinedColumnSchema { { "name" , DefinedColumnType.STRING } }; tableMeta.DefinedColumnSchema = definedColumnSchema;
设置有效版本偏差
TableOptions tableOptions = new TableOptions(); tableOptions.DeviationCellVersionInSec = 86400; request.TableOptions = tableOptions;
设置是否允许更新
TableOptions tableOptions = new TableOptions(); tableOptions.AllowUpdate = false; request.TableOptions = tableOptions;
添加二级索引
// 构造二级索引列表 List<IndexMeta> indexMetas = new List<IndexMeta>(); // 构造二级索引 IndexMeta indexMeta = new IndexMeta("test_table_index"); // 设置索引主键 indexMeta.PrimaryKey = new List<string>() { "id", "name" }; // 设置索引类型 indexMeta.IndexType = IndexType.IT_GLOBAL_INDEX; // 设置索引更新模型 indexMeta.IndexUpdateModel = IndexUpdateMode.IUM_ASYNC_INDEX; // 添加二级索引 indexMetas.Add(indexMeta); // 构造request请求 CreateTableRequest request = new CreateTableRequest(tableMeta, reservedThroughput, indexMetas);
设置Stream信息
StreamSpecification streamSpecification = new StreamSpecification(true); streamSpecification.ExpirationTime = 168; request.StreamSpecification = streamSpecification;