本文介绍如何通过Go SDK创建表格存储的数据表。
注意事项
创建数据表后,请等待数据表加载完成后再进行数据操作,否则数据操作会失败,这个过程通常需要几秒钟。
前提条件
方法说明
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
相关文档
该文章对您有帮助吗?