本文介紹如何通過Java SDK建立Table Store的資料表。
注意事項
建立資料表後,請等待資料表載入完成後再進行資料操作,否則資料操作會失敗,這個過程通常需要幾秒鐘。
前提條件
方法說明
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);