本文介紹如何通過Go SDK建立Table Store的資料表。
注意事項
建立資料表後,請等待資料表載入完成後再進行資料操作,否則資料操作會失敗,這個過程通常需要幾秒鐘。
前提條件
方法說明
func (tableStoreClient *TableStoreClient) CreateTable(request *CreateTableRequest) (*CreateTableResponse, error)
範例程式碼
以下範例程式碼建立了一張test_table表,該表包含1個 String類型的主鍵。
func CreateTableSample(client *tablestore.TableStoreClient) {
// 構造資料表的結構資訊
tableMeta := new(tablestore.TableMeta)
tableMeta.TableName = "test_table"
// 建立資料表至少需要添加一個主鍵
tableMeta.AddPrimaryKeyColumn("id", tablestore.PrimaryKeyType_STRING)
// 構造資料表的配置資訊
tableOption := new(tablestore.TableOption)
// 建立資料表時必須指定最大版本數
tableOption.MaxVersion = 1
// 建立資料表時必須指定資料生命週期,-1表示資料永不到期
tableOption.TimeToAlive = -1
// 建立資料表時必須設定預留讀寫輸送量,預設值為0(僅CU模式高效能執行個體支援設定資料表的預留讀寫輸送量為非零值)
reservedThroughput := new(tablestore.ReservedThroughput)
reservedThroughput.Readcap = 0
reservedThroughput.Writecap = 0
// 構造Request並發起請求
createTableRequest := new(tablestore.CreateTableRequest)
createTableRequest.TableMeta = tableMeta
createTableRequest.TableOption = tableOption
createTableRequest.ReservedThroughput = reservedThroughput
_, err := client.CreateTable(createTableRequest)
if err != nil {
fmt.Println("Failed to create table with error:", err)
} else {
fmt.Println("Create table finished.")
}
}
您也可以在建立資料表的同時參考範例程式碼進行以下設定。
添加預定義列
tableMeta.AddDefinedColumn("name", tablestore.DefinedColumn_STRING)
設定有效版本偏差
tableOption.DeviationCellVersionInSec = 86400
設定是否允許更新
tableOption.AllowUpdate = proto.Bool(false)
添加二級索引
// 構造二級索引 indexMeta := new(tablestore.IndexMeta) indexMeta.IndexName = "test_table_index" // 設定索引主鍵 indexMeta.AddPrimaryKeyColumn("id") indexMeta.AddPrimaryKeyColumn("name") // 設定索引類型 indexMeta.IndexType = tablestore.IT_LOCAL_INDEX // 添加二級索引 createTableRequest.AddIndexMeta(indexMeta)
設定Stream資訊
streamSpec := new(tablestore.StreamSpecification) streamSpec.EnableStream = true streamSpec.ExpirationTime = 168 createTableRequest.StreamSpec = streamSpec
設定是否開啟局部事務
enableLocalTxn := proto.Bool(true) createTableRequest.EnableLocalTxn = enableLocalTxn
設定資料加密方式
KMS祕密金鑰加密
sseSpec := new(tablestore.SSESpecification) sseSpec.SetEnable(true) sseSpec.SetKeyType(tablestore.SSE_KMS_SERVICE) createTableRequest.SSESpecification = sseSpec
BYOK加密
說明運行代碼前需要擷取使用者主要金鑰ID和RAM角色ARN,具體操作請參見BYOK加密。
sseSpec := new(tablestore.SSESpecification) sseSpec.SetEnable(true) sseSpec.SetKeyType(tablestore.SSE_BYOK) sseSpec.SetKeyId("key-hzz65****************") sseSpec.SetRoleArn("acs:ram::1705************:role/tabletorebyok") createTableRequest.SSESpecification = sseSpec