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 que você deseja recuperar, 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 principal.

  • Caso as colunas de atributo desejadas não estejam presentes na tabela de índice, busque os dados na tabela primária.

Ler uma única linha de dados

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

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 que não foram 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

O código de exemplo abaixo demonstra como ler uma linha de dados em uma tabela de índice com base na chave primária dessa linha:

func GetRowFromIndex(client *tablestore.TableStoreClient, indexName string) {
    getRowRequest := new(tablestore.GetRowRequest)
    criteria := new(tablestore.SingleRowQueryCriteria);
    // Construct the primary key. If you want to read data from a local secondary index, the first primary key column of the index table must be the same as the first primary key column of the data table. 
    putPk := new(tablestore.PrimaryKey)
    putPk.AddPrimaryKeyColumn("definedcol1", "value1")
    putPk.AddPrimaryKeyColumn("pk1", int64(2))
    putPk.AddPrimaryKeyColumn("pk2", []byte("pk2"))
    criteria.PrimaryKey = putPk
  
    getRowRequest.SingleRowQueryCriteria = criteria
    getRowRequest.SingleRowQueryCriteria.TableName = indexName 
    getRowRequest.SingleRowQueryCriteria.MaxVersion = 1  
    getResp, err := client.GetRow(getRowRequest)
    if err != nil {
        fmt.Println("getrow failed with error:", err)
    } else {
        fmt.Println("get row", getResp.Columns[0].ColumnName,"result is ", getResp.Columns[0].Value,)
    }                   
}

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 dados com valores de chave primária dentro de um intervalo específico.

Parâmetros

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

  • Especifique o nome da tabela de índice no parâmetro TableName.

  • Como o Tablestore incorpora automaticamente as colunas de chave primária da tabela de dados (não definidas como colunas de índice) à tabela de índice como suas chaves primárias, é obrigatório especificar tanto as colunas de índice originais quanto as chaves primárias da tabela de dados ao definir as chaves primárias inicial e final do intervalo de consulta.

Exemplos

Usar índices secundários globais

O exemplo a seguir 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 é definedcol1, e o valor definido para essa coluna no intervalo é value1.

func GetRangeFromGlobalIndex(client *tablestore.TableStoreClient, indexName string) {
    getRangeRequest := &tablestore.GetRangeRequest{}
    rangeRowQueryCriteria := &tablestore.RangeRowQueryCriteria{}
    rangeRowQueryCriteria.TableName = indexName

    // Construct the start primary key of the range. The range of the primary key value is a left-closed, right-opened interval. 
    startPK := new(tablestore.PrimaryKey)
    // Specify a value for the first primary key column. 
    startPK.AddPrimaryKeyColumn("definedcol1", "value1") 
    // Specify a value for the second primary key column. The second primary key column is a primary key column of the data table that is not used as an index column of the global secondary index. 
    startPK.AddPrimaryKeyColumnWithMinValue("pk1") 
    // Specify a value for the third primary key column. The third primary key column is a primary key column of the data table that is not used as an index column of the global secondary index. 
    startPK.AddPrimaryKeyColumnWithMinValue("pk2") 

    endPK := new(tablestore.PrimaryKey)
    endPK.AddPrimaryKeyColumn("definedcol1", "value1")
    endPK.AddPrimaryKeyColumnWithMaxValue("pk1")  
    endPK.AddPrimaryKeyColumnWithMaxValue("pk2")
    rangeRowQueryCriteria.StartPrimaryKey = startPK
    rangeRowQueryCriteria.EndPrimaryKey = endPK
    rangeRowQueryCriteria.Direction = tablestore.FORWARD
    rangeRowQueryCriteria.MaxVersion = 1
    rangeRowQueryCriteria.Limit = 10
    getRangeRequest.RangeRowQueryCriteria = rangeRowQueryCriteria

    getRangeResp, err := client.GetRange(getRangeRequest)

    fmt.Println("get range result is ", getRangeResp)

    for {
        if err != nil {
            fmt.Println("get range failed with error:", err)
        }
        if len(getRangeResp.Rows) > 0 {
            for _, row := range getRangeResp.Rows {
                fmt.Println("range get row with key", row.PrimaryKey.PrimaryKeys[0].Value, row.PrimaryKey.PrimaryKeys[1].Value, row.PrimaryKey.PrimaryKeys[2].Value)
            }
            if getRangeResp.NextStartPrimaryKey == nil {
                break
            } else {
                fmt.Println("next pk is :", getRangeResp.NextStartPrimaryKey.PrimaryKeys[0].Value, getRangeResp.NextStartPrimaryKey.PrimaryKeys[1].Value, getRangeResp.NextStartPrimaryKey.PrimaryKeys[2].Value)
                getRangeRequest.RangeRowQueryCriteria.StartPrimaryKey = getRangeResp.NextStartPrimaryKey
                getRangeResp, err = client.GetRange(getRangeRequest)
            }
        } else {
            break
        }

        fmt.Println("continue to query rows")
    }
    fmt.Println("getrow finished")
}

Usar índices secundários locais

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

func GetRangeFromLocalIndex(client *tablestore.TableStoreClient, indexName string) {
    getRangeRequest := &tablestore.GetRangeRequest{}
    rangeRowQueryCriteria := &tablestore.RangeRowQueryCriteria{}
    rangeRowQueryCriteria.TableName = indexName
  
    // Construct the start primary key of the range. The range of the primary key value is a left-closed, right-opened interval. 
    startPK := new(tablestore.PrimaryKey)
    // Specify a value for the first primary key column. 
    startPK.AddPrimaryKeyColumnWithMinValue("pk1")
    // Specify a value for the second primary key column. 
    startPK.AddPrimaryKeyColumnWithMinValue("definedcol1") 
    // Specify a value for the third primary key column. The third primary key column is a primary key column of the data table that is not used as an index column of the global secondary index. 
    startPK.AddPrimaryKeyColumnWithMinValue("pk2") 
   
    // Construct the end primary key of the range. 
    endPK := new(tablestore.PrimaryKey)
    endPK.AddPrimaryKeyColumnWithMaxValue("pk1")
    endPK.AddPrimaryKeyColumnWithMaxValue("definedcol1")  
    endPK.AddPrimaryKeyColumnWithMaxValue("pk2")
    rangeRowQueryCriteria.StartPrimaryKey = startPK
    rangeRowQueryCriteria.EndPrimaryKey = endPK
    rangeRowQueryCriteria.Direction = tablestore.FORWARD
    rangeRowQueryCriteria.MaxVersion = 1
    rangeRowQueryCriteria.Limit = 10
    getRangeRequest.RangeRowQueryCriteria = rangeRowQueryCriteria

    getRangeResp, err := client.GetRange(getRangeRequest)

    fmt.Println("get range result is ", getRangeResp)

    for {
        if err != nil {
            fmt.Println("get range failed with error:", err)
        }
        if len(getRangeResp.Rows) > 0 {
            for _, row := range getRangeResp.Rows {
                fmt.Println("range get row with key", row.PrimaryKey.PrimaryKeys[0].Value, row.PrimaryKey.PrimaryKeys[1].Value, row.PrimaryKey.PrimaryKeys[2].Value)
                // To return the attribute columns of the index table, write code based on the following sample code. 
                //fmt.Println("get row", row.Columns[0].ColumnName, "result is ", row.Columns[0].Value)
            }
            if getRangeResp.NextStartPrimaryKey == nil {
                break
            } else {
                fmt.Println("next pk is :", getRangeResp.NextStartPrimaryKey.PrimaryKeys[0].Value, getRangeResp.NextStartPrimaryKey.PrimaryKeys[1].Value, getRangeResp.NextStartPrimaryKey.PrimaryKeys[2].Value)
                getRangeRequest.RangeRowQueryCriteria.StartPrimaryKey = getRangeResp.NextStartPrimaryKey
                getRangeResp, err = client.GetRange(getRangeRequest)
            }
        } else {
            break
        }

        fmt.Println("continue to query rows")
    }
    fmt.Println("getrow finished")
}

Perguntas frequentes

Referências

  • Para cenários que exigem consultas multidimensionais e análise de dados, crie um índice de pesquisa e configure os atributos necessários como campos desse índice. Assim, você poderá consultar e analisar dados usando o índice de pesquisa, realizando buscas por colunas que não são de chave primária, consultas booleanas e consultas difusas. Também é possível obter valores máximos e mínimos, contabilizar linhas e agrupar resultados. Para mais informações, consulte Índice de pesquisa.

  • Se preferir executar instruções SQL para consultar e analisar dados, utilize o recurso de consulta SQL. Para mais informações, consulte Consulta SQL.