All Products
Search
Document Center

Tablestore:Create a data table

Last Updated:Apr 02, 2026

Call the createTable method to create a data table in Tablestore and configure its schema, options, indexes, and encryption settings.

Method

public CreateTableResponse createTable(CreateTableRequest createTableRequest) throws TableStoreException, ClientException

Parameters of CreateTableRequest

  • tableMeta (required) TableMeta: The schema of the table. This parameter contains the following parameters.

    Name

    Type

    Description

    tableName (required)

    String

    The name of the data table.

    primaryKey (required)

    List<PrimaryKeySchema>

    The primary key schema of the data table.

    • Supports one to four primary key columns. Data is sorted in ascending order by default. The first primary key column serves as the partition key.

    • Supported data types: STRING, INTEGER, and BINARY. An integer-type primary key column that is not a partition key can be set as an auto-increment primary key column.

    definedColumns (optional)

    List<DefinedColumnSchema>

    The predefined columns of the data table.

    • Predefined columns are attribute columns used to create secondary indexes and search indexes.

    • Supported data types: STRING, INTEGER, BINARY, DOUBLE, and BOOLEAN.

  • tableOptions (required) TableOptions: The configuration of the data table. This parameter contains the following parameters.

    Name

    Type

    Description

    timeToLive (required)

    OptionalValue<Integer>

    The time to live (TTL) of data. Unit: seconds.

    • Set this parameter to -1 to disable expiration. The minimum valid value is 86400 (one day). Data that exceeds its TTL is automatically purged.

    • To use search indexes or secondary indexes, set the TTL to -1 or set the allowUpdate parameter to false.

    maxVersions (required)

    OptionalValue<Integer>

    The maximum number of data versions to retain.

    • To use a search index or secondary index, set this parameter to 1.

    maxTimeDeviation (optional)

    OptionalValue<Long>

    The max version offset. Unit: seconds. Default value: 86400 (one day).

    • The difference between the timestamp of the written data and the current system time must be within the max version offset. Otherwise, the write operation fails.

    • The valid version range for attribute column data is [max(Data write time - Max version offset, Data write time - Time to live), Data write time + Max version offset).

    allowUpdate (optional)

    OptionalValue<Boolean>

    Specifies whether to allow updates. Default value: true.

    • When set to false, data cannot be updated through the updateRow method.

  • indexMeta (optional) List<IndexMeta>: The secondary indexes to create with the data table. Each index contains the following parameters.

    Name

    Type

    Description

    indexName (required)

    String

    The name of the index.

    primaryKey (required)

    List<String>

    The primary key columns of the index.

    • Composed of primary key columns and predefined columns from the data table.

    • For a local secondary index, the first primary key column of the index must match the first primary key column of the data table.

    definedColumns (optional)

    List<String>

    The predefined columns of the index.

    • Composed of predefined columns from the data table.

    indexType (optional)

    IndexType

    The type of the index. Valid values:

    • IT_GLOBAL_INDEX (default): global secondary index.

    • IT_LOCAL_INDEX: local secondary index.

    indexUpdateMode (optional)

    IndexUpdateMode

    The update mode of the index. Valid values:

    • IUM_ASYNC_INDEX (default): asynchronous update. The update mode for a global secondary index must be asynchronous.

    • IUM_SYNC_INDEX: synchronous update. The update mode for a local secondary index must be synchronous.

  • streamSpecification (optional) OptionalValue<StreamSpecification>: The configuration of the stream. This parameter contains the following parameters.

    Name

    Type

    Description

    enableStream (required)

    boolean

    Specifies whether to enable the stream. Default value: false.

    expirationTime (optional)

    OptionalValue<Integer>

    The retention period for incremental log data in the stream. Unit: hours. Maximum value: 168 (7 days).

    • The expirationTime parameter is required if enableStream is set to true.

  • enableLocalTxn (optional) OptionalValue<Boolean>: Specifies whether to enable local transactions. Default value: false.

    • Supported only in Java SDK 5.11.0 and later.

    • Local transactions and auto-increment primary key columns are mutually exclusive. If an auto-increment primary key column is configured, local transactions do not take effect even when enabled.

    • To enable local transactions on an existing data table, submit a ticket to request the feature.

  • sseSpecification (optional) OptionalValue<SSESpecification>: The data encryption settings. The following table describes the sseSpecification parameters.

    Important

    Data encryption can only be enabled and configured during table creation. It cannot be disabled after the table is created.

    Name

    Type

    Description

    enable (required)

    boolean

    Specifies whether to enable data encryption. Default value: false.

    keyType (optional)

    OptionalValue<SSEKeyType>

    The encryption type. Valid values:

    • SSE_KMS_SERVICE: KMS encryption.

    • SSE_BYOK: Bring-Your-Own-Key (BYOK) encryption.

    keyId (optional)

    OptionalValue<String>

    The ID of the customer master key (CMK). This parameter is required only if keyType is set to SSE_BYOK.

    roleArn (optional)

    OptionalValue<String>

    The Alibaba Cloud Resource Name (ARN) of the Resource Access Management (RAM) role. This parameter is required only if keyType is set to SSE_BYOK.

  • reservedThroughput (optional) ReservedThroughput: The reserved read/write throughput. Unit: capacity unit (CU). Default value: 0. Applies only to compute-optimized instances in CU mode.

Sample code

Basic usage

The following example creates a data table named test_table with one primary key column of the String type.

After creating a data table, wait for the table to load before performing data operations. Loading typically takes a few seconds.
Important

The encryption method cannot be changed after table creation. To create an encrypted table, see Set data table encryption.

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) {

        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations based on your instance information.
        final String region = "yourRegion"; // The ID of the region where your instance is located. Example: "cn-hangzhou".
        final String instanceName = "yourInstanceName"; // The name of your instance.
        final String endpoint = "yourEndpoint"; // The endpoint of your instance.

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

            // Create a client instance.
            client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // Define the table schema.
            TableMeta tableMeta = new TableMeta("test_table"); // TODO: Modify the table name as needed.
            // You must add at least one primary key column to create a table.
            tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema("id", PrimaryKeyType.STRING)); // TODO: Modify the table primary key as needed.

            // Configure the table.
            TableOptions tableOptions = new TableOptions();
            // You must specify the max versions when you create a data table.
            tableOptions.setMaxVersions(1);
            // You must specify the time to live (TTL) when you create a data table. A value of -1 means the data never expires.
            tableOptions.setTimeToLive(-1);

            // Create and send the request.
            CreateTableRequest request = new CreateTableRequest(tableMeta, tableOptions);
            client.createTable(request);

            System.out.println("The data table is created.");
        } catch (Exception e) {
            System.err.println("Failed to create the data table. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Add primary keys

Add primary keys by using the addPrimaryKeyColumn or addPrimaryKeyColumns method. The following example uses addPrimaryKeyColumn.

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

Add predefined columns

Add predefined columns by using the addDefinedColumn or addDefinedColumns method. The following example uses addDefinedColumn.

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

Set the max version offset

Set the max version offset by using the setMaxTimeDeviation method.

tableOptions.setMaxTimeDeviation(86400);

Configure update permissions

Use the setAllowUpdate method to specify whether to allow data updates in the table.

tableOptions.setAllowUpdate(false);

Add a secondary index

Add a secondary index by specifying the indexMetas parameter when creating the request.

// Create a list of secondary indexes.
ArrayList<IndexMeta> indexMetas = new ArrayList<IndexMeta>();
// Create a secondary index.
IndexMeta indexMeta = new IndexMeta("test_table_idx");
// Set the primary key of the index.
indexMeta.addPrimaryKeyColumn("id");
// To add more primary key columns, first define the corresponding primary keys or predefined columns in the data table.
// indexMeta.addPrimaryKeyColumn("additional_column");

// Set the index type.
indexMeta.setIndexType(IndexType.IT_LOCAL_INDEX);
// Set the index update mode.
indexMeta.setIndexUpdateMode(IndexUpdateMode.IUM_SYNC_INDEX);
// Add the secondary index.
indexMetas.add(indexMeta);

// Create the request.
CreateTableRequest request = new CreateTableRequest(tableMeta, tableOptions, indexMetas);

Set stream information

Set stream information by using the setStreamSpecification method of the request.

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

Enable local transactions

Enable local transactions by using the setLocalTxnEnabled method of the request.

request.setLocalTxnEnabled(true);

Set the reserved read/write throughput

Set the reserved read/write throughput by using the setReservedThroughput method of the request.

// Set the reserved read throughput to 10000 and the reserved write throughput to 5000.
ReservedThroughput reservedThroughput = new ReservedThroughput(10000, 5000);
request.setReservedThroughput(reservedThroughput);

Set data table encryption

Set the encryption method by using the setSseSpecification method of the request.

  • KMS encryption

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

    Note

    Before running the code, obtain the customer master key (CMK) ID and the RAM role ARN. For more information, see BYOK encryption.

    String keyId = "key-hzz6*****************";
    String roleArn = "acs:ram::1705************:role/tabletorebyok";
    SSESpecification sseSpecification = new SSESpecification(true, SSEKeyType.SSE_BYOK, keyId, roleArn);
    request.setSseSpecification(sseSpecification);

References