All Products
Search
Document Center

Tablestore:Create a data table

Last Updated:Jul 31, 2024

This topic describes how to create a data table by calling the CreateTable operation. When you call the CreateTable operation to create a data table, you must specify schema information and configuration information for the data table. If the data table belongs to a high-performance instance, you can configure the reserved read throughput and the reserved write throughput based on your business requirements. You can create one or more index tables when you create a data table.

Usage notes

  • It takes several seconds to load a data table after the data table is created. During this period, all read and write operations on the data table fail. Perform operations on the data table after the data table is loaded.

  • You must specify the primary key when you create a data table. A primary key consists of one to four primary key columns. Specify a name and data type for each primary key column.

  • In system design scenarios that require an auto-increment primary key column, such as item IDs on e-commerce websites, user IDs on large websites, post IDs in forums, and message IDs in chat tools, you can specify an auto-increment primary key column when you create a data table. For more information, see Configure an auto-increment primary key column.

Prerequisites

API operation

// Description: Create a data table based on the specified table schema. 
// request is an instance of the CreateTableRequest class and contains TableMeta, TableOption, and ReservedThroughput. 
// For more information, see the documentation of the TableMeta class. 
// After you create a data table, several seconds are required to load the partitions in the data table. You can perform operations on the data table only after the partitions are loaded. 
// Response: CreateTableResponse
CreateTable(request *CreateTableRequest) (*CreateTableResponse, error)       

Parameters

Configure the parameters in the code based on the parameters described in the following table and the "Request syntax" section of the CreateTable topic.

Parameter

Required

Description

TableMeta

Yes

The schema of the data table. This parameter includes the following configuration items:

  • TableName: required. The name of the data table.

  • PrimaryKey: optional. The primary key of the data table. For more information, see Primary keys and attributes.

    Note

    You do not need to specify the schema for attribute columns. Different rows in a Tablestore table can have different attribute columns. You can specify the names of attribute columns when you write data to a data table.

    • The primary key of a data table consists of one to four primary key columns. Primary key columns are sorted in the order in which they are added. For example, PRIMARY KEY (A, B, C) and PRIMARY KEY (A, C, B) have different schemas. Tablestore sorts rows based on the values of all primary key columns.

    • The first primary key column is the partition key. Data that has the same partition key is stored in the same partition. We recommend that you keep the size of data with the same partition key less than or equal to 10 GB. Otherwise, a single partition may be too large to split. We also recommend that you evenly distribute read/write operations among different partition keys to facilitate load balancing.

  • DefinedColumns: optional. The names and types of the predefined columns. You cannot specify primary key columns as predefined columns. You can use the predefined columns of a data table as the attribute columns or index columns of an index table that is created for the data table.

    Important

    If you want to create a data table and a secondary index at the same time, you must specify this configuration item.

TableOption

No

Optional. The configuration information about the data table. For more information, see Data versions and TTL.

The configuration information includes the following items:

  • TimeToAlive: the period for which data in the table can be retained. This period is the validity period of data. If the retention period exceeds the value of TimeToAlive, Tablestore automatically deletes expired data.

    The value of this parameter must be greater than or equal to 86400. A value of 86400 indicates one day. You can also set this parameter to -1.

    If you set the timeToLive parameter to -1 for the data table, the data in the data table never expires. After the data table is created, you can call the UpdateTable operation to modify the value of the timeToLive parameter.

    Unit: seconds.

    Important

    If you want to create an index table for the data table, the timeToLive parameter must meet one of the following requirements:

    • The timeToLive parameter of the data table is set to -1, which means that data in the data table never expires.

    • The timeToLive parameter of the data table is set to a value other than -1 and update operations on the data table are prohibited.

  • MaxVersion: the maximum number of versions of data that can be retained for a single attribute column. If the number of data versions in an attribute column exceeds the value of MaxVersion, the system deletes data of earlier versions.

    When you create a data table, you can set this parameter based on your business requirements. After the data table is created, you can call the UpdateTable operation to modify the value of the maxVersions parameter.

    Important

    If you want to create an index table for the data table, you must set the maxVersions parameter to 1.

  • DeviationCellVersionInSec: the max version offset, which is the maximum difference between the current system time and the timestamp of the written data. The difference between the version number and the time at which the data is written must be less than or equal to the value of DeviationCellVersionInSec. Otherwise, an error occurs when the data is written.

    The valid version range of data in an attribute column is calculated by using the following formula: Valid version range = [max{Data written time - Max version offset, Data written time - TTL value}, Data written time + Max version offset).

    When you create a data table, Tablestore uses the default value of 86400 if you do not specify a max version offset. After the data table is created, you can call the UpdateTable operation to modify the value of the maxTimeDeviation parameter.

ReservedThroughput

No

Optional. The reserved read throughput and the reserved write throughput of the data table.

Important

You can set the reserved read throughput and the reserved write throughput only to 0 for data tables in capacity instances. Reserved throughput does not apply to the instances.

The default value 0 indicates that you are charged for all throughput on a pay-as-you-go basis.

Unit: capacity unit (CU).

  • If you set the reserved read throughput and reserved write throughput to a value that is greater than 0 for a data table, Tablestore reserves related resources for the data table. After you create the data table, you are charged for the reserved throughput resources. You are charged for additional throughput on a pay-as-you-go basis. For more information, see Billing overview.

  • If you set the reserved read throughput and reserved write throughput to 0, Tablestore does not reserve related resources for the data table.

IndexMeta

No

Optional. The schema information about the index table. This parameter includes the following configuration items:

Important

If you want to create a data table and a secondary index at the same time, you must configure this parameter.

  • IndexName: the name of the index table.

  • PrimaryKey: the primary key of the index table. The primary key is a combination of all primary key columns and a random number of predefined columns of the data table.

    If you want to create a local secondary index, the first primary key column of the index table must be the same as the first primary key column of the data table.

  • DefinedColumns: the attribute columns of the index table. The attribute columns are a combination of predefined columns of the data table.

  • IndexType: the type of the index table. Valid values: IT_GLOBAL_INDEX and IT_LOCAL_INDEX.

    • If you do not configure the IndexType field or if you set the IndexType field to IT_GLOBAL_INDEX, a global secondary index is created.

      Tablestore automatically synchronizes the data from the indexed columns and primary key columns of the data table to the columns of the index table in asynchronous mode. The synchronization latency is within milliseconds.

    • If you set the IndexType field to IT_LOCAL_INDEX, a local secondary index is created.

      Tablestore automatically synchronizes the data from the indexed columns and primary key columns of the data table to the columns of the index table in synchronous mode. You can query the data from the index table immediately after the data is written to the data table.

Examples

Create a data table without an index table

The following sample code provides an example on how to create a data table that contains two primary key columns. In this example, the two primary key columns are named pk0 of the Integer type and pk1 of the String type. Up to three versions of data can be retained for each attribute column and data in the data table never expires.

func CreateTableSample(client *tablestore.TableStoreClient, tableName string) {
    createTableRequest := new(tablestore.CreateTableRequest)
    // Create a schema for primary key columns, which includes the number, names, and types of the primary key columns. 
    // The first primary key column is named pk0 and requires an Integer value. The first primary key column is also the partition key. 
    // The second primary key column is named pk1 and requires a String value. 
    tableMeta := new(tablestore.TableMeta)
    tableMeta.TableName = tableName
    tableMeta.AddPrimaryKeyColumn("pk0", tablestore.PrimaryKeyType_INTEGER)
    tableMeta.AddPrimaryKeyColumn("pk1", tablestore.PrimaryKeyType_STRING)
    tableOption := new(tablestore.TableOption)
    tableOption.TimeToAlive = -1
    tableOption.MaxVersion = 3
    reservedThroughput := new(tablestore.ReservedThroughput)
    reservedThroughput.Readcap = 0
    reservedThroughput.Writecap = 0
    createTableRequest.TableMeta = tableMeta
    createTableRequest.TableOption = tableOption
    createTableRequest.ReservedThroughput = reservedThroughput
    _, err := client.CreateTable(createTableRequest)
    if (err != nil) {
        fmt.Println("Failed to create table with error:", err)
    } else {
        fmt.Println("Create table finished")
    }
}

Create a data table and a global secondary index

The following sample code provides an example on how to create a data table and configure a global secondary index for the data table at the same time. The data table contains two primary key columns: the pk1 column of the STRING type and the pk2 column of the INTEGER type. The data table also contains two predefined columns: the defcol1 column of the STRING type and the defcol2 column of the INTEGER type. Only the latest version of data is retained for each attribute column, and the data never expires. The primary key columns of the global secondary index are the defcol1, pk1, and pk2 columns. The attribute column of the global secondary index is the defcol2 column.

func CreateTableWithGlobalIndexSample(client *tablestore.TableStoreClient, tableName string) {
    createTableRequest := new(tablestore.CreateTableRequest)

    tableMeta := new(tablestore.TableMeta)
    tableMeta.TableName = tableName
    tableMeta.AddPrimaryKeyColumn("pk1", tablestore.PrimaryKeyType_STRING)
    tableMeta.AddPrimaryKeyColumn("pk2", tablestore.PrimaryKeyType_INTEGER)
    tableMeta.AddDefinedColumn("defcol1", tablestore.DefinedColumn_STRING)
    tableMeta.AddDefinedColumn("defcol2", tablestore.DefinedColumn_INTEGER)

    indexMeta := new(tablestore.IndexMeta) // Create IndexMeta for the index table. 
    indexMeta.AddPrimaryKeyColumn("defcol1") // Specify a primary key column for the index table. Specify the definedcol1 column of the data table as a primary key column of the index table. 
    indexMeta.AddDefinedColumn("defcol2") // Specify attribute columns for the index table. Specify the definedcol2 column of the data table as an attribute column of the index table. 
    indexMeta.IndexName = "indexSample"

    tableOption := new(tablestore.TableOption)
    tableOption.TimeToAlive = -1 // Specify the validity period of data. A value of -1 specifies that the data never expires. Unit: seconds. You must set the TimeToAlive parameter to -1 for a data table for which index tables are created. 
    tableOption.MaxVersion = 1 // Specify the maximum number of versions that can be retained for each attribute column. A value of 1 specifies that only the latest version is retained for each attribute column. You must set the MaxVersion parameter to 1 for a data table for which index tables are created. 
    reservedThroughput := new(tablestore.ReservedThroughput)

    createTableRequest.TableMeta = tableMeta
    createTableRequest.TableOption = tableOption
    createTableRequest.ReservedThroughput = reservedThroughput
    createTableRequest.AddIndexMeta(indexMeta)

    _, err := client.CreateTable(createTableRequest)
    if err != nil {
        fmt.Println("Failed to create table with error:", err)
    } else {
        fmt.Println("Create table finished")
    }
}

Create a data table and a local secondary index

The following sample code provides an example on how to create a data table and configure a local secondary index for the data table at the same time. The data table contains two primary key columns: the pk1 column of the STRING type and the pk2 column of the INTEGER type. The data table also contains two predefined columns: the defcol1 column of the STRING type and the defcol2 column of the INTEGER type. Only the latest version of data is retained for each attribute column, and the data never expires. The primary key columns of the local secondary index are the defcol1, pk1, and pk2 columns. The attribute column of the local secondary index is the defcol2 column.

func CreateTableWithLocalIndexSample(client *tablestore.TableStoreClient, tableName string) {
    createTableRequest := new(tablestore.CreateTableRequest)

    tableMeta := new(tablestore.TableMeta)
    tableMeta.TableName = tableName
    tableMeta.AddPrimaryKeyColumn("pk1", tablestore.PrimaryKeyType_STRING)
    tableMeta.AddPrimaryKeyColumn("pk2", tablestore.PrimaryKeyType_INTEGER)
    tableMeta.AddDefinedColumn("defcol1", tablestore.DefinedColumn_STRING)
    tableMeta.AddDefinedColumn("defcol2", tablestore.DefinedColumn_INTEGER)

    indexMeta := new(tablestore.IndexMeta) // Create IndexMeta for the index table. 
    indexMeta.IndexType = tablestore.IT_LOCAL_INDEX // Set the IndexType parameter to IT_LOCAL_INDEX to create a local secondary index. 

    indexMeta.AddPrimaryKeyColumn("pk1") // Specify a primary key column for the index table. The first primary key column of the index table must be the same as the first primary key column of the data table. 
    indexMeta.AddPrimaryKeyColumn("defcol1") // Specify a primary key column for the index table. Specify the definedcol1 column of the data table as a primary key column of the index table. 
    indexMeta.AddDefinedColumn("defcol2") // Specify attribute columns for the index table. Specify the definedcol2 column of the data table as an attribute column of the index table. 
    indexMeta.IndexName = "indexSample"

    tableOption := new(tablestore.TableOption)
    tableOption.TimeToAlive = -1 // Specify the validity period of data. A value of -1 specifies that the data never expires. Unit: seconds. You must set the TimeToAlive parameter to -1 for a data table for which index tables are created. 
    tableOption.MaxVersion = 1 // Specify the maximum number of versions that can be retained for each attribute column. A value of 1 specifies that only the latest version is retained for each attribute column. You must set the MaxVersion parameter to 1 for a data table for which index tables are created. 
    reservedThroughput := new(tablestore.ReservedThroughput)

    createTableRequest.TableMeta = tableMeta
    createTableRequest.TableOption = tableOption
    createTableRequest.ReservedThroughput = reservedThroughput
    createTableRequest.AddIndexMeta(indexMeta)

    _, err := client.CreateTable(createTableRequest)
    if err != nil {
        fmt.Println("Failed to create table with error:", err)
    } else {
        fmt.Println("Create table finished")
    }
}

References

  • For information about the API operation that you can call to create a data table, see CreateTable. For the detailed sample code, visit CreateTable@GitHub.

  • You can call API operations to read and write data in a data table. For more information, see Basic operations on data.

  • You can update a table to modify the information about the table, such as the time to live (TTL) and max versions. For more information, see Update a table.

  • After you enable the local transaction feature for a data table, you can create a local transaction and perform read and write operations on the data in the local transaction. For more information, see Local transaction.

  • You can query the names of tables to view all existing tables in an instance. For more information, see Query the names of tables.

  • You can query the description of a table to view the configuration information about the table, such as the max versions and TTL. For more information, see Query the description of a table.

  • If you want to use a secondary index to accelerate data queries and no predefined columns are specified when the data table is created, you can add or remove predefined columns to the data table after the data table is created. For more information, see Add or remove predefined columns.

  • You can delete a data table that you no longer require. For more information, see Delete tables.