Todos os produtos
Search
Central de documentação

Tablestore:Consulta booleana

Última atualização: Jul 03, 2026

Uma consulta booleana recupera dados de uma tabela com base em uma combinação de subconsultas. O Tablestore retorna as linhas que atendem às condições das subconsultas. Uma subconsulta pode ser de qualquer tipo, inclusive outra consulta booleana.

Operação da API

Para executar uma consulta booleana, chame a operação Search ou ParallelScan e defina o tipo de consulta como BoolQuery.

Parâmetros

Parâmetro

Descrição

mustQueries

Lista de subconsultas. Retorna apenas as linhas que atendem a todas as condições das subconsultas. Este parâmetro equivale ao operador AND.

mustNotQueries

Lista de subconsultas. Retorna apenas as linhas que não atendem a nenhuma condição das subconsultas. Este parâmetro equivale ao operador NOT.

filterQueries

Lista de subconsultas. Retorna apenas as linhas que atendem a todos os subfiltros. Um filtro é semelhante a uma consulta, mas não calcula pontuação de relevância com base no número de subfiltros atendidos por uma linha.

shouldQueries

Lista de subconsultas opcionais para correspondência nos resultados. Este parâmetro equivale ao operador OR.

Retorna apenas as linhas que atendem ao número mínimo de condições de subconsulta especificado pelo parâmetro shouldQueries.

Uma pontuação de relevância geral mais alta indica que a linha atende a mais condições de subconsulta especificadas pelo parâmetro shouldQueries.

minimumShouldMatch

Número mínimo de condições de subconsulta especificadas pelo parâmetro shouldQueries que as linhas retornadas devem atender. Se não houver outras condições além das definidas em shouldQueries, o valor padrão de minimumShouldMatch será 1. Caso existam outras condições (como as dos parâmetros mustQueries, mustNotQueries e filterQueries), o valor padrão de minimumShouldMatch será 0.

getTotalCount

Define se o sistema deve retornar o número total de linhas que atendem às condições da consulta. O valor padrão é false, indicando que a contagem total não será retornada.

Definir este parâmetro como true compromete o desempenho da consulta.

tableName

Nome da tabela de dados.

indexName

Nome do índice de pesquisa.

columnsToGet

Define se o sistema deve retornar todas as colunas de cada linha que atenda às condições da consulta. Configure os campos returnAll e columns para este parâmetro.

O valor padrão do campo returnAll é false, indicando que nem todas as colunas serão retornadas. Nesse caso, use o campo columns para especificar as colunas desejadas. Sem essa especificação, o sistema retorna apenas as colunas de chave primária.

Se você definir o campo returnAll como true, todas as colunas serão retornadas.

Métodos

Execute consultas booleanas usando o console do Tablestore, a CLI do Tablestore ou os SDKs do Tablestore. Antes de prosseguir, certifique-se de cumprir os seguintes pré-requisitos:

Usar o console do Tablestore

  1. Acesse a aba Index Management.

    1. Faça login no console do Table Store.

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

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

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

  2. Na aba Index Management, localize o Índice de Pesquisa desejado e clique em Search na coluna Actions.

  3. Na caixa de diálogo Search, especifique as condições da consulta.

    1. Por padrão, todas as colunas são retornadas. Para retornar colunas específicas, desative a opção 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. Se escolher Or, a consulta retorna dados que atendem a pelo menos uma das condições. Ao optar por Not, a consulta retorna dados que não atendem às condições especificadas.

    3. Selecione um campo de índice e clique em Add. Em seguida, configure os parâmetros Query Type e Value.

      Repita esta etapa para adicionar condições de consulta para múltiplos campos de índice.

    4. A ordenação vem desativada por padrão. 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. A agregação vem desativada por padrão. Para realizar uma agregação estatística em um campo específico, ative Enable Aggregation, adicione o campo para agregação e configure as definições de agregação.

  4. Clique em OK.

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

Usar a CLI do Tablestore

Use a CLI do Tablestore para executar o comando search e consultar dados por meio de índices de pesquisa. Para mais informações, consulte Índice de pesquisa.

  1. Execute o comando search para usar o índice de pesquisa search_index, consultar dados e retornar todas as colunas indexadas de cada linha que atenda às condições da consulta.

    search -n search_index --return_all_indexed
  2. Insira as condições da consulta conforme solicitado:

    {
        "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 SDKs do Tablestore

Utilize os seguintes SDKs do Tablestore para realizar uma consulta booleana: Tablestore SDK for Java, Tablestore SDK for Go, Tablestore SDK for Python, Tablestore SDK for Node.js, Tablestore SDK for .NET e Tablestore SDK for PHP. Neste exemplo, utiliza-se o Tablestore SDK for Java.

Os exemplos a seguir demonstram como executar consultas booleanas.

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

Ao consultar linhas que satisfazem todas as condições de subconsulta, decida se deseja calcular as pontuações de relevância das linhas com base nos requisitos do seu negócio.

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

O código de exemplo abaixo mostra como executar uma consulta booleana para recuperar 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 das linhas

O código de exemplo abaixo demonstra como executar uma consulta booleana para recuperar linhas que atendem a todas as condições de subconsulta sem calcular as 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 ilustra como executar uma consulta booleana para recuperar linhas que satisfazem 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 exemplo de código abaixo mostra como executar uma consulta booleana para recuperar linhas que não satisfazem nenhuma das condições 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 demonstra como executar uma consulta booleana para recuperar linhas que satisfazem uma combinação de condições de subconsulta, representada por (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 Índice de Pesquisa consome throughput de leitura. Para mais informações, consulte Medição e faturamento do Índice de Pesquisa.

Perguntas frequentes

Referências