Todos os produtos
Search
Central de documentação

Tablestore:Consulta de frase correspondente

Última atualização: Jul 08, 2026

A consulta de frase correspondente assemelha-se à consulta de correspondência, mas avalia as posições dos tokens. Uma linha atende à condição de consulta apenas quando a ordem e as posições dos tokens na linha coincidem com a ordem e as posições dos tokens contidos na palavra-chave. Se o método de tokenização da coluna consultada for a tokenização difusa, a consulta de frase correspondente apresentará latência menor que a consulta com curinga.

Pré-requisitos

Parâmetros

Parâmetro

Descrição

TableName

Nome da tabela de dados.

IndexName

Nome do índice de pesquisa.

Query

Tipo da consulta. Defina como MatchPhraseQuery.

FieldName

Nome do campo a ser correspondido.

É possível executar consultas de frase correspondente em colunas TEXT.

Text

Palavra-chave usada para corresponder aos valores da coluna durante a consulta de frase correspondente.

Se a coluna consultada for do tipo TEXT, a palavra-chave será tokenizada conforme o analisador especificado na criação do índice de pesquisa. Sem essa definição, aplica-se por padrão a tokenização de palavra única. Para mais informações, consulte Tokenização.

Por exemplo, ao buscar a frase "this is", os resultados incluirão "..., this is tablestore" e "this is a table". Já "this table is ..." ou "is this a table" não serão retornados.

Offset

Posição inicial da consulta atual.

Limit

Número máximo de linhas a retornar na consulta atual.

Para obter apenas a contagem de linhas correspondentes, sem recuperar dados específicos, defina Limit como 0.

GetTotalCount

Define se o total de linhas correspondentes deve ser retornado. Valor padrão: false.

Habilitar este parâmetro (true) pode comprometer o desempenho da consulta.

ColumnsToGet

Indica se todas as colunas das linhas correspondentes devem ser retornadas. Configure os parâmetros ReturnAll e Columns.

O valor padrão de ReturnAll é false,

ou seja, nem todas as colunas são retornadas. Nesse caso, use Columns para especificar quais deseja recuperar. Sem essa definição, apenas as colunas de chave primária serão incluídas.

Ao definir ReturnAll como true, todas as colunas serão incluídas no resultado.

Código de exemplo

O exemplo abaixo demonstra como consultar linhas nas quais o valor da coluna Col_Text corresponde exatamente à frase completa "hangzhou shanghai", respeitando a ordem, na tabela de dados:

/**
 * Query the rows in which the value of the Col_Text column matches the whole phase "hangzhou shanghai" in order in a table. Tablestore returns the total number of rows that meet the query conditions and part of the matched rows. 
 */
func MatchPhraseQuery(client *tablestore.TableStoreClient, tableName string, indexName string) {
    searchRequest := &tablestore.SearchRequest{}
    searchRequest.SetTableName(tableName)
    searchRequest.SetIndexName(indexName)
    query := &search.MatchPhraseQuery{} // Set the query type to MatchPhraseQuery. 
    query.FieldName = "Col_Text"  // Specify the name of the column that you want to query. 
    query.Text = "hangzhou shanghai"  // Specify the keyword that is used to match the value of the column. 
    searchQuery := search.NewSearchQuery()
    searchQuery.SetQuery(query)
    searchQuery.SetGetTotalCount(true) 
    searchQuery.SetOffset(0) // Set the Offset parameter to 0. 
    searchQuery.SetLimit(20) // Set the Limit parameter to 20, which indicates a maximum of 20 rows can be returned. 
    searchRequest.SetSearchQuery(searchQuery)
    searchResponse, err := client.Search(searchRequest)
    if err != nil {
        fmt.Printf("%#v", err)
        return
    }
    fmt.Println("IsAllSuccess: ", searchResponse.IsAllSuccess) // Check whether all rows that meet the query conditions are returned. 
    fmt.Println("TotalCount: ", searchResponse.TotalCount) // Display the total number of rows that meet the query conditions. 
    fmt.Println("RowCount: ", len(searchResponse.Rows))
    for _, row := range searchResponse.Rows {
        jsonBody, err := json.Marshal(row)
        if err != nil {
            panic(err)
        }
        fmt.Println("Row: ", string(jsonBody))
    }
    // Return all columns in the rows that meet the query conditions. 
    searchRequest.SetColumnsToGet(&tablestore.ColumnsToGet{
        ReturnAll:true,
    })
    searchResponse, err = client.Search(searchRequest)
    if err != nil {
        fmt.Printf("%#v", err)
        return
    }
    fmt.Println("IsAllSuccess: ", searchResponse.IsAllSuccess) // Check whether all rows that meet the query conditions are returned. 
    fmt.Println("TotalCount: ", searchResponse.TotalCount) // Display the total number of rows that meet the query conditions. 
    fmt.Println("RowCount: ", len(searchResponse.Rows))
    for _, row := range searchResponse.Rows {
        jsonBody, err := json.Marshal(row)
        if err != nil {
            panic(err)
        }
        fmt.Println("Row: ", string(jsonBody))
    }
}

Perguntas frequentes

Referências