Todos os produtos
Search
Central de documentação

Tablestore:Cenários

Última atualização: Jul 03, 2026

O recurso de índice secundário permite criar um índice em colunas específicas. Os dados na tabela de índice gerada são classificados com base nas colunas de chave de índice definidas. Todos os dados gravados na tabela de dados são sincronizados automaticamente para a tabela de índice. Após gravar dados na tabela de dados, consulte-os na tabela de índice criada para essa tabela para aumentar a eficiência da consulta.

Cenário de exemplo

Este tópico descreve como usar o recurso de índice secundário para consultar registros telefônicos. Quando uma chamada termina, as informações sobre ela são registradas em uma tabela de dados.

A seção a seguir descreve as colunas de chave primária e as colunas predefinidas da tabela de dados:

  • As colunas CellNumber e StartTime funcionam como colunas de chave primária da tabela de dados. Cada valor na coluna CellNumber indica um número de origem da chamada, e cada valor na coluna StartTime indica o horário de início da chamada.

  • As colunas CalledNumber, Duration e BaseStationNumber funcionam como colunas predefinidas da tabela de dados. Cada valor na coluna CalledNumber indica um número chamado, cada valor na coluna Duration indica a duração da chamada e cada valor na coluna BaseStationNumber indica o número da estação base.

A tabela a seguir apresenta os dados de exemplo na tabela de dados. O modelo Wide Column do Tablestore classifica as linhas em uma tabela de dados com base em suas chaves primárias e fornece a operação GetRange para consultar 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

Use tabelas de dados, índices secundários globais ou índices secundários locais para executar as seguintes consultas conforme seus requisitos de negócio:

  • Consultar as linhas em que o valor da coluna CellNumber é 234567.

  • Consultar as linhas em que o valor da coluna CalledNumber é 123456.

  • Consultar as linhas em que o valor da coluna BaseStationNumber é 2 e o valor da coluna StartTime é 1532574740.

  • Consultar os valores da coluna Duration para as linhas em que o valor da coluna BaseStationNumber é 3 e o valor da coluna StartTime varia de 1532574861 a 1532584054.

  • Consultar a duração total, média, máxima e mínima de todas as chamadas encaminhadas pela estação base 3. O valor da coluna StartTime varia de 1532574861 a 1532584054.

  • Consultar as linhas em que o valor da coluna CellNumber é 456789 e o valor da coluna CalledNumber é 345678.

Consultas de dados

Selecione um método adequado para consultar dados com base nos seus requisitos de consulta.

Métodos

A tabela a seguir descreve como implementar diferentes consultas.

Importante
  • Para obter mais informações sobre o código de exemplo usado para criar uma tabela de dados e uma tabela de índice secundário, consulte Apêndice: Código de exemplo para criar a tabela de dados e as tabelas de índice secundário.

    Após criar uma tabela de dados, grave dados de exemplo nela. Os dados na tabela de dados são sincronizados automaticamente para a tabela de índice criada para ela. Para obter mais informações sobre como gravar dados, consulte Gravar dados.

  • O Tablestore adiciona automaticamente as colunas de chave primária de uma tabela de dados não especificadas como colunas de chave de índice à tabela de índice criada para essa tabela de dados. As colunas de chave primária da tabela de dados e a coluna de chave de índice funcionam como colunas de chave primária da tabela de índice.

  • Ao usar um índice secundário local, a primeira coluna de chave primária da tabela de índice deve ser igual à primeira coluna de chave primária da tabela de dados para a qual a tabela de índice foi criada.

Consulta

Método

Consultar as linhas em que o valor da coluna CellNumber é 234567

Chame diretamente a operação GetRange para verificar a tabela de dados.

Consultar as linhas em que o valor da coluna CalledNumber é 123456

Crie uma tabela de índice com base na coluna CalledNumber e chame a operação GetRange para verificar a tabela de índice.

Consultar as linhas em que o valor da coluna BaseStationNumber é 2 e o valor da coluna StartTime é 1532574740

Crie uma tabela de índice com base nas colunas BaseStationNumber e StartTime e chame a operação GetRange para verificar a tabela de índice cujo tipo de índice é índice secundário global.

Consultar os valores da coluna Duration para as linhas em que o valor da coluna BaseStationNumber é 3 e o valor da coluna StartTime varia de 1532574861 a 1532584054

Crie uma tabela de índice com base nas colunas BaseStationNumber e StartTime, especifique que apenas os valores da coluna Duration sejam retornados e, em seguida, chame a operação GetRange para verificar a tabela de índice cujo tipo de índice é índice secundário global.

Consulte manualmente os valores da coluna Duration na tabela de dados ou especifique a coluna Duration como uma coluna de atributo da tabela de índice.

Para consultar a duração total, média, máxima e mínima de todas as chamadas encaminhadas pela estação base 3 e cujo horário de início varia de 1532574861 a 1532584054, também use este método de consulta. Em seguida, execute agregação na coluna Duration para obter os resultados finais.

Nota

Execute instruções SQL para obter os resultados sem cálculos no lado do cliente. Para obter mais informações, consulte Consultar dados.

Consultar as linhas em que o valor da coluna CellNumber é 456789 e o valor da coluna CalledNumber é 345678

Crie uma tabela de índice com base nas colunas CellNumber e CalledNumber, especifique as colunas Duration e BaseStationNumber como colunas de atributo da tabela de índice e, em seguida, chame a operação GetRange para verificar a tabela de índice cujo tipo de índice é índice secundário local.

Consultar as linhas em que o valor da coluna CellNumber é 234567

A coluna CellNumber é uma coluna de chave primária da tabela de dados. Portanto, chame diretamente a operação GetRange para verificar a tabela de dados e obter as linhas que atendem à condição de consulta.

Neste caso, defina os valores máximo e mínimo da coluna CellNumber como 234567 e defina os valores mínimo e máximo da coluna StartTime como 0 e INT_MAX.

Código de exemplo:

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

    // Specify the start primary key column. 
    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());

    // Specify the end primary key column. 
    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("The cell number" + strNum + "makes the following calls:");
    while (true) {
        GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
        for (Row row : getRangeResponse.getRows()) {
            System.out.println(row);
        }

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

Consultar as linhas em que o valor da coluna CalledNumber é 123456

Esta consulta especifica uma condição com base no valor da coluna CalledNumber, que é uma coluna predefinida da tabela de dados. Não é possível consultar diretamente da tabela de dados. Crie uma tabela de índice chamada IndexOnBeCalledNumber com base na coluna CalledNumber, especifique a coluna CalledNumber como uma coluna de chave primária da tabela de índice e, em seguida, chame a operação GetRange para verificar a tabela de índice e obter as linhas que atendem à condição de consulta.

A primeira coluna de chave primária da tabela de índice difere da primeira coluna de chave primária da tabela de dados. Portanto, o tipo de índice é índice secundário global.

Dados na tabela de índice

A tabela a seguir descreve os dados na 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 para consultar dados, defina os valores máximo e mínimo da coluna CalledNumber como 123456, defina os valores mínimos das colunas CellNumber e StartTime como INT_MIN e defina os valores máximos das colunas CellNumber e StartTime como INT_MAX. Código de exemplo:

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

    // Specify the start primary key column. 
    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());

    // Specify the end primary key column. 
    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("The cell number" + strNum + "is called by the following numbers:");
    while (true) {
        GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
        for (Row row : getRangeResponse.getRows()) {
            System.out.println(row);
        }

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

Consultar as linhas em que o valor da coluna BaseStationNumber é 2 e o valor da coluna StartTime é 1532574740

Esta consulta especifica condições com base nos valores das colunas BaseStationNumber e StartTime. A coluna BaseStationNumber é uma coluna predefinida da tabela de dados. Não é possível consultar diretamente da tabela de dados. Crie uma tabela de índice chamada IndexOnBaseStation1 com base nas colunas BaseStationNumber e StartTime, especifique as colunas BaseStationNumber e StartTime como colunas de chave primária da tabela de índice e, em seguida, chame a operação GetRange para verificar a tabela de índice e obter as linhas que atendem às condições de consulta.

A primeira coluna de chave primária da tabela de índice difere da primeira coluna de chave primária da tabela de dados. Portanto, o tipo de índice é índice secundário global.

Dados na tabela de índice

A tabela a seguir descreve os dados na 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 operação GetRange para consultar dados, defina os valores máximo e mínimo da coluna BaseStationNumber como 2, defina os valores mínimo e máximo da coluna StartTime como 1532574740 e INT_MAX e defina os valores mínimo e máximo da coluna CellNumber como INT_MIN e INT_MAX. Código de exemplo:

// The baseStationNumber parameter in the sample code corresponds to the BaseStationNumber column in the index table. 
// The startTime parameter in the sample code corresponds to the StartTime column in the index table. The startTime parameter specifies the beginning of the time range to query. 
private static void getRangeFromIndexTable(SyncClient client,
                                           long baseStationNumber,
                                           long startTime) {
    RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria(INDEX1_NAME);

    // Specify the start primary key column. 
    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());

    // Specify the end primary key column. 
    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 called numbers forwarded by the base station" + strBaseStationNum + "that start from" + strStartTime + "are listed:");
    while (true) {
        GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
        for (Row row : getRangeResponse.getRows()) {
            System.out.println(row);
        }

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

Consultar os valores da coluna Duration para as linhas em que o valor da coluna BaseStationNumber é 3 e o valor da coluna StartTime varia de 1532574861 a 1532584054

Esta consulta especifica condições com base nos valores das colunas BaseStationNumber e StartTime e retorna apenas os valores da coluna Duration. Consulte dados na tabela de índice IndexOnBaseStation1 criada na seção Consultar as linhas em que o valor da coluna BaseStationNumber é 2 e o valor da coluna StartTime é 1532574740 para obter a chave primária das linhas que atendem às condições de consulta. Em seguida, consulte dados na tabela de dados com base na chave primária para obter os valores da coluna Duration.

A primeira coluna de chave primária da tabela de índice difere da primeira coluna de chave primária da tabela de dados. Portanto, o tipo de índice é índice secundário global.

Código de exemplo:

// The baseStationNumber parameter in the sample code corresponds to the BaseStationNumber column in the index table. 
// The startTime and endTime parameters in the sample code correspond to the StartTime column in the index table. The startTime and endTime parameters specify the beginning and ending of the time range to query. 
// The DEFINED_COL_NAME_2 parameter in the sample code corresponds to the Duration column in the data table. 
private static void getRowFromIndexAndMainTable(SyncClient client,
 long baseStationNumber,
 long startTime,
 long endTime) {
 RangeRowQueryCriteria rangeRowQueryCriteria = new RangeRowQueryCriteria(INDEX1_NAME);

 // Specify the start primary key column. 
 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());

 // Specify the end primary key column. 
 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("The duration of calls forwarded by the base station" + strBaseStationNum + "from" + strStartTime + "to" + strEndTime + "is listed:");
 while (true) {
 GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
 for (Row row : getRangeResponse.getRows()) {
 PrimaryKey curIndexPrimaryKey = row.getPrimaryKey();
 // Specify primary key columns for the data table. 
 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(); 

 // Query data from the data table. 
 SingleRowQueryCriteria criteria = new SingleRowQueryCriteria(TABLE_NAME, mainTablePK);
 // Read data from the Duration column in the data table. 
 criteria.addColumnsToGet(DEFINED_COL_NAME_2); 
 // 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(mainTableRow);
 }

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

Para melhorar a eficiência da consulta, crie uma tabela de índice chamada IndexOnBaseStation2 com base nas colunas BaseStationNumber e StartTime e especifique a coluna Duration como uma coluna de atributo da tabela de índice. Em seguida, chame a operação GetRange para verificar a tabela de índice e obter as linhas que atendem às condições de consulta.

Dados na tabela de índice

A tabela a seguir descreve os dados na 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 chamar a operação GetRange para consultar dados, defina os valores máximo e mínimo da coluna BaseStationNumber como 3, defina os valores mínimo e máximo da coluna StartTime como 1532574861 e 1532584054 e defina os valores mínimo e máximo da coluna CellNumber como INT_MIN e INT_MAX.

Código de exemplo:

// The baseStationNumber parameter in the sample code corresponds to the BaseStationNumber column in the index table. 
// The startTime and endTime parameters in the sample code correspond to the StartTime column in the index table. The startTime and endTime parameters specify the beginning and ending of the time range to query. 
// The DEFINED_COL_NAME_2 parameter in the sample code 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);

 // Specify the start primary key column. 
 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());

 // Specify the end primary key column. 
 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());

 // Specify the column from which data is 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("The duration of calls forwarded by the base station" + strBaseStationNum + "from" + strStartTime + "to" + strEndTime + "is listed:");
 while (true) {
 GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
 for (Row row : getRangeResponse.getRows()) {
 System.out.println(row);
 }

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

Consultar as linhas em que o valor da coluna CellNumber é 456789 e o valor da coluna CalledNumber é 345678

Esta consulta especifica condições com base nos valores das colunas CellNumber e CalledNumber. A coluna CalledNumber é uma coluna predefinida da tabela de dados. Não é possível consultar diretamente da tabela de dados. Crie uma tabela de índice chamada LocalIndexOnBeCalledNumber com base nas colunas CellNumber e CalledNumber, especifique as colunas CellNumber e CalledNumber como colunas de chave primária da tabela de índice e especifique as colunas Duration e BaseStationNumber como colunas de atributo da tabela de índice. Em seguida, chame a operação GetRange para verificar a tabela de índice e obter as linhas que atendem às condições de consulta.

A primeira coluna de chave primária da tabela de índice é igual à primeira coluna de chave primária da tabela de dados. Portanto, o tipo de índice é índice secundário local.

Dados na tabela de índice

A tabela a seguir descreve os dados na 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 para consultar dados, defina os valores máximo e mínimo da coluna CellNumber como 456789, defina os valores máximo e mínimo da coluna CalledNumber como 345678 e defina os valores mínimo e máximo da coluna StartTime como 0 e INT_MAX. Código de exemplo:

// The cellNumber and calledNumber parameters in the sample code 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);

    // Specify the start primary key column. 
    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());

    // Specify the end primary key column. 
    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 records of phone calls between the calling number" + strNum + "and the called number" +strCalledNum+ "are listed:");
    while (true) {
        GetRangeResponse getRangeResponse = client.getRange(new GetRangeRequest(rangeRowQueryCriteria));
        for (Row row : getRangeResponse.getRows()) {
            System.out.println(row);
        }

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

Apêndice: Código de exemplo para criar a tabela de dados e as tabelas de índice secundário

O código de exemplo a seguir mostra como criar a tabela de dados e as tabelas de índice secundário usadas neste tópico. Os tipos de índice incluem índice secundário local e índice secundário global.

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));
    // Specify the Time to Live (TTL) of data. Unit: seconds. The value -1 indicates that the data never expires. You must set the value of timeToLive to -1 if a data table has one or more index tables. 
    int timeToLive = -1; 
    // Specify the maximum number of data versions that can be retained. You must set the value of maxVersions to 1 if a data table has one or more index tables. 
    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 value of indexUpdateMode to IUM_SYNC_INDEX. 
    indexMeta3.setIndexUpdateMode(IUM_SYNC_INDEX);
    // Set the value of indexType to IT_LOCAL_INDEX. 
    indexMeta3.setIndexType(IT_LOCAL_INDEX);
    indexMetas.add(indexMeta3);
 
    CreateTableRequest request = new CreateTableRequest(tableMeta, tableOptions, indexMetas);

    client.createTable(request);
}