Uma consulta booleana combina várias subconsultas para recuperar linhas de uma tabela de dados. O Tablestore retorna apenas as linhas que atendem às condições combinadas. Cada subconsulta pode ser de qualquer tipo, inclusive outra consulta booleana.
Prerequisites
-
An OTSClient instance is initialized. For more information, see Initialize an OTSClient instance.
-
A data table is created and data is written to the data table. For more information, see Create a data table and Write data.
-
A search index is created for the data table. For more information, see Create search indexes.
Parâmetros
|
Parâmetro |
Descrição |
|
TableName |
Nome da tabela de dados. |
|
IndexName |
Nome do índice de pesquisa. |
|
MustQueries |
Operador lógico AND. Todas as subconsultas nesta lista devem corresponder. O sistema retorna apenas as linhas que satisfazem todas as condições. |
|
MustNotQueries |
Operador lógico NOT. O sistema exclui dos resultados as linhas que correspondem a qualquer subconsulta nesta lista. |
|
FilterQueries |
Operador lógico AND aplicado como filtro. O sistema retorna apenas as linhas que satisfazem todos os subfiltros. Diferentemente de MustQueries, FilterQueries não calcula pontuação de relevância. Esse parâmetro executa uma correspondência binária (sim ou não), ideal para correspondências exatas, intervalos e condições numéricas. |
|
ShouldQueries |
Operador lógico OR. Retorna as linhas que correspondem ao número mínimo de subconsultas. A correspondência com mais subconsultas aumenta a pontuação de relevância da linha. Se nenhuma condição MustQueries, MustNotQueries ou FilterQueries estiver definida, pelo menos uma ShouldQuery deve corresponder. Quando outras condições existem, ShouldQueries atuam como reforços opcionais de relevância, com mínimo padrão de 0. Defina MinimumShouldMatch para substituir o valor padrão. |
|
MinimumShouldMatch |
Número mínimo de condições ShouldQueries que uma linha deve satisfazer para retornar nos resultados. O padrão é 1 quando ShouldQueries é a única condição e 0 quando condições MustQueries, MustNotQueries ou FilterQueries também estão presentes. |
Código de exemplo
Os exemplos a seguir demonstram como construir uma consulta booleana. O primeiro usa MustQueries para exigir todas as condições; o segundo utiliza ShouldQueries para requerer pelo menos uma condição.
/**
* Perform a Boolean query based on a combination of subqueries.
*/
func BoolQuery(client *tablestore.TableStoreClient, tableName string, indexName string) {
searchRequest := &tablestore.SearchRequest{}
searchRequest.SetTableName(tableName)
searchRequest.SetIndexName(indexName)
// Condition 1: range query — Col_Long > 3
rangeQuery := &search.RangeQuery{}
rangeQuery.FieldName = "Col_Long"
rangeQuery.GT(3)
// Condition 2: match query — Col_Keyword contains "hangzhou"
matchQuery := &search.MatchQuery{}
matchQuery.FieldName = "Col_Keyword"
matchQuery.Text = "hangzhou"
{
// MustQueries: both conditions must match (AND)
boolQuery := &search.BoolQuery{
MustQueries: []search.Query{
rangeQuery,
matchQuery,
},
}
searchQuery := search.NewSearchQuery()
searchQuery.SetQuery(boolQuery)
searchRequest.SetSearchQuery(searchQuery)
searchResponse, err := client.Search(searchRequest)
if err != nil {
fmt.Printf("%#v", err)
return
}
fmt.Println("IsAllSuccess: ", searchResponse.IsAllSuccess) // Whether all matching rows were returned
fmt.Println("TotalCount: ", searchResponse.TotalCount) // Total rows matching the query
fmt.Println("RowCount: ", len(searchResponse.Rows))
}
{
// ShouldQueries: at least one condition must match (OR)
boolQuery := &search.BoolQuery{
ShouldQueries: []search.Query{
rangeQuery,
matchQuery,
},
MinimumShouldMatch: proto.Int32(1),
}
searchQuery := search.NewSearchQuery()
searchQuery.SetQuery(boolQuery)
searchRequest.SetSearchQuery(searchQuery)
searchResponse, err := client.Search(searchRequest)
if err != nil {
fmt.Printf("%#v", err)
return
}
fmt.Println("IsAllSuccess: ", searchResponse.IsAllSuccess) // Whether all matching rows were returned
fmt.Println("TotalCount: ", searchResponse.TotalCount) // Total rows matching the query
fmt.Println("RowCount: ", len(searchResponse.Rows))
}
}
Perguntas frequentes
Referências
When you use a search index to query data, you can use the following query methods: term query, terms query, match all query, match query, match phrase query, prefix query, range query, wildcard query, geo query, Boolean query, KNN vector query, nested query, and exists query. You can use the query methods provided by the search index to query data from multiple dimensions based on your business requirements.
You can sort or paginate rows that meet the query conditions by using the sorting and paging features. For more information, see Sorting and Paging.
You can use the collapse (distinct) feature to collapse the result set based on a specific column. This way, data of the specified type appears only once in the query results. For more information, see Collapse (deduplicate).
If you want to analyze data in a data table, you can use the aggregation feature of the Search operation or execute SQL statements. For example, you can obtain the minimum and maximum values, sum, and total number of rows. For more information, see Aggregation and SQL query.
If you want to obtain all rows that meet the query conditions without the need to sort the rows, you can call the ParallelScan and ComputeSplits operations to use the parallel scan feature. For more information, see Perform a parallel scan.