Todos os produtos
Search
Central de documentação

Tablestore:Range read

Última atualização: Jul 02, 2026

Leia um intervalo de linhas de uma tabela do Tablestore com o SDK para Go.

Pré-requisitos

Inicializar o cliente do Tablestore

Assinatura do método

func (tableStoreClient *TableStoreClient) GetRange(request *GetRangeRequest) (*GetRangeResponse, error)

Parâmetros de GetRangeRequest

  • RangeRowQueryCriteria (obrigatório)*RangeRowQueryCriteria: Critérios da leitura de intervalo.

    Parâmetro

    Tipo

    Descrição

    TableName (obrigatório)

    string

    Nome da tabela.

    StartPrimaryKey (obrigatório)

    *PrimaryKey

    Chave primária inicial, incluindo nomes e valores das colunas.

    • O conjunto de resultados inclui a linha correspondente à chave primária inicial.

    • A quantidade e os tipos das colunas de chave primária devem corresponder ao esquema da tabela.

    • Na leitura progressiva, a chave primária inicial deve ser menor que a final.

    • Na leitura regressiva, a chave primária inicial deve ser maior que a final.

    • Use AddPrimaryKeyColumnWithMinValue para representar o menor valor possível e AddPrimaryKeyColumnWithMaxValue para o maior valor possível de uma coluna de chave primária.

    EndPrimaryKey (obrigatório)

    *PrimaryKey

    Chave primária final, incluindo nomes e valores das colunas.

    • O conjunto de resultados não inclui a linha correspondente à chave primária final.

    • A quantidade e os tipos das colunas de chave primária devem corresponder ao esquema da tabela.

    • Use AddPrimaryKeyColumnWithMinValue para representar o menor valor possível e AddPrimaryKeyColumnWithMaxValue para o maior valor possível de uma coluna de chave primária.

    Direction (opcional)

    Direction

    Direção da varredura.

    • FORWARD: Leitura progressiva. Valor padrão.

    • BACKWARD: Leitura regressiva.

    MaxVersion (opcional)

    int32

    Número máximo de versões retornadas por coluna.

    • Especifique o número máximo de versões ou um intervalo de tempo.

    • Se houver mais versões correspondentes, apenas as mais recentes até esse limite serão retornadas.

    TimeRange (opcional)

    *TimeRange

    Intervalo de tempo das versões a retornar.

    • Especifique o número máximo de versões ou um intervalo de tempo.

    • Cada coluna de atributo pode ter várias versões. Definir um intervalo de tempo restringe as versões retornadas àquelas dentro desse período.

    Limit (opcional)

    int32

    Número máximo de linhas por resposta. Deve ser maior que 0. Se houver mais linhas correspondentes, a resposta incluirá NextStartPrimaryKey para a próxima página.

    ColumnsToGet (opcional)

    []string

    Colunas a ler. Especifique colunas de chave primária, colunas de atributo ou ambas.

    • Se você omitir este parâmetro, todas as colunas da linha serão retornadas.

    • Se ColumnsToGet estiver definido e uma linha não contiver nenhuma das colunas especificadas, null será retornado para essa linha.

    Filter (opcional)

    ColumnFilter

    Expressão de filtro de coluna. Para obter detalhes, consulte Filtros.

    • Quando ColumnsToGet e Filter estão definidos, o Tablestore primeiro filtra as linhas usando ColumnsToGet e depois aplica Filter.

    TransactionId (opcional)

    *string

    ID da transação local. Para obter mais informações, consulte Transação local.

Código de exemplo

O exemplo a seguir lê linhas da tabela test_table cuja chave primária é maior que row1.

func GetRangeSample(client *tablestore.TableStoreClient) {
    // Build the query criteria.
    rangeRowQueryCriteria := new(tablestore.RangeRowQueryCriteria)
    rangeRowQueryCriteria.TableName = "test_table"
    // Set the start primary key for the query.
    startPK := new(tablestore.PrimaryKey)
    startPK.AddPrimaryKeyColumn("id", "row1")
    rangeRowQueryCriteria.StartPrimaryKey = startPK
    // Set the end primary key for the query. The end primary key is exclusive.
    endPK := new(tablestore.PrimaryKey)
    endPK.AddPrimaryKeyColumnWithMaxValue("id")
    rangeRowQueryCriteria.EndPrimaryKey = endPK
    // Set the maximum number of versions to read per column.
    rangeRowQueryCriteria.MaxVersion = 1

    // Call the GetRange method to query data.
    getRangeRequest := new(tablestore.GetRangeRequest)
    getRangeRequest.RangeRowQueryCriteria = rangeRowQueryCriteria
    getRangeResponse, err := client.GetRange(getRangeRequest)

    // Process the response.
    if err != nil {
        fmt.Println("Range get failed with error: ", err)
    } else {
        fmt.Printf("* RequestId: %s \n", getRangeResponse.RequestId)
        fmt.Printf("* Read CU Cost: %d \n", getRangeResponse.ConsumedCapacityUnit.Read)
        fmt.Printf("* Write CU Cost: %d \n", getRangeResponse.ConsumedCapacityUnit.Write)
        fmt.Println("* Rows Data:")
        for _, row := range getRangeResponse.Rows {
            fmt.Printf("PrimaryKey: %v; Columns: ", row.PrimaryKey.PrimaryKeys)
            for _, column := range row.Columns {
                fmt.Printf("%v ", column)
            }
            fmt.Printf("\n")
        }
    }
}

Cada resposta de GetRange retorna no máximo 5.000 linhas ou 4 MB de dados. Quando o resultado excede esse limite, a resposta inclui um NextStartPrimaryKey para a próxima leitura. Use o loop a seguir para iterar até ler todas as linhas.

for {
    // Call the GetRange method to query data.
    getRangeRequest := new(tablestore.GetRangeRequest)
    getRangeRequest.RangeRowQueryCriteria = rangeRowQueryCriteria
    getRangeResponse, err := client.GetRange(getRangeRequest)
    // Process the response.
    if err != nil {
        fmt.Println("Range get failed with error: ", err)
        break
    } else {
        fmt.Printf("* RequestId: %s \n", getRangeResponse.RequestId)
        fmt.Printf("* Read CU Cost: %d \n", getRangeResponse.ConsumedCapacityUnit.Read)
        fmt.Printf("* Write CU Cost: %d \n", getRangeResponse.ConsumedCapacityUnit.Write)
        fmt.Printf("* Rows Count: %d \n", len(getRangeResponse.Rows))
        fmt.Println("* Rows Data:")
        for _, row := range getRangeResponse.Rows {
            fmt.Printf("PrimaryKey: %v; Columns: ", row.PrimaryKey.PrimaryKeys)
            for _, column := range row.Columns {
                fmt.Printf("%v ", column)
            }
            fmt.Printf("\n")
        }
    }
    // Set the start primary key for the next iteration.
    if getRangeResponse.NextStartPrimaryKey != nil {
        startPK := new(tablestore.PrimaryKey)
        startPK.AddPrimaryKeyColumn("id", getRangeResponse.NextStartPrimaryKey.PrimaryKeys[0].Value)
        rangeRowQueryCriteria.StartPrimaryKey = startPK
    } else {
        break
    }
}

Você também pode aplicar as seguintes configurações opcionais na consulta.

  • Defina a direção da leitura.

    // Set the direction to backward.
    rangeRowQueryCriteria.Direction = tablestore.BACKWARD
    // Set the start primary key. For a backward read, the start primary key must be greater than the end primary key.
    startPK := new(tablestore.PrimaryKey)
    startPK.AddPrimaryKeyColumnWithMaxValue("id")
    rangeRowQueryCriteria.StartPrimaryKey = startPK
    // Set the end primary key. The end primary key is exclusive.
    endPK := new(tablestore.PrimaryKey)
    endPK.AddPrimaryKeyColumn("id", "row1")
    rangeRowQueryCriteria.EndPrimaryKey = endPK
  • Configure um intervalo de tempo para retornar apenas versões dentro dessa janela.

    // Set the time range for the query to the last 24 hours.
    timeRange := new(tablestore.TimeRange)
    timeRange.Start = int64(time.Now().Unix() * 1000 - 86400 * 1000) 
    timeRange.End = int64(time.Now().Unix() * 1000) 
    rangeRowQueryCriteria.TimeRange = timeRange;
  • Retorne apenas as colunas de atributo especificadas.

    rangeRowQueryCriteria.AddColumnToGet("col1")
  • Limite o número de linhas retornadas por solicitação.

    rangeRowQueryCriteria.Limit = 10

Referências

Leitura de dados em lote