Operaciones de API
Puede ejecutar una consulta booleana mediante la operación de API Search o ParallelScan. El tipo de consulta es BoolQuery.
Parámetros
|
Parámetro
|
Descripción
|
|
mustQueries
|
Lista de consultas. Una fila de datos debe coincidir con todas las subconsultas para considerarse una coincidencia. Esto equivale al operador AND.
|
|
mustNotQueries
|
Lista de consultas. Una fila de datos no debe coincidir con ninguna de las subconsultas para considerarse una coincidencia. Esto equivale al operador NOT.
|
|
filterQueries
|
Lista de consultas. Una fila de datos debe coincidir con todos los subfiltros para considerarse una coincidencia. Un filtro es similar a una consulta, pero no calcula una puntuación de relevancia basada en el número de consultas de filtro que coinciden.
|
|
shouldQueries
|
Lista de consultas. Estas consultas pueden coincidir o no. Esto equivale al operador OR.
Una fila de datos debe coincidir como mínimo con el número mínimo de subconsultas shouldQueries para considerarse una coincidencia.
Entre más subconsultas shouldQueries coincidan, mayor será la puntuación de relevancia general.
|
|
minimumShouldMatch
|
Número mínimo de subconsultas shouldQueries que deben coincidir. El valor predeterminado es 1 si solo existe shouldQueries en el mismo nivel. El valor predeterminado es 0 si existen otras consultas en el mismo nivel, como mustQueries, mustNotQueries y filterQueries.
|
|
getTotalCount
|
Especifica si se devuelve el número total de filas que coinciden. El valor predeterminado es false.
Devolver el número total de filas que coinciden puede afectar el rendimiento de la consulta.
|
|
tableName
|
Nombre de la tabla de datos.
|
|
indexName
|
Nombre del índice de búsqueda.
|
|
columnsToGet
|
Especifica si se devuelven todas las columnas. Incluye las configuraciones returnAll y columns.
El valor predeterminado de returnAll es false, lo que significa que no se devuelven todas las columnas. En este caso, puede usar columns para especificar las columnas que desea devolver. Si no especifica las columnas, solo se devuelven las columnas de clave primaria.
Si establece returnAll en true, se devuelven todas las columnas.
|
Uso
Puede ejecutar una consulta booleana desde la consola, la interfaz de línea de comandos o un SDK. Antes de empezar, complete los siguientes pasos.
Usar la consola
-
Vaya a la pestaña Index Management.
Inicie sesión en la consola de Table Store.
En la barra de navegación superior, seleccione un resource group y una región.
En la página Overview, haga clic en el nombre de la instancia o haga clic en Instance Management en la columna Actions.
En la pestaña Instance Details y dentro de la pestaña Data Table List, haga clic en el nombre de la tabla de datos o haga clic en Index Management en la columna Actions.
En la pestaña Index Management, busque el Search Index de destino y haga clic en Search en la columna Actions.
-
Consulte los datos en el cuadro de diálogo Query Data.
-
De forma predeterminada, se devuelven todas las columnas. Para devolver columnas específicas, desactive Retrieve All Columns e introduzca los nombres de las columnas separados por comas.
Nota
De forma predeterminada, Table Store devuelve las columnas de clave primaria de la tabla de datos.
-
Seleccione un operador lógico: And, Or o Not.
Si selecciona And, la consulta devuelve los datos que cumplen con todas las condiciones especificadas. Si selecciona Or, la consulta devuelve los datos que cumplen con al menos una de las condiciones especificadas. Si selecciona Not, la consulta devuelve los datos que no cumplen con las condiciones especificadas.
-
Seleccione un campo de índice, haga clic en Add y, a continuación, establezca el tipo de consulta para el campo de índice e introduzca un valor.
Si es necesario, repita este paso para agregar configuraciones de consulta para varios campos de índice.
De forma predeterminada, la ordenación está deshabilitada. Para ordenar los resultados por un campo específico, active Enable Sorting, agregue el campo de ordenación y configure el criterio de ordenación.
De forma predeterminada, la agregación está deshabilitada. Para realizar una agregación estadística sobre un campo específico, active Enable Aggregation, agregue el campo para la agregación y configure los parámetros de agregación.
-
Haga clic en OK.
Los resultados de la consulta se muestran en la pestaña Index Management.
Usar la interfaz de línea de comandos
Ejecute el comando search en la interfaz de línea de comandos para consultar datos de un índice de búsqueda. Para obtener más información, consulte Search index.
-
Ejecute el comando search para consultar datos de la tabla mediante el índice de búsqueda search_index. Este comando devuelve todas las columnas indexadas.
search -n search_index --return_all_indexed
-
Introduzca las condiciones de consulta cuando el sistema lo solicite. A continuación se muestra un ejemplo:
{
"Offset": -1,
"Limit": 10,
"Collapse": null,
"Sort": null,
"GetTotalCount": true,
"Token": null,
"Query": {
"Name": "BoolQuery",
"Query": {
"MinimumShouldMatch": null,
"MustQueries": null,
"MustNotQueries": null,
"FilterQueries": null,
"ShouldQueries": [{
"Name": "RangeQuery",
"Query": {
"FieldName": "gid",
"From": null,
"To": 10,
"IncludeLower": false,
"IncludeUpper": false
}
}, {
"Name": "TermQuery",
"Query": {
"FieldName": "gid",
"Term": 77
}
}]
}
},
"Aggregations": [{
"Name": "avg",
"Aggregation": {
"AggName": "agg1",
"Field": "gid",
"MissingValue": null
}
}]
}
Usar un SDK
Puede ejecutar una consulta booleana mediante Java SDK, Go SDK, Python SDK, Node.js SDK, .NET SDK o PHP SDK. Este tema utiliza el SDK de Java como ejemplo.
A continuación se muestran ejemplos de cómo ejecutar consultas booleanas.
Consultar filas que cumplen con todas las condiciones de subconsulta
Cuando consulta filas que cumplen con todas las condiciones de subconsulta, puede decidir si se calculan las puntuaciones de relevancia de las filas según sus requisitos de negocio.
Calcular las puntuaciones de relevancia de las filas
El siguiente código de ejemplo muestra cómo ejecutar una consulta booleana para buscar las filas que cumplen con todas las condiciones de subconsulta y calcular sus puntuaciones de relevancia.
/**
* Perform a Boolean query to query the rows that meet all subquery conditions.
* @param client
*/
public static void andQuery(SyncClient client){
/**
* Condition 1: Perform a range query to query the rows in which the value of the Col_Long column is greater than 3.
*/
RangeQuery rangeQuery = new RangeQuery();
rangeQuery.setFieldName("Col_Long");
rangeQuery.greaterThan(ColumnValue.fromLong(3));
/**
* Condition 2: Perform a match query to query the rows in which the value of the Col_Keyword column is hangzhou.
*/
MatchQuery matchQuery = new MatchQuery();
matchQuery.setFieldName("Col_Keyword");
matchQuery.setText("hangzhou");
SearchQuery searchQuery = new SearchQuery();
{
/**
* Construct a Boolean query whose query results meet both Condition 1 and Condition 2.
*/
BoolQuery boolQuery = new BoolQuery();
boolQuery.setMustQueries(Arrays.asList(rangeQuery, matchQuery));
searchQuery.setQuery(boolQuery);
//searchQuery.setGetTotalCount(true);// Set the GetTotalCount parameter to true to return the total number of rows that meet the query conditions.
SearchRequest searchRequest = new SearchRequest("<TABLE_NAME>", "<SEARCH_INDEX_NAME>", searchQuery);
// You can configure the columnsToGet parameter to specify the columns to return or specify that all columns are returned. If you do not configure this parameter, only the primary key columns are returned.
//SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
//columnsToGet.setReturnAll(true); // Set the ReturnAll parameter to true to return all columns.
//columnsToGet.setColumns(Arrays.asList("ColName1","ColName2")); // Specify the columns that you want to return.
//searchRequest.setColumnsToGet(columnsToGet);
SearchResponse resp = client.search(searchRequest);
//System.out.println("TotalCount: " + resp.getTotalCount()); // Specify that the total number of rows that meet the query conditions instead of the number of returned rows is displayed.
System.out.println("Row: " + resp.getRows());
}
}
No calcular las puntuaciones de relevancia de las filas
El siguiente código de ejemplo muestra cómo ejecutar una consulta booleana para buscar las filas que cumplen con todas las condiciones de subconsulta sin calcular sus puntuaciones de relevancia.
/**
* Perform a Boolean query to query the rows that meet all subquery conditions without calculating the relevance scores for the rows.
* @param client
*/
public static void filtersQuery(SyncClient client){
/**
* Condition 1: Perform a range query to query the rows in which the value of the Col_Long column is greater than 3.
*/
RangeQuery rangeQuery = new RangeQuery();
rangeQuery.setFieldName("Col_Long");
rangeQuery.greaterThan(ColumnValue.fromLong(3));
/**
* Condition 2: Perform a match query to query the rows in which the value of the Col_Keyword column is hangzhou.
*/
MatchQuery matchQuery = new MatchQuery();
matchQuery.setFieldName("Col_Keyword");
matchQuery.setText("hangzhou");
SearchQuery searchQuery = new SearchQuery();
{
/**
* Construct a Boolean query whose query results meet both Condition 1 and Condition 2.
*/
BoolQuery boolQuery = new BoolQuery();
boolQuery.setFilterQueries(Arrays.asList(rangeQuery, matchQuery));
searchQuery.setQuery(boolQuery);
//searchQuery.setGetTotalCount(true);// Set the GetTotalCount parameter to true to return the total number of rows that meet the query conditions.
SearchRequest searchRequest = new SearchRequest("sampleTable", "sampleSearchIndex", searchQuery);
// You can configure the columnsToGet parameter to specify the columns to return or specify that all columns are returned. If you do not configure this parameter, only the primary key columns are returned.
//SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
//columnsToGet.setReturnAll(true); // Set the ReturnAll parameter to true to return all columns.
//columnsToGet.setColumns(Arrays.asList("ColName1","ColName2")); // Specify the columns that you want to return.
//searchRequest.setColumnsToGet(columnsToGet);
SearchResponse resp = client.search(searchRequest);
//System.out.println("TotalCount: " + resp.getTotalCount()); // Specify that the total number of rows that meet the query conditions instead of the number of returned rows is displayed.
System.out.println("Row: " + resp.getRows());
}
}
Consultar filas que cumplen con al menos una de las condiciones de subconsulta
El siguiente código de ejemplo muestra cómo ejecutar una consulta booleana para buscar las filas que cumplen con al menos una de las condiciones de subconsulta especificadas:
/**
* Perform a Boolean query to query the rows that meet at least one of the specified subquery conditions.
* @param client
*/
public static void orQuery(SyncClient client) {
/**
* Condition 1: Perform a range query to query the rows in which the value of the Col_Long column is greater than 3.
*/
RangeQuery rangeQuery = new RangeQuery();
rangeQuery.setFieldName("Col_Long");
rangeQuery.greaterThan(ColumnValue.fromLong(3));
/**
* Condition 2: Perform a match query to query the rows in which the value of the Col_Keyword column is hangzhou.
*/
MatchQuery matchQuery = new MatchQuery();
matchQuery.setFieldName("Col_Keyword");
matchQuery.setText("hangzhou");
SearchQuery searchQuery = new SearchQuery();
{
/**
* Construct a Boolean query whose query results meet at least one of Condition 1 and Condition 2.
*/
BoolQuery boolQuery = new BoolQuery();
boolQuery.setShouldQueries(Arrays.asList(rangeQuery, matchQuery));
boolQuery.setMinimumShouldMatch(1); // Specify that the results meet at least one of the subquery conditions.
searchQuery.setQuery(boolQuery);
//searchQuery.setGetTotalCount(true);// Set the GetTotalCount parameter to true to return the total number of rows that meet the query conditions.
SearchRequest searchRequest = new SearchRequest("<TABLE_NAME>", "<SEARCH_INDEX_NAME>", searchQuery);
// You can configure the columnsToGet parameter to specify the columns to return or specify that all columns are returned. If you do not configure this parameter, only the primary key columns are returned.
//SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
//columnsToGet.setReturnAll(true); // Set the ReturnAll parameter to true to return all columns.
//columnsToGet.setColumns(Arrays.asList("ColName1","ColName2")); // Specify the columns that you want to return.
//searchRequest.setColumnsToGet(columnsToGet);
SearchResponse resp = client.search(searchRequest);
//System.out.println("TotalCount: " + resp.getTotalCount()); // Specify that the total number of rows that meet the query conditions instead of the number of returned rows is displayed.
System.out.println("Row: " + resp.getRows());
}
}
Consultar filas que no cumplen con ninguna condición de subconsulta
El siguiente código de ejemplo muestra cómo ejecutar una consulta booleana para buscar las filas que no cumplen con ninguna condición de subconsulta:
/**
* Perform a Boolean query to query the rows that do not meet any subquery conditions.
* @param client
*/
public static void notQuery(SyncClient client) {
/**
* Condition 1: Perform a match query to query the rows in which the value of the Col_Keyword column is hangzhou.
*/
MatchQuery matchQuery = new MatchQuery();
matchQuery.setFieldName("Col_Keyword");
matchQuery.setText("hangzhou");
SearchQuery searchQuery = new SearchQuery();
{
/**
* Construct a Boolean query whose query results do not meet Condition 1.
*/
BoolQuery boolQuery = new BoolQuery();
boolQuery.setMustNotQueries(Arrays.asList(matchQuery));
searchQuery.setQuery(boolQuery);
//searchQuery.setGetTotalCount(true);// Set the GetTotalCount parameter to true to return the total number of rows that meet the query conditions.
SearchRequest searchRequest = new SearchRequest("<TABLE_NAME>", "<SEARCH_INDEX_NAME>", searchQuery);
// You can configure the columnsToGet parameter to specify the columns to return or specify that all columns are returned. If you do not configure this parameter, only the primary key columns are returned.
//SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
//columnsToGet.setReturnAll(true); // Set the ReturnAll parameter to true to return all columns.
//columnsToGet.setColumns(Arrays.asList("ColName1","ColName2")); // Specify the columns that you want to return.
//searchRequest.setColumnsToGet(columnsToGet);
SearchResponse resp = client.search(searchRequest);
//System.out.println("TotalCount: " + resp.getTotalCount()); // Specify that the total number of rows that meet the query conditions instead of the number of returned rows is displayed.
System.out.println("Row: " + resp.getRows());
}
}
Consultar filas que cumplen con una combinación de condiciones de subconsulta
El siguiente código de ejemplo muestra cómo ejecutar una consulta booleana para buscar las filas que cumplen con una combinación de condiciones de subconsulta: (col2<4 o col3<5) o (col2 = 4 y (col3 = 5 o col3 = 6)). En esta combinación, las subconsultas booleanas se conectan mediante el operador AND u OR.
/**
* (col2<4 or col3<5) or (col2 = 4 and (col3 = 5 or col3 =6))
* The Boolean subqueries are connected by the AND or OR operator.
* @param client
*/
private static void boolQuery2(SyncClient client){
// Condition 1: The value of the col2 column is less than 4.
RangeQuery rangeQuery1 = new RangeQuery();
rangeQuery1.setFieldName("col2");
rangeQuery1.lessThan(ColumnValue.fromLong(4));
// Condition 2: The value of the col3 column is less than 5.
RangeQuery rangeQuery2 = new RangeQuery();
rangeQuery2.setFieldName("col3");
rangeQuery2.lessThan(ColumnValue.fromLong(5));
// Condition 3: The value of the col2 column is equal to 4.
TermQuery termQuery = new TermQuery();
termQuery.setFieldName("col2");
termQuery.setTerm(ColumnValue.fromLong(4));
// Condition 4: The value of the col3 column is equal to 5 or the value of the col3 column is equal to 6.
TermsQuery termsQuery = new TermsQuery();
termsQuery.setFieldName("col3");
termsQuery.addTerm(ColumnValue.fromLong(5));
termsQuery.addTerm(ColumnValue.fromLong(6));
SearchQuery searchQuery = new SearchQuery();
List<Query> queryList1 = new ArrayList<>();
queryList1.add(rangeQuery1);
queryList1.add(rangeQuery2);
// Composite condition 1: The value of the col2 column is less than 4 or the value of the col3 column is less than 5.
BoolQuery boolQuery1 = new BoolQuery();
boolQuery1.setShouldQueries(queryList1);
// Composite condition 2: The value of the col2 column is equal to 4 and the value of the col3 column is equal to 5 or 6.
List<Query> queryList2 = new ArrayList<>();
queryList2.add(termQuery);
queryList2.add(termsQuery);
BoolQuery boolQuery2 = new BoolQuery();
boolQuery2.setMustQueries(queryList2);
// Composite conditions: The value of the col2 column is less than 4 or the value of the col3 column is less than 5, or the value of the col2 column is equal to 4 and the value of the col3 column is equal to 5 or 6.
List<Query> queryList3 = new ArrayList<>();
queryList3.add(boolQuery1);
queryList3.add(boolQuery2);
BoolQuery boolQuery = new BoolQuery();
boolQuery.setShouldQueries(queryList3);
searchQuery.setQuery(boolQuery);
//searchQuery.setGetTotalCount(true);// Set the GetTotalCount parameter to true to return the total number of rows that meet the query conditions.
SearchRequest searchRequest = new SearchRequest("<TABLE_NAME>", "<SEARCH_INDEX_NAME>", searchQuery);
// You can configure the columnsToGet parameter to specify the columns to return or specify that all columns are returned. If you do not configure this parameter, only the primary key columns are returned.
//SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
//columnsToGet.setReturnAll(true); // Set the ReturnAll parameter to true to return all columns.
//columnsToGet.setColumns(Arrays.asList("ColName1","ColName2")); // Specify the columns that you want to return.
//searchRequest.setColumnsToGet(columnsToGet);
SearchResponse response = client.search(searchRequest);
//System.out.println("TotalCount: " + resp.getTotalCount()); // Specify that the total number of rows that meet the query conditions instead of the number of returned rows is displayed.
System.out.println(response.getRows());
}
Referencias
Search Index admite diversos tipos de consulta para búsquedas de datos multidimensionales, entre ellos: term query, terms query, match all query, match query, phrase match query, range query, prefix query, suffix query, wildcard query, token-based wildcard query, boolean query, geo query, nested query, vector search, y exists query.
Al consultar datos, puede sort and paginate el conjunto de resultados o ejecutar collapsing (deduplication).
Para el análisis de datos, como buscar el valor máximo o mínimo, calcular una suma o contar filas, utilice las funciones statistical aggregation o SQL query.
Si necesita exportar datos rápidamente sin importar el orden del conjunto de resultados, utilice la función Parallel Scan.