Tablestore permite ler uma única linha de dados ou dados cujos valores de chave primária estejam dentro de um intervalo específico em uma tabela de índice. Se a tabela de índice contiver as colunas de atributo desejadas, leia diretamente a tabela de índice para obter os dados. Caso contrário, consulte os dados na tabela de dados para a qual o índice foi criado.
Os índices secundários dividem-se em globais e locais. Para obter mais informações sobre esse recurso, consulte Índice secundário.
Pré-requisitos
Instância OTSClient inicializada. Para obter mais informações, consulte Inicializar um cliente Tablestore.
Índice secundário criado. Para obter mais informações, consulte Criar um índice secundário.
Observações de uso
A tabela de índice serve exclusivamente para leitura de dados.
A primeira coluna de chave primária de um índice secundário local deve ser idêntica à primeira coluna de chave primária da tabela de dados.
Se as colunas de atributo desejadas não estiverem na tabela de índice, consulte a tabela de dados associada para obtê-las.
Ler uma única linha de dados
Chame a operação GetRow para ler uma única linha de dados. Para obter mais informações, consulte Ler uma única linha de dados.
Parâmetros
Ao chamar a operação GetRow para ler dados de uma tabela de índice, observe os seguintes pontos:
Defina o parâmetro tableName como o nome da tabela de índice.
O Tablestore adiciona automaticamente as colunas de chave primária da tabela de dados não especificadas como colunas de índice à tabela de índice, tratando-as como chaves primárias desta última. Portanto, ao especificar as colunas de chave primária de uma linha na tabela de índice, inclua tanto as colunas de índice usadas na criação quanto as colunas de chave primária da tabela de dados.
Exemplos
O código de exemplo a seguir demonstra como ler colunas de atributo específicas de uma linha em uma tabela de índice:
private static void getRowFromIndex(SyncClient client) {
// Construct the primary key. If you want to read data from 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.
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.fromString("def1"));
primaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.fromLong(100));
primaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.fromString("pri1"));
PrimaryKey primaryKey = primaryKeyBuilder.build();
// Specify the name of the index table from which you want to read a row of data and the primary key of the row.
SingleRowQueryCriteria criteria = new SingleRowQueryCriteria("<INDEX_NAME>", primaryKey);
// Set the MaxVersions parameter to 1 to read the latest version of data.
criteria.setMaxVersions(1);
GetRowResponse getRowResponse = client.getRow(new GetRowRequest(criteria));
Row row = getRowResponse.getRow();
// If the row that you want to read does exist, null is returned.
System.out.println("Read complete. Result:");
System.out.println(row);
// Specify the attribute columns that you want to read.
criteria.addColumnsToGet("Col0");
getRowResponse = client.getRow(new GetRowRequest(criteria));
row = getRowResponse.getRow();
System.out.println("Read complete. Result:");
System.out.println(row);
}
Ler dados com valores de chave primária em um intervalo específico
Utilize a operação GetRange para ler dados cujos valores de chave primária estejam dentro de um intervalo definido. Para obter mais detalhes, consulte Ler dados com valores de chave primária no intervalo especificado.
Parâmetros
Ao executar a operação GetRange para leitura em uma tabela de índice, atente-se aos seguintes itens:
Especifique o nome da tabela de índice no parâmetro tableName.
O Tablestore inclui automaticamente as colunas de chave primária da tabela de dados (não definidas como colunas de índice) na tabela de índice como chaves primárias. Por isso, ao definir as chaves primárias inicial e final do intervalo de consulta, especifique tanto as colunas de índice originais quanto as chaves primárias da tabela de dados.
Exemplos
Usar índices secundários globais
Caso a tabela de índice possua as colunas de atributo necessárias, consulte os dados diretamente nela.
private static void scanFromIndex(SyncClient client) {
// Specify the name of the index table.
RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria("<INDEX_NAME>");
// Specify the start primary key of the range that you want to query.
PrimaryKeyBuilder startPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
// Set the value of the index column to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.INF_MIN);
// Set the value of a primary key column of the data table that is not specified as an index column in the index table to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MIN);
// Set the value of a primary key column of the data table that is not specified as an index column in the index table to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MIN);
rangeRowQueryCriteria.setInclusiveStartPrimaryKey(startPrimaryKeyBuilder.build());
// Specify the end primary key of the range that you want to query.
PrimaryKeyBuilder endPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
// Set the value of the index column to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.INF_MAX);
// Set the value of a primary key column of the data table that is not specified as an index column in the index table to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MAX);
// Set the value of a primary key column of the data table that is not specified as an index column in the index table to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MAX);
rangeRowQueryCriteria.setExclusiveEndPrimaryKey(endPrimaryKeyBuilder.build());
rangeRowQueryCriteria.setMaxVersions(1);
System.out.println("Results returned from the index table:");
while (true) {
GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
for (Row row : getRangeResponse.getRows()) {
System.out.println(row);
}
// If the nextStartPrimaryKey parameter is not null in the response, continue to read data.
if (getRangeResponse.getNextStartPrimaryKey() != null) {
rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
} else {
break;
}
}
}
Se a tabela de índice não contiver as colunas de atributo desejadas, consulte a tabela de dados correspondente para obter as informações.
private static void scanFromIndex(SyncClient client) {
// Specify the name of the index table.
RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria("<INDEX_NAME>");
// Specify the start primary key of the range that you want to query.
PrimaryKeyBuilder startPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
// Set the value of the index column to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.INF_MIN);
// Set the value of a primary key column of the data table that is not specified as an index column in the index table to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MIN);
// Set the value of a primary key column of the data table that is not specified as an index column in the index table to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MIN);
rangeRowQueryCriteria.setInclusiveStartPrimaryKey(startPrimaryKeyBuilder.build());
// Specify the end primary key of the range that you want to query.
PrimaryKeyBuilder endPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
// Set the value of the index column to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.INF_MAX);
// Set the value of a primary key column of the data table that is not specified as an index column in the index table to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MAX);
// Set the value of a primary key column of the data table that is not specified as an index column in the index table to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MAX);
rangeRowQueryCriteria.setExclusiveEndPrimaryKey(endPrimaryKeyBuilder.build());
rangeRowQueryCriteria.setMaxVersions(1);
while (true) {
GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
for (Row row : getRangeResponse.getRows()) {
PrimaryKey curIndexPrimaryKey = row.getPrimaryKey();
PrimaryKeyColumn pk1 = curIndexPrimaryKey.getPrimaryKeyColumn(PRIMARY_KEY_NAME_1);
PrimaryKeyColumn pk2 = curIndexPrimaryKey.getPrimaryKeyColumn(PRIMARY_KEY_NAME_2);
PrimaryKeyBuilder mainTablePKBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
mainTablePKBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, pk1.getValue());
mainTablePKBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, pk2.getValue());
// Specify the primary key of the data table based on the primary key of the index table.
PrimaryKey mainTablePK = mainTablePKBuilder.build();
// Query data from the data table.
SingleRowQueryCriteria criteria = new SingleRowQueryCriteria("<TABLE_NAME>", mainTablePK);
// Specify the attribute columns that you want to return. In this example, the DEFINED_COL_NAME_3 column is returned.
criteria.addColumnsToGet(DEFINED_COL_NAME_3);
// Set the MaxVersions parameter to 1 to read the latest version of data.
criteria.setMaxVersions(1);
GetRowResponse getRowResponse = client.getRow(new GetRowRequest(criteria));
Row mainTableRow = getRowResponse.getRow();
System.out.println(row);
}
// If the nextStartPrimaryKey parameter is not null in the response, continue to read data.
if (getRangeResponse.getNextStartPrimaryKey() != null) {
rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
} else {
break;
}
}
}
Usar índices secundários locais
Se a tabela de índice incluir as colunas de atributo que você precisa retornar, obtenha os dados diretamente dessa tabela.
private static void scanFromIndex(SyncClient client) {
// Specify the name of the index table.
RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria("INDEX_NAME");
// Specify the start primary key of the range that you want to query.
PrimaryKeyBuilder startPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
// Set the value of an index column to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MIN);
// Set the value of an index column to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.INF_MIN);
// Set the value of the primary key column of the data table that is not specified as an index column in the index table to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MIN);
rangeRowQueryCriteria.setInclusiveStartPrimaryKey(startPrimaryKeyBuilder.build());
// Specify the end primary key of the range that you want to query.
PrimaryKeyBuilder endPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
// Set the value of an index column to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MAX);
// Set the value of an index column to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.INF_MAX);
// Set the value of the primary key column of the data table that is not specified as an index column in the index table to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MAX);
rangeRowQueryCriteria.setExclusiveEndPrimaryKey(endPrimaryKeyBuilder.build());
rangeRowQueryCriteria.setMaxVersions(1);
System.out.println("Results returned from the index table:");
while (true) {
GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
for (Row row : getRangeResponse.getRows()) {
System.out.println(row);
}
// If the nextStartPrimaryKey parameter is not null in the response, continue to read data.
if (getRangeResponse.getNextStartPrimaryKey() != null) {
rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
} else {
break;
}
}
}
Se a tabela de índice não possuir as colunas de atributo alvo, consulte a tabela de dados principal.
private static void scanFromIndex(SyncClient client) {
// Specify the name of the index table.
RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria("<INDEX_NAME>");
// Specify the start primary key of the range that you want to query.
PrimaryKeyBuilder startPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
// Set the value of an index column to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MIN);
// Set the value of an index column to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.INF_MIN);
// Set the value of the primary key column of the data table that is not specified as an index column in the index table to an infinitely small value.
startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MIN);
rangeRowQueryCriteria.setInclusiveStartPrimaryKey(startPrimaryKeyBuilder.build());
// Specify the end primary key of the range that you want to query.
PrimaryKeyBuilder endPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
// Set the value of an index column to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MAX);
// Set the value of an index column to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.INF_MAX);
// Set the value of the primary key column of the data table that is not specified as an index column in the index table to an infinitely great value.
endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MAX);
rangeRowQueryCriteria.setExclusiveEndPrimaryKey(endPrimaryKeyBuilder.build());
rangeRowQueryCriteria.setMaxVersions(1);
while (true) {
GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
for (Row row : getRangeResponse.getRows()) {
PrimaryKey curIndexPrimaryKey = row.getPrimaryKey();
PrimaryKeyColumn pk1 = curIndexPrimaryKey.getPrimaryKeyColumn(PRIMARY_KEY_NAME_1);
PrimaryKeyColumn pk2 = curIndexPrimaryKey.getPrimaryKeyColumn(PRIMARY_KEY_NAME_2);
PrimaryKeyBuilder mainTablePKBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
mainTablePKBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, pk1.getValue());
mainTablePKBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, pk2.getValue());
// Specify the primary key of the data table based on the primary key of the index table.
PrimaryKey mainTablePK = mainTablePKBuilder.build();
// Query data from the data table.
SingleRowQueryCriteria criteria = new SingleRowQueryCriteria("TABLE_NAME", mainTablePK);
// Specify the attribute columns that you want to return from the data table. In this example, the DEFINED_COL_NAME3 column is returned.
criteria.addColumnsToGet(DEFINED_COL_NAME3);
// Set the MaxVersions parameter to 1 to read the latest version of data.
criteria.setMaxVersions(1);
GetRowResponse getRowResponse = client.getRow(new GetRowRequest(criteria));
Row mainTableRow = getRowResponse.getRow();
System.out.println(row);
}
// If the nextStartPrimaryKey parameter is not null in the response, continue to read data.
if (getRangeResponse.getNextStartPrimaryKey() != null) {
rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
} else {
break;
}
}
}
Perguntas frequentes
Referências
Para consultas multidimensionais e análise de dados, crie um índice de pesquisa e defina os atributos necessários como campos desse índice. Assim, é possível consultar e analisar dados usando recursos como consultas baseadas em colunas sem chave primária, consultas booleanas e consultas difusas. Também é possível obter valores máximos e mínimos, contabilizar linhas e agrupar resultados. Para saber mais, consulte Índice de pesquisa.
Para executar instruções SQL de consulta e análise, utilize o recurso de consulta SQL. Para mais detalhes, consulte Consulta SQL.