Todos os produtos
Search
Central de documentação

Tablestore:Batch read data

Última atualização: Jun 30, 2026

Leia linhas de uma ou mais tabelas do Tablestore em uma única solicitação com o SDK para Go.

Observações de uso

Uma única solicitação de leitura em lote retorna até 100 linhas.

Pré-requisitos

Inicializar um cliente do Tablestore

Método

func (tableStoreClient *TableStoreClient) BatchGetRow(request *BatchGetRowRequest) (*BatchGetRowResponse, error)

Referência de parâmetros do BatchGetRowRequest

  • MultiRowQueryCriteria (obrigatório)[]*MultiRowQueryCriteria: Critérios de consulta que definem as tabelas e as linhas a ler.

    Parâmetro

    Tipo

    Descrição

    TableName (obrigatório)

    string

    Nome da tabela a ler.

    PrimaryKey (obrigatório)

    []*PrimaryKey

    Chaves primárias das linhas a ler.

    • Tipos de coluna de chave primária compatíveis: STRING, INTEGER e BINARY.

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

    MaxVersion (opcional)

    int

    Número máximo de versões a retornar por célula.

    • Especifique este parâmetro ou TimeRange.

    • Se houver mais versões que o limite especificado, o Tablestore retorna primeiro as mais recentes.

    TimeRange (opcional)

    *TimeRange

    Intervalo de tempo das versões de célula a retornar.

    • Especifique este parâmetro ou MaxVersion.

    • Cada coluna de atributo pode armazenar várias versões. Ao definir este parâmetro, apenas as versões dentro do intervalo especificado são retornadas.

    ColumnsToGet (opcional)

    []string

    Nomes das colunas a retornar. Especifique colunas de chave primária, colunas de atributo ou ambas.

    • Se omitido, todas as colunas da linha são retornadas.

    • Se uma linha não contiver nenhuma das colunas solicitadas, o resultado dessa linha será nulo.

    Filter (opcional)

    ColumnFilter

    Condição de filtro. Para obter mais informações, consulte Filtros.

    • Se ColumnsToGet e Filter forem definidos simultaneamente, o Tablestore recupera primeiro as colunas indicadas por ColumnsToGet e depois aplica o Filter ao resultado. Apenas as linhas correspondentes ao filtro são retornadas, contendo exclusivamente as colunas especificadas em ColumnsToGet.

Código de exemplo

O exemplo a seguir lê duas linhas cujas chaves primárias são row1 e row2 da tabela test_table.

func BatchGetRowSample(client *tablestore.TableStoreClient) {
    // Construct the query criteria.
    multiRowQueryCriteria := new(tablestore.MultiRowQueryCriteria)
    // Set the table name.
    multiRowQueryCriteria.TableName = "test_table"
    // Add the primary key for the first row.
    getPk1 := new(tablestore.PrimaryKey)
    getPk1.AddPrimaryKeyColumn("id", "row1")
    multiRowQueryCriteria.AddRow(getPk1)
    // Add the primary key for the second row.
    getPk2 := new(tablestore.PrimaryKey)
    getPk2.AddPrimaryKeyColumn("id", "row2")
    multiRowQueryCriteria.AddRow(getPk2)
    // Set the maximum number of versions to return.
    multiRowQueryCriteria.MaxVersion = 1

    // Call the BatchGetRow method.
    batchGetRowRequest := new(tablestore.BatchGetRowRequest)
    batchGetRowRequest.MultiRowQueryCriteria = append(batchGetRowRequest.MultiRowQueryCriteria, multiRowQueryCriteria)
    batchGetRowResponse, err := client.BatchGetRow(batchGetRowRequest)

    // Process the response.
    if err != nil {
        fmt.Println("Batch get row failed with error: ", err)
    } else {
        fmt.Printf("* RequestId: %s \n", batchGetRowResponse.RequestId)
        for tableName, rows := range batchGetRowResponse.TableToRowsResult {
            fmt.Printf("* Table: %s \n", tableName)
            for _, row := range rows {
                if row.IsSucceed {
                    fmt.Printf("Succeeded Row: %v \n", row)
                } else {
                    fmt.Printf("Failed Row: %d | %v \n", row.Index, row.Error)
                }
            }
        }
    }
}

Os trechos a seguir demonstram como configurar os parâmetros opcionais de leitura em lote.

  • Para ler de múltiplas tabelas em uma única solicitação, adicione um objeto MultiRowQueryCriteria separado para cada tabela.

    // Construct the query criteria for the second table.
    multiRowQueryCriteria1 := new(tablestore.MultiRowQueryCriteria)
    multiRowQueryCriteria1.TableName = "orders_small"
    // Add the primary key for the first row.
    getPk3 := new(tablestore.PrimaryKey)
    getPk3.AddPrimaryKeyColumn("order_id", "90fb478c-1360-11f0-a34d-00163e30a2a9")
    multiRowQueryCriteria1.AddRow(getPk3)
    // Set the maximum number of versions to return.
    multiRowQueryCriteria1.MaxVersion = 1
    // Add the MultiRowQueryCriteria object to the request.
    batchGetRowRequest.MultiRowQueryCriteria = append(batchGetRowRequest.MultiRowQueryCriteria, multiRowQueryCriteria1)
  • Para restringir a leitura a um intervalo específico de versões, defina TimeRange. Somente os dados dentro do intervalo especificado serão retornados.

    // Set the version range 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) 
    multiRowQueryCriteria.TimeRange = timeRange
  • Especifique colunas de atributo específicas para leitura.

    multiRowQueryCriteria.AddColumnToGet("col1")

Tópicos relacionados

Ler dados dentro de um intervalo