Una consulta booleana (BoolQuery) contiene una o más subconsultas. Estas subconsultas se utilizan para comprobar si una fila cumple las condiciones de la consulta. Cada subconsulta puede ser de cualquier tipo, incluida otra consulta booleana.
Requisitos previos
Se inicializó una instancia de OTSClient. Para obtener más información, consulte Initialize an OTSClient instance.
Se creó una tabla de datos y se escribieron datos en ella. Para obtener más información, consulte Create data tables y Write data.
Se creó un índice de búsqueda para la tabla de datos. Para obtener más información, consulte Create a search index.
Parámetros
|
Parámetro |
Descripción |
|
tableName |
El nombre de la tabla de datos. |
|
indexName |
El nombre del índice de búsqueda. |
|
mustQueries |
Lista de consultas. Una fila debe coincidir con todas las subconsultas. Esto equivale al operador AND. |
|
mustNotQueries |
Lista de consultas. Una fila no debe coincidir con ninguna de las subconsultas. Esto equivale al operador NOT. |
|
filterQueries |
Lista de consultas. Una fila debe coincidir con todas las subconsultas del filtro. Un filtro es similar a una consulta, pero no calcula una puntuación de relevancia basada en la cantidad de filtros que coinciden. |
|
shouldQueries |
Lista de consultas. Una fila puede coincidir con estas subconsultas. Esto equivale al operador OR. Para considerarse una coincidencia, una fila debe cumplir como mínimo con el número mínimo de subconsultas de shouldQueries. Entre más subconsultas de shouldQueries coincidan con una fila, mayor será su puntuación de relevancia. |
|
minimumShouldMatch |
Número mínimo de shouldQueries que deben coincidir. El valor predeterminado es 1 si solo existe shouldQueries en el mismo nivel. Si existen otras consultas en el mismo nivel, como mustQueries, mustNotQueries y filterQueries, el valor predeterminado es 0. |
Ejemplo
A continuación se muestra cómo construir un BoolQuery para ejecutar una 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));
});
Preguntas frecuentes
Referencias
-
Los índices de búsqueda son compatibles con los siguientes 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 y exists query. Seleccione el tipo de consulta adecuado según sus necesidades de negocio.
Si necesita ordenar o paginar las filas que cumplen las condiciones de la consulta, utilice la función de ordenamiento y paginación. Para obtener más información, consulte Sorting and paging.
Si desea agrupar el conjunto de resultados con base en una columna específica, utilice la función de contracción (distinct). De esta manera, los datos del tipo especificado aparecerán una sola vez en los resultados de la consulta. Para obtener más información, consulte Collapse (distinct).
Si necesita analizar los datos de una tabla de datos, por ejemplo, para obtener los valores extremos, la suma y el número total de filas, ejecute operaciones de agregación o sentencias SQL. Para obtener más información, consulte Aggregation y SQL query.
Si desea obtener rápidamente todas las filas que cumplen las condiciones de la consulta sin necesidad de ordenarlas, llame a las operaciones ParallelScan y ComputeSplits para usar la función de escaneo paralelo. Para obtener más información, consulte Parallel scan.