Todos os produtos
Search
Central de documentação

Tablestore:Getting started with the search index feature

Última atualização: Jun 30, 2026

Este tópico descreve como usar rapidamente o Tablestore SDK for Java para realizar operações em índices de busca.

Pré-requisitos

  • Cliente inicializado. Para mais informações, consulte Inicializar um cliente Tablestore.

  • Tabela de dados criada com as seguintes condições. Para mais informações, consulte Criar uma tabela de dados.

    • Parâmetro max versions definido como 1.

    • TTL definido como -1 ou atualizações na tabela de dados proibidas.

Procedimento

Etapa 1: Criar um índice de busca

Crie um índice de busca para acelerar consultas de dados. Ao criar o índice, adicione os campos que deseja consultar. Configure também opções avançadas, como tempo de vida (TTL) e pré-classificação, conforme as necessidades do seu negócio.

O código de exemplo a seguir demonstra como criar um índice de busca para uma tabela de dados. Neste exemplo, o índice contém a coluna Col_Keyword do tipo Keyword e a coluna Col_Long do tipo Long. Os dados no índice são pré-classificados com base na chave primária da tabela e nunca expiram.

Nota

Para obter informações sobre os mapeamentos de tipos de dados entre índices de busca e tabelas de dados, consulte Tipos de dados.

private static void createSearchIndex(SyncClient client) {
    CreateSearchIndexRequest request = new CreateSearchIndexRequest();
    // Specify the name of the data table.
    request.setTableName("sampletable"); 
    // Specify the name of the search index.
    request.setIndexName("samplesearchindex"); 
    IndexSchema indexSchema = new IndexSchema();
    indexSchema.setFieldSchemas(Arrays.asList(
            // Specify the names and types of the fields.
            new FieldSchema("Col_Keyword", FieldType.KEYWORD), 
            new FieldSchema("Col_Long", FieldType.LONG)));
    request.setIndexSchema(indexSchema);
    // Call the client to create the search index.
    client.createSearchIndex(request); 
}

Etapa 2: Consultar dados usando o índice de busca

Ao usar um índice de busca para consultar dados, selecione os tipos de consulta adequados ao seu cenário de negócios. Especifique as colunas a retornar e o método de classificação dos dados resultantes.

O exemplo de código a seguir mostra como consultar linhas em que o valor da coluna Col_Keyword corresponde exatamente a "hangzhou" em uma tabela:

/**
 * Query the rows in which the value of the Col_Keyword column exactly matches "hangzhou" in a table.
 * @param client
 */
private static void termQuery(SyncClient client) {
    SearchQuery searchQuery = new SearchQuery();
    TermQuery termQuery = new TermQuery(); // Set the query type to TermQuery.
    termQuery.setFieldName("Col_Keyword"); // Specify the name of the column that you want to query.
    termQuery.setTerm(ColumnValue.fromString("hangzhou")); // Specify the keyword that you want to match.
    searchQuery.setQuery(termQuery);
    //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 that you want 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 ReturnAll to true to return all columns.
    //columnsToGet.setColumns(Arrays.asList("ColName1","ColName2")); // Configure the Columns parameter to 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 rows that are returned is displayed.
    System.out.println("Row: " + resp.getRows());
}

Referências