This topic describes how to query nested fields. You can use a nested query to query the data of nested fields.

You must use the NestedQuery operation to wrap the nested field before its query data can be used. In NestedQuery, you must specify a subquery of any type and the path of the nested field.

You can only query fields of the nested type.

Common fields and nested fields can be queried simultaneously within a request.

Parameters

  • path: the tree path of the nested fields content. For example, news.title indicates the title nested within the news field.
  • query: the query to perform on the child field of the nested field. It can be of any type.

Examples

/**
 * The NESTED column contains nested_1 and nested_2. You need to search the col_nested.nested_1 column for data that matches "tablestore".
 * @param client
 */
private static void nestedQuery(SyncClient client) {
    SearchQuery searchQuery = new SearchQuery();
    NestedQuery nestedQuery = new NestedQuery(); // Set the query type to NestedQuery.
    nestedQuery.setPath("col_nested"); // Set the path of the NESTED field.
    TermQuery termQuery = new TermQuery(); // Specify a subquery for NestedQuery.
    termQuery.setFieldName("col_nested.nested_1"); // Set the name of the field that you want to match. The field name must contain the prefix of the Nested column.
    termQuery.setTerm(ColumnValue.fromString("tablestore")); // Set the value that you want to match.
    nestedQuery.setQuery(termQuery);
    nestedQuery.setScoreMode(ScoreMode.None);
    searchQuery.setQuery(nestedQuery);
    searchQuery.setGetTotalCount(true);
    SearchRequest searchRequest = new SearchRequest(TABLE_NAME, INDEX_NAME, searchQuery);

    SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
    columnsToGet.setReturnAll(true); // Set ReturnAll to true to return all columns.
    searchRequest.setColumnsToGet(columnsToGet);

    SearchResponse resp = client.search(searchRequest);
    System.out.println("TotalCount: " + resp.getTotalCount()); // Display the total number of matched rows instead of the number of returned rows.
    System.out.println("Row: " + resp.getRows());
}