Todos os produtos
Search
Central de documentação

Tablestore:Filters

Última atualização: Jul 03, 2026

O Tablestore avalia filtros no servidor para retornar linhas correspondentes às condições especificadas. Configure filtros no SDK em Go conforme descrito nesta página.

Pré-requisitos

Inicializar um cliente do Tablestore

Tipos de filtro

O Tablestore oferece três tipos de filtro:

  • Filtro de valor de coluna única (SingleColumnCondition): avalia se o valor de uma coluna de atributo atende a uma condição.

  • Filtro regex de valor de coluna única (SingleColumnValueRegexFilter): em uma coluna de atributo do tipo string, faz a correspondência de uma substring com uma expressão regular, converte-a para um tipo específico e a avalia em relação a uma condição.

  • Filtro composto (CompositeColumnCondition): combina várias condições por meio de operadores lógicos.

Filtro de valor de coluna única

func NewSingleColumnCondition(columnName string, comparator ComparatorType, value interface{}) *SingleColumnCondition

Parâmetros

Parâmetro

Tipo

Descrição

Comparator (Obrigatório)

ComparatorType

Operador relacional. Valores permitidos: CT_EQUAL (igual a), CT_NOT_EQUAL (diferente de), CT_GREATER_THAN (maior que), CT_GREATER_EQUAL (maior ou igual a), CT_LESS_THAN (menor que) e CT_LESS_EQUAL (menor ou igual a).

ColumnName (Obrigatório)

string

Nome da coluna de atributo a avaliar.

ColumnValue (Obrigatório)

interface{}

Valor para comparação.

FilterIfMissing (Opcional)

bool

Quando falso (padrão), o sistema ainda retorna linhas sem a coluna de atributo. Defina como verdadeiro para excluir essas linhas.

LatestVersionOnly (Opcional)

bool

Quando falso (padrão), qualquer versão da coluna pode satisfazer a condição. Defina como verdadeiro para avaliar apenas a versão mais recente.

Código de exemplo

Este exemplo executa uma consulta de intervalo nas chaves primárias [ e mantém as linhas cujo atributo col1 seja igual a val1.

func SingleValueFilterSample(client *tablestore.TableStoreClient) {
    // Construct the query criteria.
    rangeRowQueryCriteria := &tablestore.RangeRowQueryCriteria{}
    rangeRowQueryCriteria.TableName = "test_table"
    // Set the start primary key.
    startPK := new(tablestore.PrimaryKey)
    startPK.AddPrimaryKeyColumn("id", "row1")
    rangeRowQueryCriteria.StartPrimaryKey = startPK
    // Set the end primary key. The row with this key is not included in the result.
    endPK := new(tablestore.PrimaryKey)
    endPK.AddPrimaryKeyColumn("id", "row3")
    rangeRowQueryCriteria.EndPrimaryKey = endPK
    // Set the number of versions to query.
    rangeRowQueryCriteria.MaxVersion = 1

    // Construct a filter where col1 equals "val1".
    singleColumnCondition := tablestore.NewSingleColumnCondition("col1", tablestore.CT_EQUAL, "val1")
    rangeRowQueryCriteria.Filter = singleColumnCondition

    // Call the GetRange operation 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")
        }
    }
}
  • Defina FilterIfMissing como true para descartar linhas sem a coluna de atributo.

    singleColumnCondition.FilterIfMissing = true
  • Defina LatestVersionOnly como true para usar apenas a versão mais recente da coluna de atributo.

    singleColumnCondition.LatestVersionOnly = true

Filtro regex de valor de coluna única

Use filtros regex apenas em colunas de atributo do tipo string.

func NewSingleColumnValueRegexFilter(columnName string, comparator ComparatorType, rule *ValueTransferRule, value interface{}) *SingleColumnCondition

Parâmetros

Parâmetro

Tipo

Descrição

Comparator (Obrigatório)

ComparatorType

Operador relacional. Valores permitidos: CT_EQUAL (igual a), CT_NOT_EQUAL (diferente de), CT_GREATER_THAN (maior que), CT_GREATER_EQUAL (maior ou igual a), CT_LESS_THAN (menor que) e CT_LESS_EQUAL (menor ou igual a).

ColumnName (Obrigatório)

string

Nome da coluna de atributo a avaliar.

ColumnValue (Obrigatório)

interface{}

Valor para comparação.

TransferRule (Obrigatório)

ValueTransferRule

Regra de correspondência regex com os seguintes campos:

  • Regex (Obrigatório) string: padrão para corresponder a uma substring; comprimento máximo de 256 bytes.

    • Compatível com Expressões Regulares Compatíveis com Perl (PCRE) e regex de byte único.

    • Não há suporte para caracteres chineses em padrões regex.

    • Grupos de captura são permitidos; o sistema utiliza a primeira substring capturada. Exemplo: valor da coluna 1aaa51bbb5, padrão 1([a-z]+)5 resulta em aaa.

  • Cast_type (Obrigatório) VariantType: tipo de destino para a substring correspondente. Valores: Variant_INTEGER (inteiro), Variant_DOUBLE (ponto flutuante de precisão dupla) e Variant_STRING (string).

Código de exemplo

Este exemplo executa uma consulta de intervalo nas chaves primárias [ e mantém as linhas em que col1 corresponde a 1([a-z]+)5 com a substring capturada aaa.

func SingleRegexFilterSample(client *tablestore.TableStoreClient) {
    // Construct the query criteria.
    rangeRowQueryCriteria := &tablestore.RangeRowQueryCriteria{}
    rangeRowQueryCriteria.TableName = "test_table"
    // Set the start primary key.
    startPK := new(tablestore.PrimaryKey)
    startPK.AddPrimaryKeyColumn("id", "row1")
    rangeRowQueryCriteria.StartPrimaryKey = startPK
    // Set the end primary key. The row with this key is not included in the result.
    endPK := new(tablestore.PrimaryKey)
    endPK.AddPrimaryKeyColumn("id", "row3")
    rangeRowQueryCriteria.EndPrimaryKey = endPK
    // Set the number of versions to query.
    rangeRowQueryCriteria.MaxVersion = 1

    // Construct the filter: cast<String>(reg(col1)) == "aaa"
    valueTransferRule := tablestore.NewValueTransferRule("1([a-z]+)5", tablestore.Variant_STRING)
    singleColumnValueRegexFilter := tablestore.NewSingleColumnValueRegexFilter("col1", tablestore.CT_EQUAL, valueTransferRule, "aaa")
    rangeRowQueryCriteria.Filter = singleColumnValueRegexFilter

    // Call the GetRange operation 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")
        }
    }
}

Filtro composto

Os filtros compostos aceitam até 32 condições aninhadas.

func NewCompositeColumnCondition(lo LogicalOperator) *CompositeColumnCondition

Parâmetros

Parâmetro

Tipo

Descrição

Operator (Obrigatório)

LogicalOperator

Operador lógico. Valores permitidos: LO_NOT (não), LO_AND (e) e LO_OR (ou).

Filters (Obrigatório)

[]ColumnFilter

Filtros filhos combinados pelo operador: SingleColumnCondition, SingleColumnValueRegexFilter ou CompositeColumnCondition aninhado.

Código de exemplo

Este exemplo executa uma consulta de intervalo nas chaves primárias [ e aplica um filtro composto para restringir o conjunto de resultados.

func CompositeFilterSample(client *tablestore.TableStoreClient) {
    // Construct the query criteria.
    rangeRowQueryCriteria := &tablestore.RangeRowQueryCriteria{}
    rangeRowQueryCriteria.TableName = "test_table"
    // Set the start primary key.
    startPK := new(tablestore.PrimaryKey)
    startPK.AddPrimaryKeyColumn("id", "row1")
    rangeRowQueryCriteria.StartPrimaryKey = startPK
    // Set the end primary key. The row with this key is not included in the result.
    endPK := new(tablestore.PrimaryKey)
    endPK.AddPrimaryKeyColumn("id", "row3")
    rangeRowQueryCriteria.EndPrimaryKey = endPK
    // Set the number of versions to query.
    rangeRowQueryCriteria.MaxVersion = 1

    // Construct the first single-column value filter: col1 == "val1".
    singleColumnCondition1 := tablestore.NewSingleColumnCondition("col1", tablestore.CT_EQUAL, "val1")
    // Construct the single-column regex filter: cast<String>(reg(col2)) == "aaa".
    valueTransferRule := tablestore.NewValueTransferRule("1([a-z]+)5", tablestore.Variant_STRING)
    singleColumnValueRegexFilter2 := tablestore.NewSingleColumnValueRegexFilter("col2", tablestore.CT_EQUAL, valueTransferRule, "aaa")
    // Construct the first composite filter: col1 == "val1" OR cast<String>(reg(col2)) == "aaa".
    compositeCondition1 := tablestore.NewCompositeColumnCondition(tablestore.LO_OR)
    compositeCondition1.AddFilter(singleColumnCondition1)
    compositeCondition1.AddFilter(singleColumnValueRegexFilter2)
    // Construct the second single-column value filter: col3 == "val3".
    singleColumnCondition3 := tablestore.NewSingleColumnCondition("col3", tablestore.CT_EQUAL, "val3")
    // Construct the final composite filter: (col1 == "val1" OR cast<String>(reg(col2)) == "aaa") AND col3 == "val3".
    compositeCondition2 := tablestore.NewCompositeColumnCondition(tablestore.LO_AND)
    compositeCondition2.AddFilter(compositeCondition1)
    compositeCondition2.AddFilter(singleColumnCondition3)

    // Add the filter to the query.
    rangeRowQueryCriteria.Filter = compositeCondition2

    // Call the GetRange operation 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")
        }
    }
}

Tópicos relacionados