全部產品
Search
文件中心

Tablestore:建立資料表

更新時間:Nov 01, 2025

介紹通過Java SDK建立Table Store資料表的方法和參數配置。

方法說明

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及以上版本支援此功能。

    • 局部事務功能和主鍵列自增無法同時使用,如果配置了主鍵列自增,局部事務功能即使設定開啟也不會生效。

    • 建立資料表時未開啟局部事務功能,後續需要使用該功能時,請提交工單進行申請

  • 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的資料表,包含1個String類型的主鍵。

建立資料表後,需等待資料表載入完成(通常需要幾秒鐘)後再進行資料操作,否則操作會失敗。
重要

建立資料表後,資料表的加密方式無法修改,如需建立加密表,請參見設定資料表加密

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加密

    說明

    運行代碼前需要擷取使用者主要金鑰ID和RAM角色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);

相關文檔