创建数据表

介绍通过Java SDK创建表格存储数据表的方法和参数配置。

方法说明

public CreateTableResponse createTable(CreateTableRequest createTableRequest) throws TableStoreException, ClientException

点击查看CreateTableRequest参数说明

  • tableMeta(必选)TableMeta:表结构信息,包含以下参数。

    名称

    类型

    说明

    tableName(必选)

    String

    数据表名称。

    primaryKey(必选)

    List<PrimaryKeySchema>

    主键信息。

    • 支持设置1~4个主键列,默认按升序排序,第一个主键列作为分区键。

    • 主键数据类型支持STRINGINTEGERBINARY,非分区键中的整型主键列可设置主键列自增

    definedColumns(可选)

    List<DefinedColumnSchema>

    预定义列信息。

    • 预先定义的属性列,用于创建二级索引多元索引

    • 预定义列数据类型支持STRINGINTEGERBINARYDOUBLEBOOLEAN

  • tableOptions(必选)TableOptions:配置信息,包含以下参数。

    名称

    类型

    说明

    timeToLive(必选)

    OptionalValue<Integer>

    数据生命周期,单位为秒。

    • 设置为-1时数据永不过期,否则最低取值为86400(1天),超出生命周期的数据将自动清除。

    • 使用多元索引或二级索引功能时,必须将数据生命周期设置为-1,或将allowUpdate参数设置为false

    maxVersions(必选)

    OptionalValue<Integer>

    最大版本数。

    • 使用多元索引或二级索引时,最大版本数必须设置为1。

    maxTimeDeviation(可选)

    OptionalValue<Long>

    有效版本偏差,单位为秒,默认值为86400(1天)。

    • 写入数据的时间戳与系统当前时间的差值必须在有效版本偏差范围内,否则写入操作失败。

    • 属性列数据的有效版本范围为[max(数据写入时间-有效版本偏差, 数据写入时间-数据生命周期), 数据写入时间+有效版本偏差)

    allowUpdate(可选)

    OptionalValue<Boolean>

    是否允许更新,默认值为true

    • 设置为false时,无法通过updateRow方法更新数据。

  • indexMeta(可选)List<IndexMeta>:二级索引列表,每个索引包含以下参数。

    名称

    类型

    说明

    indexName(必选)

    String

    索引名称。

    primaryKey(必选)

    List<String>

    索引的主键列。

    • 由数据表的主键列和预定义列组成。

    • 使用本地二级索引时,索引第一个主键列必须是数据表的第一个主键列。

    definedColumns(可选)

    List<String>

    索引的预定义列。

    • 由数据表的预定义列组成。

    indexType(可选)

    IndexType

    索引类型,取值范围:

    • IT_GLOBAL_INDEX(默认值):全局二级索引。

    • IT_LOCAL_INDEX:本地二级索引。

    indexUpdateMode(可选)

    IndexUpdateMode

    索引更新模式,取值范围:

    • IUM_ASYNC_INDEX(默认值):异步更新。全局二级索引的更新模式必须设置为异步更新。

    • IUM_SYNC_INDEX:同步更新。本地二级索引的更新模式必须设置为同步更新。

  • streamSpecification(可选)OptionalValue<StreamSpecification>:Stream配置信息,包含以下参数。

    名称

    类型

    说明

    enableStream(必选)

    boolean

    是否开启Stream,默认值为false

    expirationTime(可选)

    OptionalValue<Integer>

    Stream过期时间,表示增量日志过期时长。单位为小时,最大值为168(7天)。

    • enableStream设置为true时,必须设置expirationTime

  • enableLocalTxn(可选)OptionalValue<Boolean>:是否开启局部事务,默认值为false

    • Java SDK 5.11.0及以上版本支持此功能。

    • 局部事务功能和主键列自增无法同时使用,如果配置了主键列自增,局部事务功能即使设置开启也不会生效。

    • 创建数据表时未开启局部事务功能,后续需要使用该功能时,请加入钉钉群 23307953(表格存储技术交流群-3)进行咨询

  • sseSpecification(可选)OptionalValue<SSESpecification>数据加密设置,包含以下参数。

    重要

    数据加密功能仅支持在创建数据表时开启和配置,创建完成后无法关闭加密功能。

    名称

    类型

    说明

    enable(必选)

    boolean

    是否开启数据加密功能,默认值为false

    keyType(可选)

    OptionalValue<SSEKeyType>

    加密类型。SSEKeyType包含以下类型。

    • SSE_KMS_SERVICE:KMS加密。

    • SSE_BYOK:BYOK加密。

    keyId(可选)

    OptionalValue<String>

    用户主密钥ID。仅当keyTypeSSE_BYOK时需设置此参数。

    roleArn(可选)

    OptionalValue<String>

    RAM角色ARN。仅当keyTypeSSE_BYOK时需设置此参数。

  • reservedThroughput(可选)ReservedThroughput预留读写吞吐量,单位为CU,默认值为0,仅CU模式的高性能型实例可以设置且有效。

示例代码

基本用法

以下示例创建名为test_table的数据表,包含1String类型的主键。

创建数据表后,需等待数据表加载完成(通常需要几秒钟)后再进行数据操作,否则操作会失败。
重要

创建数据表后,数据表的加密方式无法修改,如需创建加密表,请参见设置数据表加密

package org.example.ots;

import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.core.auth.V4Credentials;
import com.alicloud.openservices.tablestore.model.*;

public class CreateTable {
    
    public static void main(String[] args) {

        // 从环境变量中获取访问凭证(需要配置TABLESTORE_ACCESS_KEY_ID和TABLESTORE_ACCESS_KEY_SECRET)
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: 根据实例信息修改以下配置
        final String region = "yourRegion"; // 填写实例所属的地域ID,例如 "cn-hangzhou"
        final String instanceName = "yourInstanceName"; // 填写实例名称
        final String endpoint = "yourEndpoint"; // 填写实例访问地址

        SyncClient client = null;
        try {
            // 构造凭证
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // 创建客户端实例
            client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // 构造数据表的结构信息
            TableMeta tableMeta = new TableMeta("test_table"); // TODO: 根据需求修改数据表名称
            // 创建数据表至少需要添加一个主键
            tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema("id", PrimaryKeyType.STRING)); // TODO: 根据需求修改数据表主键

            // 构造数据表的配置信息
            TableOptions tableOptions = new TableOptions();
            // 创建数据表时必须指定最大版本数
            tableOptions.setMaxVersions(1);
            // 创建数据表时必须指定数据生命周期,-1表示数据永不过期
            tableOptions.setTimeToLive(-1);

            // 构造Request并发起请求
            CreateTableRequest request = new CreateTableRequest(tableMeta, tableOptions);
            client.createTable(request);

            System.out.println("创建数据表成功");
        } catch (Exception e) {
            System.err.println("创建数据表失败,详细信息如下:");
            e.printStackTrace();
        } finally {
            // 关闭客户端
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

添加主键

通过addPrimaryKeyColumnaddPrimaryKeyColumns方法添加主键,以addPrimaryKeyColumn为例。

tableMeta.addPrimaryKeyColumn("name", PrimaryKeyType.STRING);

添加预定义列

通过addDefinedColumnaddDefinedColumns方法添加预定义列,以addDefinedColumn为例。

tableMeta.addDefinedColumn("age", DefinedColumnType.INTEGER);

设置有效版本偏差

通过setMaxTimeDeviation方法设置有效版本偏差。

tableOptions.setMaxTimeDeviation(86400);

设置是否允许更新

通过setAllowUpdate方法设置是否允许更新表数据。

tableOptions.setAllowUpdate(false);

添加二级索引

通过在构造请求时指定indexMetas参数添加二级索引。

// 构造二级索引列表
ArrayList<IndexMeta> indexMetas = new ArrayList<IndexMeta>();
// 构造二级索引
IndexMeta indexMeta = new IndexMeta("test_table_idx");
// 设置索引主键
indexMeta.addPrimaryKeyColumn("id");
// 如果需要添加更多主键列,请先在数据表中定义对应的主键或预定义列
// indexMeta.addPrimaryKeyColumn("additional_column");

// 设置索引类型
indexMeta.setIndexType(IndexType.IT_LOCAL_INDEX);
// 设置索引更新模式
indexMeta.setIndexUpdateMode(IndexUpdateMode.IUM_SYNC_INDEX);
// 添加二级索引
indexMetas.add(indexMeta);

// 构造Request请求
CreateTableRequest request = new CreateTableRequest(tableMeta, tableOptions, indexMetas);

设置Stream信息

通过请求的setStreamSpecification方法设置Stream信息。

StreamSpecification streamSpecification = new StreamSpecification(true, 168);
request.setStreamSpecification(streamSpecification);

开启局部事务

通过请求的setLocalTxnEnabled方法开启局部事务。

request.setLocalTxnEnabled(true);

设置预留读写吞吐量

通过请求的setReservedThroughput方法设置表的预留读写吞吐量。

// 设置预留读吞吐量为10000,预留写吞吐量为5000
ReservedThroughput reservedThroughput = new ReservedThroughput(10000, 5000);
request.setReservedThroughput(reservedThroughput);

设置数据表加密

通过请求的setSseSpecification方法设置数据表加密方式。

  • KMS密钥加密

    SSESpecification sseSpecification = new SSESpecification(true, SSEKeyType.SSE_KMS_SERVICE);
    request.setSseSpecification(sseSpecification);
  • BYOK加密

    说明

    运行代码前需要获取用户主密钥IDRAM角色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);

相关文档