Todos os produtos
Search
Central de documentação

Tablestore:Usar um índice secundário para ler dados

Última atualização: Jul 03, 2026

Tablestore oferece métodos de leitura de linha única e de intervalo para acessar dados em tabelas de índice. Se a tabela de índice contiver as colunas de atributo desejadas, leia os dados diretamente dela. Caso contrário, consulte os dados na tabela primária.

Pré-requisitos

Precauções

  • Tabelas de índice servem exclusivamente para leitura de dados.

  • A primeira coluna de chave primária de uma tabela de índice secundário local deve ser idêntica à primeira coluna de chave primária da tabela primária.

  • Se as colunas de atributo necessárias não estiverem na tabela de índice, busque os dados na tabela primária.

Ler uma única linha de dados

Chame a operação GetRow para ler uma única linha de dados. Para mais informações, consulte Ler uma única linha.

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 com 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 colunas de chave primária 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

Usar índices secundários globais

O código de exemplo a seguir demonstra como ler uma linha de dados em um índice secundário global com base na chave primária da linha:

var TableStore = require('./index.js');
var Long = TableStore.Long;
var client = require('./client');

var params = {
  // Specify the name of the index table. 
  tableName: "<INDEX_NAME>",  
  // Specify the information about the primary key of row in the index table. 
  primaryKey: [{ 'col1': Long.fromNumber(2) }, { 'pk1': Long.fromNumber(2) }, { 'pk2': Long.fromNumber(1) }]
};

client.getRow(params, function (err, data) {
  if (err) {
    console.log('error:', err);
    return;
  }
  console.log('success:', JSON.stringify(data.row, null, 2));
});

Usar índices secundários locais

O código de exemplo a seguir demonstra como ler uma linha de dados em um índice secundário local com base na chave primária da linha:

var TableStore = require('./index.js');
var Long = TableStore.Long;
var client = require('./client');

var params = {
  // Specify the name of the index table. 
  tableName: "<INDEX_NAME>", 
  // Specify the information about the primary key of row in 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. 
  primaryKey: [{ 'pk1': Long.fromNumber(1) }, { 'col1': Long.fromNumber(2) }, { 'pk2': Long.fromNumber(2) }]
};

client.getRow(params, function (err, data) {
  if (err) {
    console.log('error:', err);
    return;
  }
  console.log('success:', JSON.stringify(data.row, null, 2));
});

Ler dados com valores de chave primária dentro de um intervalo específico

Chame a operação GetRange para ler dados cujos valores de chave primária estejam dentro de um intervalo específico. Para mais informações, consulte Ler um intervalo de dados.

Parâmetros

Ao chamar a operação GetRange para ler dados de uma tabela de índice, atente-se aos seguintes itens:

  • Defina o parâmetro tableName com o nome da tabela de índice.

  • O Tablestore adiciona automaticamente as colunas de chave primária da tabela de dados não definidas como colunas de índice à tabela de índice, funcionando como chaves primárias desta. Assim, ao especificar a chave primária inicial e final do intervalo de consulta, informe as colunas de índice utilizadas na criação da tabela e as colunas de chave primária da tabela de dados.

Exemplos

Usar índices secundários globais

O exemplo de código abaixo ilustra a leitura de dados com valores de chave primária dentro de um intervalo específico em um índice secundário global. Neste cenário, a primeira coluna de chave primária do índice secundário global é col1, e o valor definido para essa coluna no intervalo é 1.

var TableStore = require('./index.js');
var Long = TableStore.Long;
var client = require('./client');

var params = {
  // Specify the name of the index table. In this example, col1 is the first primary key column of the index table. pk1 and pk2 are the primary key columns of the data table. Tablestore automatically adds pk1 and pk2 to the index table as the primary key columns of the index table. 
  tableName: "<INDEX_NAME>", 
  // Specify that data is read in the forward direction. 
  direction: TableStore.Direction.FORWARD,
  // Specify the maximum number of versions of data that you want to return. 
  maxVersions: 10,
  // Specify the start and end primary keys. The range of the primary key value is a left-closed, right-opened interval. INF_MIN indicates an infinitely small value. INF_MAX indicates an infinitely great value. 
  inclusiveStartPrimaryKey: [{ "col1": Long.fromNumber(1) }, { "pk1": TableStore.INF_MIN }, { "pk2": TableStore.INF_MIN }],
  exclusiveEndPrimaryKey: [{ "col1": Long.fromNumber(1) }, { "pk1": TableStore.INF_MAX }, { "pk2": TableStore.INF_MAX }],
  // Specify the maximum number of rows that can be returned for a call. 
  limit: 2
};

var resultRows = []

var getRange = function () {
  client.getRange(params, function (err, data) {
    if (err) {
      console.log('error:', err);
      return;
    }
    resultRows = resultRows.concat(data.rows)

    // If the data.next_start_primary_key parameter is not empty in the response, continue to read data. 
    if (data.nextStartPrimaryKey) {
      params.inclusiveStartPrimaryKey = [
        { "col1": data.nextStartPrimaryKey[0].value },
        { "pk1": data.nextStartPrimaryKey[1].value },
        { "pk2": data.nextStartPrimaryKey[2].value }
      ];
      getRange()
    } else {
      console.log(JSON.stringify(resultRows));
    }
  });
}

getRange()

Usar índices secundários locais

O trecho de código a seguir mostra como ler os dados de todas as linhas de um índice secundário local:

var TableStore = require('./index.js');
var Long = TableStore.Long;
var client = require('./client');

var params = {
  // Specify the name of the index table. In this example, pk1 and col1 are specified as the primary key columns of the index table. pk2 is the primary key column of the data table. Tablestore automatically adds pk2 to the index table as the primary key column of the index table. 
  tableName: "<INDEX_NAMW>", 
  // Specify that data is read in the forward direction. 
  direction: TableStore.Direction.FORWARD,
  // Specify the maximum number of versions of data that you want to return. 
  maxVersions: 10,
  // Specify the start and end primary keys. The range of the primary key value is a left-closed, right-opened interval. INF_MIN indicates an infinitely small value. INF_MAX indicates an infinitely great value. 
  inclusiveStartPrimaryKey: [{ "pk1": TableStore.INF_MIN }, { "col1": TableStore.INF_MIN }, { "pk2": TableStore.INF_MIN }],
  exclusiveEndPrimaryKey: [{ "pk1": TableStore.INF_MAX }, { "col1": TableStore.INF_MAX }, { "pk2": TableStore.INF_MAX }],
  // Specify the maximum number of rows that can be returned for a call. 
  limit: 2
};

var resultRows = []

var getRange = function () {
  client.getRange(params, function (err, data) {
    if (err) {
      console.log('error:', err);
      return;
    }
    resultRows = resultRows.concat(data.rows)

    // If the data.next_start_primary_key parameter is not empty in the response, continue to read data. 
    if (data.nextStartPrimaryKey) {
      params.inclusiveStartPrimaryKey = [
        { "pk1": data.nextStartPrimaryKey[0].value },
        { "col1": data.nextStartPrimaryKey[1].value },
        { "pk2": data.nextStartPrimaryKey[2].value }
      ];
      getRange()
    } else {
      console.log(JSON.stringify(resultRows));
    }
  });
}

getRange()

Perguntas frequentes

Referências

  • Se seu negócio exigir consultas multidimensionais e análise de dados, crie um índice de pesquisa e defina os atributos necessários como campos desse índice. Em seguida, utilize-o para consultar e analisar dados. Por exemplo, use um índice de pesquisa para executar consultas baseadas em colunas que não são de chave primária, consultas booleanas e consultas difusas. Esse recurso também permite obter valores máximos e mínimos, gerar estatísticas sobre a quantidade de linhas e agrupar resultados de consultas. Para mais informações, consulte Índice de pesquisa.

  • Para executar instruções SQL de consulta e análise de dados, use o recurso de consulta SQL. Para mais informações, consulte Consulta SQL.