All Products
Search
Document Center

Tablestore:Create a data table

Last Updated:Nov 01, 2025

This topic describes how to use the Tablestore SDK for Java to create a Tablestore data table and configure its parameters.

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 information about the primary key.

    • You can configure one to four primary key columns. By default, data is sorted in ascending order. The first primary key column is the partition key.

    • The supported data types for primary key columns are STRING, INTEGER, and BINARY. You can set an integer-type primary key column that is not a partition key as an auto-increment primary key column.

    definedColumns (optional)

    List<DefinedColumnSchema>

    The information about predefined columns.

    • Predefined columns are attribute columns that you can use to create secondary indexes and search indexes.

    • The supported data types for predefined columns are 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, in seconds.

    • If you set this parameter to -1, the data never expires. Otherwise, the minimum 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 versions.

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

    maxTimeDeviation (optional)

    OptionalValue<Long>

    The max version offset, in seconds. The default value is 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. The default value is true.

    • If you set this parameter to false, you cannot update data using the updateRow method.

  • indexMeta (optional) List<IndexMeta>: The list of secondary indexes. 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.

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

    • When you use a local secondary index, the first primary key column of the index must be the first primary key column of the data table.

    definedColumns (optional)

    List<String>

    The predefined columns of the index.

    • Consists 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. The default value is false.

    expirationTime (optional)

    OptionalValue<Integer>

    The expiration time for stream data. This specifies how long incremental logs are kept. The unit is hours. The maximum value is 168 (7 days).

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

  • enableLocalTxn (optional) OptionalValue<Boolean>: Specifies whether to enable the local transaction feature. The default value is false.

    • This feature is supported only in Java SDK 5.11.0 and later.

    • The local transaction and auto-increment primary key column features cannot be used at the same time. If you configure an auto-increment primary key column, the local transaction feature does not take effect even if it is enabled.

    • If you create a data table without enabling the local transaction feature and want to use this feature later, submit a ticket to request the feature.

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

    Important

    You can enable and configure the data encryption feature only when you create a data table. You cannot disable the feature after the table is created.

    Name

    Type

    Description

    enable (required)

    boolean

    Specifies whether to enable the data encryption feature. The default value is false.

    keyType (optional)

    OptionalValue<SSEKeyType>

    The encryption type. SSEKeyType includes the following types.

    • 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. The unit is capacity unit (CU). The default value is 0. This parameter applies only to compute-optimized instances in CU mode.

Sample code

Basic usage

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

After you create a data table, you must wait for the table to load before you can perform data operations. This process typically takes a few seconds. If you do not wait, the operations fail.
Important

You cannot change the encryption method after you create a data table. 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

You can add primary keys using the addPrimaryKeyColumn or addPrimaryKeyColumns method. The following example uses the addPrimaryKeyColumn method.

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

Add predefined columns

You can add predefined columns using the addDefinedColumn or addDefinedColumns method. The following example uses the addDefinedColumn method.

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

Set the max version offset

You can set the max version offset using the setMaxTimeDeviation method.

tableOptions.setMaxTimeDeviation(86400);

Set whether to allow updates

You can use the setAllowUpdate method to specify whether to allow data updates in the table.

tableOptions.setAllowUpdate(false);

Add a secondary index

You can add a secondary index by specifying the indexMetas parameter when you create 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

You can set stream information using the setStreamSpecification method of the request.

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

Enable local transactions

You can enable local transactions using the setLocalTxnEnabled method of the request.

request.setLocalTxnEnabled(true);

Set the reserved read/write throughput

You can set the reserved read/write throughput for the table 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

You can set the data table encryption method 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 you run the code, you must 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