Todos os produtos
Search
Central de documentação

Tablestore:Boolean query

Última atualização: Oct 09, 2026

Uma consulta booleana (BoolQuery) contém uma ou mais subconsultas e as usa para determinar se uma linha de dados atende às condições de consulta especificadas. Cada subconsulta pode ser de qualquer tipo, incluindo outra BoolQuery.

Operações de API

Execute uma consulta booleana usando a operação de API Search ou ParallelScan. O tipo de consulta é BoolQuery.

Parâmetros

Parâmetro

Descrição

mustQueries

Uma lista de consultas. Uma linha de dados deve atender a todas as subconsultas para ser considerada correspondente. Isso equivale ao operador AND.

mustNotQueries

Uma lista de consultas. Uma linha de dados não deve atender a nenhuma das subconsultas para ser considerada correspondente. Isso equivale ao operador NOT.

filterQueries

Uma lista de consultas. Uma linha de dados deve atender a todos os subfiltros para ser considerada correspondente. Um filtro é semelhante a uma consulta, mas não calcula pontuação de relevância com base na quantidade de consultas de filtro correspondentes.

shouldQueries

Uma lista de consultas. A correspondência dessas consultas é opcional. Isso equivale ao operador OR.

Uma linha de dados deve atender ao número mínimo de subconsultas shouldQueries para ser considerada correspondente.

Quanto maior o número de subconsultas shouldQueries correspondidas, maior a pontuação geral de relevância.

minimumShouldMatch

A quantidade mínima de subconsultas shouldQueries que devem ser correspondidas. O valor padrão é 1 quando apenas shouldQueries existe no mesmo nível, e 0 quando outras consultas, como mustQueries, mustNotQueries e filterQueries, também estão presentes.

getTotalCount

Especifica se a quantidade total de linhas correspondentes será retornada. O valor padrão é false.

Retornar a quantidade total de linhas correspondentes pode afetar o desempenho da consulta.

tableName

O nome da tabela de dados.

indexName

O nome do índice de pesquisa.

columnsToGet

Especifica se todas as colunas serão retornadas. Inclui as configurações returnAll e columns.

O valor padrão de returnAll é false, o que impede o retorno de todas as colunas. Nesse caso, use columns para especificar as colunas a serem retornadas. Se nenhuma coluna for especificada, apenas as colunas de chave primária serão retornadas.

Se returnAll for definido como true, todas as colunas serão retornadas.

Uso

Execute uma consulta booleana pelo console, pela interface de linha de comando ou por um SDK. Antes de começar, conclua as etapas a seguir.

Usar o console

  1. Acesse a aba Index Management.

    1. Faça login no Table Store console.

    2. Na barra de navegação superior, selecione um grupo de recursos e uma região.

    3. Na página Overview, clique no nome da instância ou clique em Instance Management na coluna Actions.

    4. Na aba Instance Details, dentro da aba Data Table List, clique no nome da tabela de dados ou clique em Index Management na coluna Actions.

  2. Na aba Index Management, localize o Search Index de destino e clique em Search na coluna Actions.

  3. Consulte os dados na caixa de diálogo Query Data.

    1. Por padrão, todas as colunas são retornadas. Para retornar colunas específicas, desative Retrieve All Columns e insira os nomes das colunas, separados por vírgulas.

      Nota

      Por padrão, o Table Store retorna as colunas de chave primária da tabela de dados.

    2. Selecione um operador lógico: And, Or ou Not.

      Ao selecionar And, a consulta retorna dados que atendem a todas as condições especificadas. Ao selecionar Or, a consulta retorna dados que atendem a pelo menos uma das condições especificadas. Ao selecionar Not, a consulta retorna dados que não atendem às condições especificadas.

    3. Selecione um campo de índice, clique em Add, defina o tipo de consulta para o campo de índice e insira um valor.

      Se necessário, repita esta etapa para adicionar configurações de consulta para vários campos de índice.

    4. Por padrão, a classificação está desativada. Para classificar os resultados por um campo específico, ative Enable Sorting, adicione o campo de classificação e configure a ordem de classificação.

    5. Por padrão, a agregação está desativada. Para realizar uma agregação estatística em um campo específico, ative Enable Aggregation, adicione o campo para agregação e defina as configurações de agregação.

  4. Clique em OK.

    Os resultados da consulta são exibidos na aba Index Management.

Usar a interface de linha de comando

Execute o comando search na interface de linha de comando para consultar dados de um índice de pesquisa. Para mais informações, consulte Search index.

  1. Execute o comando search para consultar dados da tabela usando o índice de pesquisa search_index. Esse comando retorna todas as colunas indexadas.

    search -n search_index --return_all_indexed
  2. Insira as condições de consulta conforme solicitado. Veja o exemplo a seguir:

    {
        "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 um SDK

Execute uma consulta booleana usando o Java SDK, Go SDK, Python SDK, Node.js SDK, .NET SDK ou PHP SDK. Este tópico usa o Java SDK como exemplo.

Os exemplos a seguir mostram como executar consultas booleanas.

Consultar linhas que atendem a todas as condições de subconsulta

Ao consultar linhas que atendem a todas as condições de subconsulta, determine se as pontuações de relevância para as linhas devem ser calculadas com base nos requisitos do seu negócio.

Calcular as pontuações de relevância para as linhas

O código de exemplo a seguir mostra como executar uma consulta booleana para buscar as linhas que atendem a todas as condições de subconsulta e calcular suas pontuações de relevância.

/**
 * 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());
    }
}

Não calcular as pontuações de relevância para as linhas

O código de exemplo a seguir mostra como executar uma consulta booleana para buscar as linhas que atendem a todas as condições de subconsulta sem calcular suas pontuações de relevância.

/**
     * 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 linhas que atendem a pelo menos uma das condições de subconsulta

O código de exemplo a seguir mostra como executar uma consulta booleana para buscar as linhas que atendem a pelo menos uma das condições 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 linhas que não atendem a nenhuma condição de subconsulta

O código de exemplo a seguir mostra como executar uma consulta booleana para buscar as linhas que não atendem a nenhuma condição 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 linhas que atendem a uma combinação de condições de subconsulta

O código de exemplo a seguir mostra como executar uma consulta booleana para buscar as linhas que atendem a uma combinação de condições de subconsulta: (col2<4 ou col3<5) ou (col2 = 4 e (col3 = 5 ou col3 =6)). Nessa combinação, as subconsultas booleanas são conectadas pelos operadores AND ou 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());

    }

Faturamento

A consulta de dados por meio de um Search Index consome throughput de leitura. Para mais informações, consulte Search Index metering and billing.

Perguntas frequentes

Referências