Todos os produtos
Search
Central de documentação

Tablestore:Nested query

Última atualização: Jul 03, 2026

Use NestedQuery para consultar dados em sublinhas de um campo aninhado. Não é possível consultar tipos aninhados diretamente. Envolva a consulta em um NestedQuery, especifique o caminho do campo aninhado e uma subconsulta. A subconsulta pode ser de qualquer tipo.

Pré-requisitos

Parâmetros

Parâmetro

Descrição

tableName

Nome da tabela de dados.

indexName

Nome do índice de busca.

path

Caminho do campo aninhado. Por exemplo, news.title refere-se ao subcampo title dentro do campo aninhado news.

query

Consulta a executar nos subcampos do campo aninhado. Aceita qualquer tipo de consulta.

scoreMode

Modo de pontuação usado quando um campo contém vários valores.

InnerHits

Configuração dos subcampos do campo aninhado. Inclui as seguintes opções:

  • sort: ordem de classificação para retorno das sublinhas aninhadas.

  • offset: posição inicial quando o campo aninhado contém várias sublinhas.

  • limit: número máximo de sublinhas a retornar quando o campo aninhado contém várias sublinhas. Padrão: 3.

  • highlight: configurações de destaque para subcampos aninhados. Para obter detalhes, consulte Resumo e destaque.

Exemplos

Exemplo de consulta aninhada de nível único

Consulte linhas em que Col_Nested.Sub_Col_Keyword seja igual a "happy". Col_Nested é um campo aninhado cujas sublinhas contêm o 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));
});

Exemplo de uso de resumo e destaque em consulta aninhada

Use NestedQuery para localizar linhas em que o subcampo Sub_Col_Text do campo aninhado Col_Nested corresponda a tablestore e destaque os termos correspondentes nos 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 + "    ");
        }
    });
}

FAQ

Referências