本文介绍如何通过Java SDK创建表格存储的数据表。
注意事项
创建数据表后,请等待数据表加载完成后再进行数据操作,否则数据操作会失败,这个过程通常需要几秒钟。
前提条件
方法说明
public CreateTableResponse createTable(CreateTableRequest createTableRequest) throws TableStoreException, ClientException
示例代码
以下示例代码创建了一张test_table表,该表包含1个 String类型的主键。
public static void createTableExample(SyncClient client) {
// 构造数据表的结构信息
TableMeta tableMeta = new TableMeta("test_table");
// 创建数据表至少需要添加一个主键
tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema("id", PrimaryKeyType.STRING));
// 构造数据表的配置信息
TableOptions tableOptions = new TableOptions();
// 创建数据表时必须指定最大版本数
tableOptions.setMaxVersions(1);
// 创建数据表时必须指定数据生命周期,-1表示数据永不过期
tableOptions.setTimeToLive(-1);
// 构造Request并发起请求
CreateTableRequest request = new CreateTableRequest(tableMeta, tableOptions);
client.createTable(request);
}
您也可以在创建数据表的同时参考示例代码进行以下设置。
添加预定义列
tableMeta.addDefinedColumn(new DefinedColumnSchema("name", DefinedColumnType.STRING));
设置有效版本偏差
tableOptions.setMaxTimeDeviation(86400);
设置是否允许更新
tableOptions.setAllowUpdate(false);
添加二级索引
// 构造二级索引列表 ArrayList<IndexMeta> indexMetas = new ArrayList<IndexMeta>(); // 构造二级索引 IndexMeta indexMeta = new IndexMeta("test_table_idx"); // 设置索引主键 indexMeta.addPrimaryKeyColumn("id"); indexMeta.addPrimaryKeyColumn("name"); // 设置索引类型 indexMeta.setIndexType(IndexType.IT_LOCAL_INDEX); // 设置索引更新模式 indexMeta.setIndexUpdateMode(IndexUpdateMode.IUM_SYNC_INDEX); // 添加二级索引 indexMetas.add(indexMeta); // 构造Request请求 CreateTableRequest request = new CreateTableRequest(tableMeta, tableOptions, indexMetas);
设置Stream信息
StreamSpecification streamSpecification = new StreamSpecification(true, 168); request.setStreamSpecification(streamSpecification);
设置是否开启局部事务
request.setLocalTxnEnabled(true);
设置预留读写吞吐量
// 设置预留读吞吐量为10000,预留写吞吐量为5000 ReservedThroughput reservedThroughput = new ReservedThroughput(10000, 5000); request.setReservedThroughput(reservedThroughput);
设置数据加密方式
KMS密钥加密
SSESpecification sseSpecification = new SSESpecification(true, SSEKeyType.SSE_KMS_SERVICE); request.setSseSpecification(sseSpecification);
BYOK加密
说明运行代码前需要获取用户主密钥ID和RAM角色ARN,具体操作请参见BYOK加密。
String keyId = "key-hzz6*****************"; String roleArn = "acs:ram::1705************:role/tabletorebyok"; SSESpecification sseSpecification = new SSESpecification(true, SSEKeyType.SSE_BYOK, keyId, roleArn); request.setSseSpecification(sseSpecification);