Utilice NestedQuery para consultar datos en subfilas de un campo anidado. Los tipos anidados no se pueden consultar directamente; debe encapsular la consulta en un NestedQuery y especificar la ruta del campo anidado junto con una subconsulta. La subconsulta puede ser de cualquier tipo.
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. |
|
path |
La ruta del campo anidado. Por ejemplo, |
|
query |
La consulta que se ejecutará contra los subcampos del campo anidado. Se admite cualquier tipo de consulta. |
|
scoreMode |
El modo de puntuación que se utiliza cuando un campo contiene varios valores. |
|
InnerHits |
Configuración para los subcampos del campo anidado. Incluye las siguientes opciones:
|
Ejemplos
Ejemplo de consulta anidada de un solo nivel
Consulte las filas donde Col_Nested.Sub_Col_Keyword es igual a "happy". Col_Nested es un campo anidado cuyas subfilas contienen el subcampo Sub_Col_Keyword.
/**
* Sample nested data for Col_Nested: '[{Sub_Col_Keyword: "happy"},{Sub_Col_Keyword: "sunny"}]'
*/
client.search({
tableName: "<TABLE_NAME>",
indexName: "<SEARCH_INDEX_NAME>",
searchQuery: {
offset: 0,
limit: 10, // To get only the row count without retrieving specific data, set limit to 0. This prevents any rows from being returned.
query: { // Set the query type to TableStore.QueryType.NESTED_QUERY.
queryType: TableStore.QueryType.NESTED_QUERY,
query: {
path: "Col_Nested",
query: {
queryType: TableStore.QueryType.TERM_QUERY,
query: {
fieldName: "Col_Nested.Sub_Col_Keyword",
term: "happy"
}
},
}
},
getTotalCount: true // TotalCount in the result indicates the total number of rows in the table. The default value is false, which means the total count is not returned.
},
columnToGet: { // The columns to return. You can set this to RETURN_SPECIFIED (return custom columns), RETURN_ALL (return all columns), RETURN_ALL_FROM_INDEX (return all columns from the search index), or RETURN_NONE (return no columns).
returnType: TableStore.ColumnReturnType.RETURN_ALL
}
}, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
console.log('success:', JSON.stringify(data, null, 2));
});
Ejemplo de uso de resumen y resaltado en una consulta anidada
Utilice NestedQuery para buscar filas donde el subcampo Sub_Col_Text del campo anidado Col_Nested coincida con tablestore, y resalte los términos coincidentes en los resultados.
client.search({
tableName: "<TABLE_NAME>",
indexName: "<SEARCH_INDEX_NAME>",
searchQuery: {
offset: 0,
limit: 10, // To get only the row count without retrieving specific data, set limit to 0. This prevents any rows from being returned.
query: { // Set the query type to TableStore.QueryType.NESTED_QUERY.
queryType: TableStore.QueryType.NESTED_QUERY,
query: {
path: "Col_Nested",
query: {
queryType: TableStore.QueryType.MATCH_QUERY,
query: {
fieldName: "Col_Nested.Sub_Col_Text",
text: "tablestore"
}
},
innerHits: {
sort: {
sorters: [
{
scoreSort: {
order: TableStore.SortOrder.SORT_ORDER_DESC
}
},
{
docSort: {
order: TableStore.SortOrder.SORT_ORDER_ASC
}
},
],
},
highlight: {
highlightParameters: [
{
fieldName:"Col_Nested.Sub_Col_Text",
preTag: "",
postTag: "",
fragmentsOrder: TableStore.HighlightFragmentOrder.TEXT_SEQUENCE,
fragmentSize: 20,
numberOfFragments: 3,
}
]
}
},
}
},
getTotalCount: true // TotalCount in the result indicates the total number of rows in the table. The default value is false, which means the total count is not returned.
},
columnToGet: { // The columns to return. You can set this to RETURN_SPECIFIED (return custom columns), RETURN_ALL (return all columns), RETURN_ALL_FROM_INDEX (return all columns from the search index), or RETURN_NONE (return no columns).
returnType: TableStore.ColumnReturnType.RETURN_ALL
}
}, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
console.log('success:', JSON.stringify(data.rows, null, 2));
printSearchHit(data.searchHits, "");
});
/**
* Prints the content of searchHit.
* @param searchHits The searchHits.
* @param prefix The prefix to add for nested structures to print hierarchical information.
*/
function printSearchHit(searchHits, prefix) {
TableStore.util.arrayEach(searchHits, function (searchHit) {
if (searchHit.highlightResultItem != null) {
console.log(prefix + "Highlight: \n");
var strBuilder = ""
for (const [key,val] of searchHit.highlightResultItem.highlightFields.entries()) {
strBuilder += key + ":[";
strBuilder += val.fragments.join(",") + "]\n";
console.log(strBuilder);
}
}
for (const [key,val] of searchHit.searchInnerHits.entries()) {
console.log(prefix + "Path: " + key + "\n");
console.log(prefix + "InnerHit: \n");
printSearchHit(val.subSearchHits, prefix + " ");
}
});
}
Preguntas frecuentes
Referencias
-
Los índices de búsqueda admiten 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 un tipo de consulta para consultar datos según sus requisitos empresariales.
Si desea ordenar o paginar las filas que cumplen con 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 colapsar el conjunto de resultados basándose en una columna específica, utilice la función de colapso (distinto). De esta manera, los datos del tipo especificado aparecen solo una vez en los resultados de la consulta. Para obtener más información, consulte Collapse (distinct).
Si desea analizar datos en una tabla de datos, como obtener los valores extremos, la suma y el número total de filas, realice operaciones de agregación o ejecute sentencias SQL. Para obtener más información, consulte Aggregation y SQL query.
Si desea obtener rápidamente todas las filas que cumplen con las condiciones de la consulta sin necesidad de ordenarlas, llame a las operaciones ParallelScan y ComputeSplits para utilizar la función de escaneo paralelo. Para obtener más información, consulte Parallel scan.