通过 Python SDK创建表格存储数据表,按需配置表结构、表选项、二级索引和数据加密。
使用说明
创建数据表后,需等待数据表加载完成再进行数据操作,否则操作会失败。加载过程通常需要几秒钟。
前提条件
方法说明
def create_table(self, table_meta, table_options, reserved_throughput, secondary_indexes=[], sse_spec)
示例代码
以下示例创建了一张名为 test_table 的数据表,包含 1 个 STRING 类型的主键列。
# 数据表至少需要 1 个主键列
schema_of_primary_key = [('id', 'STRING')]
# 构造表结构信息
table_meta = TableMeta('test_table', schema_of_primary_key)
# 构造表配置信息
table_options = TableOptions(time_to_live=-1, max_version=1, max_time_deviation=86400, allow_update=True)
# 设置预留读写吞吐量,默认为 0 CU
# 仅 CU 模式的高性能实例支持设置为非零值
reserved_throughput = ReservedThroughput(CapacityUnit(0,0))
try:
client.create_table(table_meta, table_options, reserved_throughput)
print("Create table succeeded.")
except Exception as e:
print("Create table failed. %s" % e)
创建数据表时还可以进行以下可选配置。
-
添加预定义列
defined_columns = [('name', 'STRING')] # 将预定义列加入表结构信息 table_meta = TableMeta('test_table', schema_of_primary_key, defined_columns) -
添加二级索引
# 构造二级索引列表 secondary_indexes = [ # 设置索引名称、索引主键列、索引预定义列、索引类型 SecondaryIndexMeta('test_table_index', ['id', 'name'], [], index_type= SecondaryIndexType.LOCAL_INDEX) ] client.create_table(table_meta, table_options, reserved_throughput, secondary_indexes) -
设置数据加密
通过
SSESpecification类配置数据表的服务端加密(SSE)。-
KMS 加密
sse_specification = SSESpecification(enable=True, key_type=SSEKeyType.SSE_KMS_SERVICE, key_id=None, role_arn=None) client.create_table(table_meta, table_option, reserved_throughput, sse_spec=sse_specification) -
BYOK 加密
说明运行代码前需获取用户主密钥ID和RAM角色 ARN,具体操作请参见BYOK加密。
key_id = "key-hzz6*****************" role_arn = "acs:ram::1705************:role/tabletorebyok" sse_specification = SSESpecification(enable=True, key_type=SSEKeyType.SSE_BYOK, key_id=key_id, role_arn=role_arn) client.create_table(table_meta, table_option, reserved_throughput, sse_spec=sse_specification)
-
相关文档
该文章对您有帮助吗?