Uma consulta booleana (BoolQuery) contém uma ou mais subconsultas e as utiliza para verificar se uma linha atende às condições especificadas. Cada subconsulta pode ser de qualquer tipo, inclusive outra consulta booleana.
Pré-requisitos
Instância do OTSClient inicializada. Para mais informações, consulte Initialize an OTSClient instance.
Tabela de dados criada e preenchida. Para mais informações, consulte Create data tables e Write data.
Índice de busca criado para a tabela de dados. Para mais informações, consulte Create a search index.
Parâmetros
|
Parâmetro |
Descrição |
|
tableName |
Nome da tabela de dados. |
|
indexName |
Nome do índice de busca. |
|
mustQueries |
Lista de consultas. A linha deve corresponder a todas as subconsultas, funcionando como o operador AND. |
|
mustNotQueries |
Lista de consultas. A linha não deve corresponder a nenhuma das subconsultas, equivalendo ao operador NOT. |
|
filterQueries |
Lista de consultas. A linha precisa atender a todas as subconsultas no filtro. Embora semelhante a uma consulta comum, o filtro não calcula pontuação de relevância com base na quantidade de correspondências. |
|
shouldQueries |
Lista de consultas opcionais às quais a linha pode corresponder, atuando como o operador OR. Para ser considerada válida, a linha deve atender ao número mínimo definido de subconsultas shouldQueries. Quanto mais subconsultas shouldQueries forem correspondidas, maior será a pontuação de relevância da linha. |
|
minimumShouldMatch |
Número mínimo de correspondências em shouldQueries. O valor padrão é 1 quando apenas shouldQueries existe no mesmo nível. Caso existam outras consultas no mesmo nível, como mustQueries, mustNotQueries ou filterQueries, o valor padrão passa a ser 0. |
Exemplo
O exemplo abaixo demonstra como construir um BoolQuery para executar uma consulta booleana.
var client = require('../client');
var TableStore = require('../../index.js');
var Long = TableStore.Long;
/**
* Use a boolean query to implement (col2 < 4 OR col3 < 5) OR (col2 = 4 AND (col3 = 5 OR col3 = 6)). The logic is as follows:
* boolQuery1 = rangeQuery(col2 < 4) OR rangeQuery(col3 < 5)
* boolQuery2 = termQuery(col3 = 5) OR termQuery(col3 = 6)
* boolQuery3 = termQuery(col2 = 4) AND boolQuery2
* boolQuery4 = boolQuery1 OR boolQuery3
*/
client.search({
tableName: "sampleTable",
indexName: "sampleSearchIndex",
searchQuery: {
offset: 0, // The query offset.
limit: 10, // To get only the row count without retrieving data, set limit to 0. This returns no rows.
getTotalCount: false, // TotalCount in the result indicates the total number of rows in the table. The default value is false, which means it is not returned.
query: { // Construct boolQuery4. Set the query condition to match at least one of boolQuery1 and boolQuery3.
queryType: TableStore.QueryType.BOOL_QUERY,
query: {
shouldQueries: [ // You can use mustQueries, shouldQueries, or mustNotQueries.
{ // Construct boolQuery1. Set the query condition to match at least one of "Query Condition 1" and "Query Condition 2".
queryType: TableStore.QueryType.BOOL_QUERY,
query: {
// shouldQueries: The query condition is that the value of col2 is less than 4 or the value of col3 is less than 5.
shouldQueries:[
{
// Query Condition 1: rangeQuery, the value of col2 is less than 4.
queryType: TableStore.QueryType.RANGE_QUERY,
query:{
fieldName: "col2",
rangeTo: 4
}
},
{
// Query Condition 2: rangeQuery, the value of col3 is less than 5.
queryType: TableStore.QueryType.RANGE_QUERY,
query:{
fieldName: "col3",
rangeTo: 5
}
}
],
minimumShouldMatch:1
}
},
{ // Construct boolQuery3. Set the query condition to match both "Query Condition 3" and boolQuery2.
queryType: TableStore.QueryType.BOOL_QUERY,
query: {
mustQueries: [
// mustQueries: The query condition is that the value of col2 is 4, and the value of col3 is 5 or 6.
{
// Query Condition 3: termQuery, the value of col2 is 4.
queryType:TableStore.QueryType.TERM_QUERY,
query: {
fieldName : "col2",
term: 4
}
},
{ // Construct boolQuery2: Set the query condition to match at least one of "Query Condition 4" and "Query Condition 5".
queryType: TableStore.QueryType.BOOL_QUERY,
query: {
// shouldQueries: The query condition is that the value of col3 is 5 or 6.
shouldQueries:[
{
// Query Condition 4: termQuery, the value of col3 is 5.
queryType: TableStore.QueryType.TERM_QUERY,
query:{
fieldName:"col3",
term: 5
}
},
{
// Query Condition 5: termQuery, the value of col3 is 6.
queryType: TableStore.QueryType.TERM_QUERY,
query:{
fieldName:"col3",
term: 6
}
}
],
minimumShouldMatch:1
}
}
]
}
}
],
minimumShouldMatch: 1 // This is valid only for shouldQueries. It specifies the minimum number of conditions to match.
}
},
},
columnToGet: { // Specifies the columns to return. Valid values: RETURN_SPECIFIED (returns custom columns), RETURN_ALL (returns all columns), RETURN_ALL_FROM_INDEX (returns all columns from the search index), and RETURN_NONE (returns no columns).
returnType: TableStore.ColumnReturnType.RETURN_SPECIFIED,
returnNames: ["col2", "col3", "col4"]
}
}, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
console.log('success:', JSON.stringify(data, null, 2));
});
Perguntas frequentes
Referências
-
Os índices de busca suportam os seguintes tipos de consulta: term query, terms query, match all query, match query, match phrase query, prefix query, range query, wildcard query, Boolean query, geo query, nested query, vector query e exists query. Selecione o tipo adequado conforme as necessidades do seu negócio.
Para ordenar ou paginar as linhas que atendem aos critérios de busca, utilize o recurso de ordenação e paginação. Para mais informações, consulte Sorting and paging.
Caso precise agrupar o conjunto de resultados com base em uma coluna específica, use o recurso de colapso (distinto). Isso garante que dados do tipo especificado apareçam apenas uma vez nos resultados. Para mais informações, consulte Collapse (distinct).
Para analisar dados em uma tabela, como obter valores extremos, somas ou contagem total de linhas, execute operações de agregação ou instruções SQL. Para mais informações, consulte Aggregation e SQL query.
Se o objetivo for obter rapidamente todas as linhas correspondentes sem necessidade de ordenação, chame as operações ParallelScan e ComputeSplits para usar a varredura paralela. Para mais informações, consulte Parallel scan.