Chame o método createTable para criar uma tabela de dados no Tablestore e configurar seu esquema, opções, índices e definições de criptografia.
Método
public CreateTableResponse createTable(CreateTableRequest createTableRequest) throws TableStoreException, ClientException
Código de exemplo
Uso básico
O exemplo a seguir cria uma tabela de dados chamada test_table com uma coluna de chave primária do tipo String.
Após criar uma tabela de dados, aguarde o carregamento da tabela antes de executar operações de dados. O carregamento geralmente leva alguns segundos.
Não é possível alterar o método de criptografia após a criação da tabela. Para criar uma tabela criptografada, consulte Definir criptografia da tabela de dados.
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();
}
}
}
}
Adicionar chaves primárias
Adicione chaves primárias usando o método addPrimaryKeyColumn ou addPrimaryKeyColumns. O exemplo a seguir usa addPrimaryKeyColumn.
tableMeta.addPrimaryKeyColumn("name", PrimaryKeyType.STRING);
Adicionar colunas predefinidas
Adicione colunas predefinidas usando o método addDefinedColumn ou addDefinedColumns. O exemplo a seguir usa addDefinedColumn.
tableMeta.addDefinedColumn("age", DefinedColumnType.INTEGER);
Definir o desvio máximo de versão
Defina o desvio máximo de versão usando o método setMaxTimeDeviation.
tableOptions.setMaxTimeDeviation(86400);
Configurar permissões de atualização
Use o método setAllowUpdate para especificar se as atualizações de dados na tabela são permitidas.
tableOptions.setAllowUpdate(false);
Adicionar um índice secundário
Adicione um índice secundário especificando o parâmetro indexMetas ao criar a solicitação.
// 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);
Definir informações do stream
Defina as informações do stream usando o método setStreamSpecification da solicitação.
StreamSpecification streamSpecification = new StreamSpecification(true, 168);
request.setStreamSpecification(streamSpecification);
Ativar transações locais
Ative transações locais usando o método setLocalTxnEnabled da solicitação.
request.setLocalTxnEnabled(true);
Definir o throughput reservado de leitura/gravação
Defina o throughput reservado de leitura/gravação usando o método setReservedThroughput da solicitação.
// Set the reserved read throughput to 10000 and the reserved write throughput to 5000.
ReservedThroughput reservedThroughput = new ReservedThroughput(10000, 5000);
request.setReservedThroughput(reservedThroughput);
Definir criptografia da tabela de dados
Defina o método de criptografia usando o método setSseSpecification da solicitação.
-
Criptografia KMS
SSESpecification sseSpecification = new SSESpecification(true, SSEKeyType.SSE_KMS_SERVICE); request.setSseSpecification(sseSpecification); -
Criptografia BYOK
NotaAntes de executar o código, obtenha o ID da chave mestra do cliente (CMK) e o ARN da função RAM. Para mais informações, consulte Criptografia 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);