Todos os produtos
Search
Central de documentação

Tablestore:Cenários

Última atualização: Sep 09, 2026

Os índices secundários aumentam a eficiência das consultas em diversos cenários. Crie um índice em colunas específicas para ordenar os dados da tabela de índice resultante por essas colunas. Ao gravar dados na tabela primária, o sistema sincroniza automaticamente as informações com a tabela de índice, o que permite consultas rápidas para recuperação de dados.

Cenário de exemplo

Em um cenário de consulta de registros de chamadas telefônicas, as informações de cada chamada são armazenadas em uma tabela de dados após o término da ligação.

A chave primária e as colunas predefinidas da tabela de dados são:

  • CellNumber e StartTime são as chaves primárias. Elas representam o número de origem e o horário de início da chamada, respectivamente.

  • CalledNumber, Duration e BaseStationNumber são colunas predefinidas. Elas correspondem ao número de destino, à duração da chamada e ao número da estação base, respectivamente.

A tabela a seguir apresenta dados de amostra. O modelo de tabela ampla do Tablestore organiza todas as linhas pela chave primária e oferece a operação de varredura sequencial (GetRange) para leitura de dados.

CellNumber

StartTime (UNIX timestamp)

CalledNumber

Duration

BaseStationNumber

123456

1532574644

654321

60

1

234567

1532574714

765432

10

1

234567

1532574734

123456

20

3

345678

1532574795

123456

5

2

345678

1532574861

123456

100

2

456789

1532584054

345678

200

3

Considere os seguintes requisitos de consulta. Recupere os dados necessários da tabela primária, de um índice secundário global ou de um índice secundário local, conforme a necessidade.

  • Consultar todos os registros de chamadas originadas pelo número 234567.

  • Listar todas as chamadas recebidas pelo número 123456.

  • Buscar registros de chamadas da estação base 002 iniciadas no timestamp 1532574740 ou posterior.

  • Obter a duração de todas as chamadas ocorridas na estação base 003 entre os timestamps 1532574861 e 1532584054.

  • Calcular a duração total, média, máxima e mínima das chamadas na estação base 003 entre os timestamps 1532574861 e 1532584054.

  • Recuperar todos os registros de chamadas do número de origem 456789 para o número de destino 345678.

Consulta de dados

Selecione o método de consulta adequado para cada requisito.

Métodos de implementação

A tabela a seguir descreve o método de implementação para cada requisito de consulta.

Importante
  • Para ver um exemplo de criação de tabela e índice secundário, consulte Appendix: Example of creating a data table and secondary indexes.

    Após criar a tabela primária, grave os dados de amostra nela. O sistema sincroniza automaticamente os dados com a tabela de índice. Para mais detalhes sobre gravação de dados, consulte Write data.

  • O sistema preenche automaticamente a chave primária. Isso significa que as colunas de chave primária da tabela primária são adicionadas às colunas de índice para formar a chave primária da tabela de índice.

  • 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 primária.

Requisito de consulta

Método de implementação

Consultar todos os registros de chamadas originadas pelo número 234567.

Chame a interface getRange para varrer a tabela de dados.

Listar todas as chamadas recebidas pelo número 123456.

Crie um índice na coluna CalledNumber. Em seguida, chame a operação getRange para varrer a tabela de índice.

Buscar registros de chamadas da estação base 002 iniciadas no timestamp 1532574740 ou posterior.

Crie um índice composto nas colunas BaseStationNumber e StartTime. Depois, utilize a operação getRange para varrer a tabela de índice (um índice secundário global).

Obter a duração de todas as chamadas ocorridas na estação base 003 entre os timestamps 1532574861 e 1532584054.

Crie um índice composto nas colunas BaseStationNumber e StartTime e retorne apenas a coluna Duration. Em seguida, chame a operação getRange para varrer a tabela de índice (um índice secundário global).

Consulte manualmente a tabela primária para obter o valor da coluna Duration ou inclua essa coluna como atributo na tabela de índice.

Para calcular a duração total, média, máxima e mínima das chamadas na estação base 003 entre os timestamps 1532574861 e 1532584054, utilize o mesmo método de implementação e calcule os resultados finais com base na duração retornada para cada chamada.

Nota

Use consultas SQL do Tablestore para eliminar a necessidade de cálculos no cliente. Uma instrução SQL recupera diretamente os resultados estatísticos finais. Para mais informações, consulte Query data.

Recuperar todos os registros de chamadas do número de origem 456789 para o número de destino 345678.

Crie um índice composto nas colunas CellNumber e CalledNumber e inclua as colunas Duration e BaseStationNumber como atributos na tabela de índice. Por fim, execute a operação getRange para varrer a tabela de índice (um índice secundário local).

Consultar todos os registros de chamadas originadas pelo número 234567

A coluna CellNumber é uma chave primária da tabela primária, o que permite consultas rápidas. Chame a operação GetRange para varrer a tabela primária e obter os resultados.

Ao chamar a operação GetRange, defina os valores mínimo e máximo da coluna CellNumber como 234567. Configure o valor mínimo da coluna StartTime como 0 e o máximo como INT_MAX.

O código a seguir serve como exemplo:

// The cellNumber parameter in the example corresponds to the CellNumber column in the primary table.
private static void getRangeFromMainTable(SyncClient client, long cellNumber){
    RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria(TABLE_NAME);

    // Construct the start primary key.
    PrimaryKeyBuilder startPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
    startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.fromLong(cellNumber));
    startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.fromLong(0));
    rangeRowQueryCriteria.setInclusiveStartPrimaryKey(startPrimaryKeyBuilder.build());

    // Construct the end primary key.
    PrimaryKeyBuilder endPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
    endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.fromLong(cellNumber));
    endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MAX);
    rangeRowQueryCriteria.setExclusiveEndPrimaryKey(endPrimaryKeyBuilder.build());

    rangeRowQueryCriteria.setMaxVersions(1);

    String strNum = String.format("%d", cellNumber);
    System.out.println("All outgoing call records for number " + strNum + ":");
    while (true) {
        GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
        for (Row row : getRangeResponse.getRows()) {
            System.out.println(row);
        }

        // If nextStartPrimaryKey is not null, continue to read data.
        if (getRangeResponse.getNextStartPrimaryKey() != null) {
            rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
        } else {
            break;
        }
    }
}

Listar todas as chamadas recebidas pelo número 123456

Esta consulta utiliza a coluna CalledNumber como condição. Como CalledNumber é uma coluna predefinida na tabela primária, ela não suporta consultas rápidas. Para resolver isso, crie um índice chamado IndexOnBeCalledNumber na coluna CalledNumber e use-a como chave primária da tabela de índice. Em seguida, chame a operação getRange para varrer a tabela de índice e recuperar os resultados.

Como a primeira coluna de chave primária da tabela de índice difere da primeira coluna de chave primária da tabela primária, trata-se de um índice secundário global.

Dados da tabela de índice

A tabela a seguir exibe os dados da tabela de índice IndexOnBeCalledNumber.

PK0

PK1

PK2

CalledNumber

CellNumber

StartTime

123456

234567

1532574734

123456

345678

1532574795

123456

345678

1532574861

345678

456789

1532584054

654321

123456

1532574644

765432

234567

1532574714

Ao chamar a operação GetRange, configure os valores mínimo e máximo da coluna CalledNumber como 123456. Defina os valores mínimos das colunas CellNumber e StartTime como INT_MIN e os máximos como INT_MAX. Veja o exemplo de código:

// The calledNumber parameter in the example corresponds to the CalledNumber column in the index table.
private static void getRangeFromIndexTable(SyncClient client, long calledNumber) {
    RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria(INDEX0_NAME);

    // Construct the start primary key.
    PrimaryKeyBuilder startPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
    startPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.fromLong(calledNumber));
    startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MIN);
    startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MIN);
    rangeRowQueryCriteria.setInclusiveStartPrimaryKey(startPrimaryKeyBuilder.build());

    // Construct the end primary key.
    PrimaryKeyBuilder endPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
    endPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.fromLong(calledNumber));
    endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MAX);
    endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MAX);
    rangeRowQueryCriteria.setExclusiveEndPrimaryKey(endPrimaryKeyBuilder.build());

    rangeRowQueryCriteria.setMaxVersions(1);

    String strNum = String.format("%d", calledNumber);
    System.out.println("All incoming call records for number " + strNum + ":");
    while (true) {
        GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
        for (Row row : getRangeResponse.getRows()) {
            System.out.println(row);
        }

        // If nextStartPrimaryKey is not null, continue to read data.
        if (getRangeResponse.getNextStartPrimaryKey() != null) {
            rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
        } else {
            break;
        }
    }
}

Buscar registros de chamadas da estação base 002 iniciadas no timestamp 1532574740 ou posterior

Nesta consulta, as colunas BaseStationNumber e StartTime servem como condições. Como BaseStationNumber é uma coluna predefinida na tabela primária sem suporte a consultas rápidas, crie um índice composto chamado IndexOnBaseStation1 nas colunas BaseStationNumber e StartTime. Utilize essas colunas como chave primária da tabela de índice e chame a operação getRange para varrer a tabela e obter os resultados.

Como a primeira coluna de chave primária da tabela de índice é diferente da primeira coluna de chave primária da tabela primária, este é um índice secundário global.

Dados da tabela de índice

A tabela a seguir mostra os dados da tabela de índice IndexOnBaseStation1.

PK0

PK1

PK2

BaseStationNumber

StartTime

CellNumber

1

1532574644

123456

1

1532574714

234567

2

1532574795

345678

2

1532574861

345678

3

1532574734

234567

3

1532584054

456789

Ao chamar a API GetRange para consultar dados, defina a coluna BaseStationNumber com valores mínimo e máximo iguais a 2, a coluna StartTime com valor mínimo de 1532574740 e máximo de INT_MAX, e a coluna CellNumber com mínimo de INT_MIN e máximo de INT_MAX. O código a seguir ilustra esse processo:

// The baseStationNumber parameter in the example corresponds to the BaseStationNumber column in the index table.
// The startTime parameter in the example corresponds to the start time for the StartTime column in the index table.
private static void getRangeFromIndexTable(SyncClient client,
                                           long baseStationNumber,
                                           long startTime) {
    RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria(INDEX1_NAME);

    // Construct the start primary key.
    PrimaryKeyBuilder startPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
    startPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_3, PrimaryKeyValue.fromLong(baseStationNumber));
    startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.fromLong(startTime));
    startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MIN);
    rangeRowQueryCriteria.setInclusiveStartPrimaryKey(startPrimaryKeyBuilder.build());

    // Construct the end primary key.
    PrimaryKeyBuilder endPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
    endPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_3, PrimaryKeyValue.fromLong(baseStationNumber));
    endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MAX);
    endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MAX);
    rangeRowQueryCriteria.setExclusiveEndPrimaryKey(endPrimaryKeyBuilder.build());

    rangeRowQueryCriteria.setMaxVersions(1);

    String strBaseStationNum = String.format("%d", baseStationNumber);
    String strStartTime = String.format("%d", startTime);
    System.out.println("All incoming call records from base station " + strBaseStationNum + " starting from time " + strStartTime + ":");
    while (true) {
        GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
        for (Row row : getRangeResponse.getRows()) {
            System.out.println(row);
        }

        // If nextStartPrimaryKey is not null, continue to read data.
        if (getRangeResponse.getNextStartPrimaryKey() != null) {
            rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
        } else {
            break;
        }
    }
}

Obter a duração de todas as chamadas ocorridas na estação base 003 entre os timestamps 1532574861 e 1532584054

Como as colunas BaseStationNumber e StartTime são usadas como condições de consulta e apenas a coluna Duration é recuperada, utilize a tabela de índice IndexOnBaseStation1 do cenário Query all call records for base station 002 starting from 1532574740 para consultar a tabela de índice. Em seguida, faça uma busca reversa na tabela de dados para obter a duração da chamada.

Como a primeira coluna de chave primária da tabela de índice difere da primeira coluna de chave primária da tabela primária, este é um índice secundário global.

Confira o exemplo de código:

// The baseStationNumber parameter in the example corresponds to the BaseStationNumber column in the index table.
// The startTime and endTime parameters in the example correspond to the start and end times for the StartTime column values to query in the index table.
// The DEFINED_COL_NAME_2 parameter in the example corresponds to the Duration column in the primary table to look up.
private static void getRowFromIndexAndMainTable(SyncClient client,
 long baseStationNumber,
 long startTime,
 long endTime) {
 RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria(INDEX1_NAME);

 // Construct the start primary key.
 PrimaryKeyBuilder startPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
 startPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_3, PrimaryKeyValue.fromLong(baseStationNumber));
 startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.fromLong(startTime));
 startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MIN);
 rangeRowQueryCriteria.setInclusiveStartPrimaryKey(startPrimaryKeyBuilder.build());

 // Construct the end primary key.
 PrimaryKeyBuilder endPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
 endPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_3, PrimaryKeyValue.fromLong(baseStationNumber));
 endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.fromLong(endTime));
 endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MAX);
 rangeRowQueryCriteria.setExclusiveEndPrimaryKey(endPrimaryKeyBuilder.build());

 rangeRowQueryCriteria.setMaxVersions(1);

 String strBaseStationNum = String.format("%d", baseStationNumber);
 String strStartTime = String.format("%d", startTime);
 String strEndTime = String.format("%d", endTime);

 System.out.println("Call duration for all call records from base station " + strBaseStationNum + " from time " + strStartTime + " to " + strEndTime + ":");
 while (true) {
 GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
 for (Row row : getRangeResponse.getRows()) {
 PrimaryKey curIndexPrimaryKey = row.getPrimaryKey();
 // Construct the primary table primary key.
 PrimaryKeyColumn mainCalledNumber = curIndexPrimaryKey.getPrimaryKeyColumn(PRIMARY_KEY_NAME_1);
 PrimaryKeyColumn callStartTime = curIndexPrimaryKey.getPrimaryKeyColumn(PRIMARY_KEY_NAME_2);
 PrimaryKeyBuilder mainTablePKBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
 mainTablePKBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, mainCalledNumber.getValue());
 mainTablePKBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, callStartTime.getValue());
 PrimaryKey mainTablePK = mainTablePKBuilder.build(); 

 // Look up the primary table.
 SingleRowQueryCriteria criteria = new SingleRowQueryCriteria(TABLE_NAME, mainTablePK);
 // Read the Duration column of the primary table.
 criteria.addColumnsToGet(DEFINED_COL_NAME_2); 
 // Set to read the latest version.
 criteria.setMaxVersions(1);
 GetRowResponse getRowResponse = client.getRow(new GetRowRequest(criteria));
 Row mainTableRow = getRowResponse.getRow();

 System.out.println(mainTableRow);
 }

 // If nextStartPrimaryKey is not null, continue to read data.
 if (getRangeResponse.getNextStartPrimaryKey() != null) {
 rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
 } else {
 break;
 }
 }
}

Para otimizar a eficiência da consulta, crie um índice composto chamado IndexOnBaseStation2 nas colunas BaseStationNumber e StartTime e inclua a coluna Duration como atributo na tabela de índice. Dessa forma, ao chamar a operação getRange, você varre a tabela de índice e recupera os resultados diretamente.

Dados da tabela de índice

A tabela a seguir apresenta os dados da tabela de índice IndexOnBaseStation2.

PK0

PK1

PK2

Defined0

BaseStationNumber

StartTime

CellNumber

Duration

1

1532574644

123456

60

1

1532574714

234567

10

2

1532574795

345678

5

2

1532574861

345678

100

3

1532574734

234567

20

3

1532584054

456789

200

Ao executar a operação GetRange, configure os valores mínimo e máximo da coluna BaseStationNumber como "003". Defina o valor mínimo da coluna StartTime como 1532574861 e o máximo como 1532584054. Para a coluna CellNumber, defina o mínimo como INT_MIN e o máximo como INT_MAX.

Veja o exemplo de código:

// The baseStationNumber parameter in the example corresponds to the BaseStationNumber column in the index table.
// The startTime and endTime parameters in the example correspond to the start and end times for the StartTime column values to query in the index table.
// The DEFINED_COL_NAME_2 parameter in the example corresponds to the Duration column in the index table.
private static void getRangeFromIndexTable(SyncClient client,
 long baseStationNumber,
 long startTime,
 long endTime) {
 RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria(INDEX2_NAME);

 // Construct the start primary key.
 PrimaryKeyBuilder startPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
 startPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_3, PrimaryKeyValue.fromLong(baseStationNumber));
 startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.fromLong(startTime));
 startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MIN);
 rangeRowQueryCriteria.setInclusiveStartPrimaryKey(startPrimaryKeyBuilder.build());

 // Construct the end primary key.
 PrimaryKeyBuilder endPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
 endPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_3, PrimaryKeyValue.fromLong(baseStationNumber));
 endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.fromLong(endTime));
 endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.INF_MAX);
 rangeRowQueryCriteria.setExclusiveEndPrimaryKey(endPrimaryKeyBuilder.build());

 // Set the columns to read.
 rangeRowQueryCriteria.addColumnsToGet(DEFINED_COL_NAME_2);

 rangeRowQueryCriteria.setMaxVersions(1);

 String strBaseStationNum = String.format("%d", baseStationNumber);
 String strStartTime = String.format("%d", startTime);
 String strEndTime = String.format("%d", endTime);

 System.out.println("Call duration for all call records from base station " + strBaseStationNum + " from time " + strStartTime + " to " + strEndTime + ":");
 while (true) {
 GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
 for (Row row : getRangeResponse.getRows()) {
 System.out.println(row);
 }

 // If nextStartPrimaryKey is not null, continue to read data.
 if (getRangeResponse.getNextStartPrimaryKey() != null) {
 rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
 } else {
 break;
 }
 }
}

Recuperar todos os registros de chamadas do número de origem 456789 para o número de destino 345678

Esta consulta tem como condição as colunas CellNumber e CalledNumber. Como CalledNumber é uma coluna predefinida na tabela primária e não suporta consultas rápidas, crie um índice composto chamado LocalIndexOnBeCalledNumber nas colunas CellNumber e CalledNumber. Use essas colunas como chave primária da tabela de índice e inclua as colunas Duration e BaseStationNumber como atributos. Em seguida, chame a operação getRange para varrer a tabela de índice e obter os resultados.

Como a primeira coluna de chave primária da tabela de índice é igual à primeira coluna de chave primária da tabela primária, trata-se de um índice secundário local.

Dados da tabela de índice

A tabela a seguir exibe os dados da tabela de índice LocalIndexOnBeCalledNumber.

PK0

Defined0

PK1

Defined1

Defined2

CellNumber

CalledNumber

StartTime (UNIX timestamp)

Duration

BaseStationNumber

123456

654321

1532574644

60

1

234567

123456

1532574734

20

3

234567

765432

1532574714

10

1

345678

123456

1532574795

5

2

345678

123456

1532574861

100

2

456789

345678

1532584054

200

3

Ao chamar a operação GetRange, defina os valores mínimo e máximo da coluna CellNumber como 456789 e da coluna CalledNumber como 345678. Configure o valor mínimo da coluna StartTime como 0 e o máximo como INT_MAX. O código a seguir demonstra essa implementação:

// The cellNumber and calledNumber parameters in the example correspond to the CellNumber and CalledNumber columns in the index table.
private static void getRangeFromLocalIndex(SyncClient client, long cellNumber, long calledNumber){

    RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria(INDEX3_NAME);

    // Construct the start primary key.
    PrimaryKeyBuilder startPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
    startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.fromLong(cellNumber));
    startPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.fromLong(calledNumber));
    startPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.fromLong(0));
    rangeRowQueryCriteria.setInclusiveStartPrimaryKey(startPrimaryKeyBuilder.build());

    // Construct the end primary key.
    PrimaryKeyBuilder endPrimaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
    endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1, PrimaryKeyValue.fromLong(cellNumber));
    endPrimaryKeyBuilder.addPrimaryKeyColumn(DEFINED_COL_NAME_1, PrimaryKeyValue.fromLong(calledNumber));
    endPrimaryKeyBuilder.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2, PrimaryKeyValue.INF_MAX);
    rangeRowQueryCriteria.setExclusiveEndPrimaryKey(endPrimaryKeyBuilder.build());

    rangeRowQueryCriteria.setMaxVersions(1);

    String strNum = String.format("%d", cellNumber);
    String strCalledNum = String.format("%d", calledNumber);
    System.out.println("All call records between number " + strNum + " and number " +strCalledNum+ ":");
    while (true) {
        GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
        for (Row row : getRangeResponse.getRows()) {
            System.out.println(row);
        }

        // If nextStartPrimaryKey is not null, continue to read data.
        if (getRangeResponse.getNextStartPrimaryKey() != null) {
            rangeRowQueryCriteria.setInclusiveStartPrimaryKey(getRangeResponse.getNextStartPrimaryKey());
        } else {
            break;
        }
    }
}

Apêndice: Exemplo de criação de tabela de dados e índices secundários

O exemplo a seguir demonstra como criar a tabela primária e os índices secundários, incluindo índices locais e globais, utilizados neste tópico.

private static final String TABLE_NAME = "CallRecordTable";
private static final String INDEX0_NAME = "IndexOnBeCalledNumber";
private static final String INDEX1_NAME = "IndexOnBaseStation1";
private static final String INDEX2_NAME = "IndexOnBaseStation2";
private static final String INDEX3_NAME = "LocalIndexOnBeCalledNumber";
private static final String PRIMARY_KEY_NAME_1 = "CellNumber";
private static final String PRIMARY_KEY_NAME_2 = "StartTime";
private static final String DEFINED_COL_NAME_1 = "CalledNumber";
private static final String DEFINED_COL_NAME_2 = "Duration";
private static final String DEFINED_COL_NAME_3 = "BaseStationNumber";

private static void createTable(SyncClient client) {
    TableMeta tableMeta = new TableMeta(TABLE_NAME);
    tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema(PRIMARY_KEY_NAME_1, PrimaryKeyType.INTEGER));
    tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema(PRIMARY_KEY_NAME_2, PrimaryKeyType.INTEGER));
    tableMeta.addDefinedColumn(new DefinedColumnSchema(DEFINED_COL_NAME_1, DefinedColumnType.INTEGER));
    tableMeta.addDefinedColumn(new DefinedColumnSchema(DEFINED_COL_NAME_2, DefinedColumnType.INTEGER));
    tableMeta.addDefinedColumn(new DefinedColumnSchema(DEFINED_COL_NAME_3, DefinedColumnType.INTEGER));
    // The time-to-live (TTL) of the data, in seconds. A value of -1 means that the data never expires. The TTL for a primary table with an index table must be -1.
    int timeToLive = -1; 
    // The maximum number of versions to save. The max versions for a primary table with an index table must be 1.
    int maxVersions = 1; 

    TableOptions tableOptions = new TableOptions(timeToLive, maxVersions);

    ArrayList<IndexMeta> indexMetas = new ArrayList<IndexMeta>();
 
    IndexMeta indexMeta0 = new IndexMeta(INDEX0_NAME);
    indexMeta0.addPrimaryKeyColumn(DEFINED_COL_NAME_1);
    indexMetas.add(indexMeta0);
   
    IndexMeta indexMeta1 = new IndexMeta(INDEX1_NAME);
    indexMeta1.addPrimaryKeyColumn(DEFINED_COL_NAME_3);
    indexMeta1.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2);
    indexMetas.add(indexMeta1);
   
    IndexMeta indexMeta2 = new IndexMeta(INDEX2_NAME);
    indexMeta2.addPrimaryKeyColumn(DEFINED_COL_NAME_3);
    indexMeta2.addPrimaryKeyColumn(PRIMARY_KEY_NAME_2);
    indexMeta2.addDefinedColumn(DEFINED_COL_NAME_2);
    indexMetas.add(indexMeta2);
 
    IndexMeta indexMeta3 = new IndexMeta(INDEX3_NAME);
    indexMeta3.addPrimaryKeyColumn(PRIMARY_KEY_NAME_1);
    indexMeta3.addPrimaryKeyColumn(DEFINED_COL_NAME_1);
    indexMeta3.addDefinedColumn(DEFINED_COL_NAME_2);
    indexMeta3.addDefinedColumn(DEFINED_COL_NAME_3);
    // Set the index synchronization mode.
    indexMeta3.setIndexUpdateMode(IUM_SYNC_INDEX);
    // Set the index type to IT_LOCAL_INDEX (local secondary index).
    indexMeta3.setIndexType(IT_LOCAL_INDEX);
    indexMetas.add(indexMeta3);
 
    CreateTableRequest request = new CreateTableRequest(tableMeta, tableOptions, indexMetas);

    client.createTable(request);
}