O recurso de índice secundário permite consultar dados com base na chave primária de uma tabela de dados e nas colunas de índice do índice secundário criado para essa tabela. Caso precise usar as colunas de atributo de uma tabela de dados para consultar dados, crie um índice secundário para acelerar as consultas. Ao criar um índice secundário para uma tabela de dados, você pode definir as colunas de índice ou de atributo do índice secundário como as colunas predefinidas especificadas na criação da tabela.
Os índices secundários são classificados em índices secundários globais e índices secundários locais. Para mais informações sobre o recurso de índice secundário, consulte Secondary index.
É possível criar um ou mais índices ao criar uma tabela de dados por meio da operação CreateTable. Para mais informações, consulte Create a table.
Pré-requisitos
Uma instância OTSClient foi inicializada. Para mais informações, consulte Initialize a Tablestore client.
-
Uma tabela de dados com o parâmetro MaxVersions definido como 1 foi criada. O parâmetro TimeToLive da tabela de dados deve atender a uma das seguintes condições:
O parâmetro TimeToLive da tabela de dados está definido como -1, o que significa que os dados nunca expiram.
O parâmetro TimeToLive da tabela de dados está definido com um valor diferente de -1 e as operações de atualização na tabela de dados são proibidas.
Colunas predefinidas foram especificadas para a tabela de dados.
Descrição
Um índice secundário usa um esquema de chave primária diferente, composto por colunas de chave primária e colunas predefinidas de uma tabela de dados, para oferecer dimensões adicionais de consulta. Os índices secundários são classificados em globais e locais, com modos de sincronização de dados e requisitos de chave primária distintos. Para mais informações, consulte Overview.
Chame createIndex para criar um índice secundário para uma tabela de dados existente. Para criar um ou mais índices secundários junto com uma tabela de dados, configure os schemas de índice na requisição createTable. Para mais informações, consulte Create a data table.
public CreateIndexResponse createIndex(CreateIndexRequest createIndexRequest)
throws TableStoreException, ClientException
O código de exemplo a seguir cria o índice secundário global example_global_index para example_table, incluindo os dados existentes.
IndexMeta indexMeta = new IndexMeta("example_global_index");
indexMeta.addPrimaryKeyColumn("category");
indexMeta.addDefinedColumn("status");
CreateIndexRequest request =
new CreateIndexRequest("example_table", indexMeta, true);
client.createIndex(request);
Parâmetros
|
Parâmetro |
Descrição |
|
MainTableName |
O nome da tabela de dados. |
|
IndexMeta |
As informações de schema da tabela de índice, contendo os seguintes itens:
|
|
IncludeBaseData |
Especifica se os dados existentes da tabela de dados devem ser incluídos na tabela de índice. Se o parâmetro IncludeBaseData estiver definido como true, a tabela de índice incluirá os dados existentes da tabela de dados. Se estiver definido como false, os dados existentes não serão incluídos. |
Exemplos
Criar um índice secundário global
O código de exemplo a seguir demonstra como criar um índice secundário global que inclui os dados existentes da tabela de dados. Neste exemplo, as colunas de chave primária da tabela de dados são pk1 e pk2. A coluna de chave primária e a coluna de atributo especificadas para o índice secundário global são definedcol1 e definedcol2, respectivamente. As colunas de chave primária da tabela de índice são compostas por definedcol1, pk1 e pk2. A coluna de atributo da tabela de índice é definedcol2.
func CreateGlobalIndexSample(client *tablestore.TableStoreClient, tableName string) {
// Specify the metadata of the index table.
indexMeta := new(tablestore.IndexMeta)
// Specify the definedcol1 column of the data table as the primary key column of the index table.
indexMeta.AddPrimaryKeyColumn("definedcol1")
// Specify the definedcol2 column of the data table as the attribute column of the index table.
indexMeta.AddDefinedColumn("definedcol2")
// Specify the name of the index table.
indexMeta.IndexName = "<INDEX_NAME>"
indexReq := &tablestore.CreateIndexRequest{
// Specify the data table for which you want to create the index table and apply the settings that you specified for the index table.
MainTableName:tableName,
IndexMeta: indexMeta,
/**
You can set the IncludeBaseData parameter to true to synchronize the existing data of the data table to the index table. This way, you can use the index table to query all data in the data table.
The amount of time required to synchronize the existing data of the data table to the index table varies based on the amount of data in the data table.
*/
IncludeBaseData: true,
}
resp, err := client.CreateIndex(indexReq)
if err != nil {
fmt.Println("Failed to create table with error:", err)
} else {
fmt.Println("Create index finished", resp)
}
}
Criar um índice secundário local
O código de exemplo a seguir demonstra como criar um índice secundário local que inclui os dados existentes da tabela de dados. Neste exemplo, as colunas de chave primária da tabela de dados são pk1 e pk2. As colunas de chave primária especificadas para o índice secundário local são pk1 e definedcol1. A coluna de atributo especificada para o índice secundário local é definedcol2. As colunas de chave primária da tabela de índice são compostas por pk1, definedcol1 e pk2. A coluna de atributo da tabela de índice é definedcol2.
func CreateGLocalIndexSample(client *tablestore.TableStoreClient, tableName string) {
// Specify the metadata of the index table.
indexMeta := new(tablestore.IndexMeta)
// Set the first primary key column of the index table to the first primary key column of the data table.
indexMeta.AddPrimaryKeyColumn("pk1")
// Specify the definedcol1 column of the data table as the primary key column of the index table.
indexMeta.AddPrimaryKeyColumn("definedcol1")
// Specify the definedcol2 column of the data table as the attribute column of the index table.
indexMeta.AddDefinedColumn("definedcol2")
// Set the index type to IT_LOCAL_INDEX.
indexMeta.IndexType = tablestore.IT_LOCAL_INDEX
// Specify the name of the index table.
indexMeta.IndexName = "<INDEX_NAME>"
indexReq := &tablestore.CreateIndexRequest{
// Specify the data table for which you want to create the index table and apply the settings that you specified for the index table.
MainTableName:tableName,
IndexMeta: indexMeta,
/**
You can set the IncludeBaseData parameter to true to synchronize the existing data of the data table to the index table. This way, you can use the index table to query all data in the data table.
The amount of time required to synchronize the existing data of the data table to the index table varies based on the amount of data in the data table.
*/
IncludeBaseData: true,
}
resp, err := client.CreateIndex(indexReq)
if err != nil {
fmt.Println("Failed to create table with error:", err)
} else {
fmt.Println("Create index finished", resp)
}
}
Referências
Após criar um índice secundário, use-o para ler uma única linha de dados ou dados cujos valores de chave primária estejam dentro de um intervalo específico. Para mais informações, consulte Use a secondary index to read data.
Exclua um índice secundário que não seja mais necessário. Para mais informações, consulte Delete a secondary index.