Todos os produtos
Search
Central de documentação

Tablestore:Search index quick start

Última atualização: Jul 30, 2026

Os search indexes permitem consultar dados com base em colunas que não são de chave primária e em múltiplas condições. Este tópico usa dados de product como exemplo para mostrar como crie uma tabela de dados e um search index, gravar dados e execute uma term query com o Tablestore SDK for Java.

Preparativos

  • Ative o Tablestore e crie uma instância. Para mais informações, consulte Activate service and create instance.

  • Instale o Tablestore SDK for Java, inicialize um cliente e obtenha uma instância SyncClient. Para mais informações, consulte Java SDK.

Procedimento

Neste exemplo, você cria uma tabela de dados chamada example_table e um search index chamado example_index. Depois que o search index estiver pronto, grave três linhas de product e consulte as linhas cujo valor da coluna category seja books.

Adicione os métodos de exemplo das etapas a seguir à aplicação Java em que o cliente foi inicializado. Em seguida, chame os métodos na seguinte ordem:

private static void runQuickStart(SyncClient client)
        throws InterruptedException {
    String tableName = "example_table";
    String indexName = "example_index";

    createTable(client, tableName);
    createSearchIndex(client, tableName, indexName);
    waitUntilSearchIndexIsReady(client, tableName, indexName);
    putSampleRows(client, tableName);

    SearchResponse response =
            waitUntilBooksAreQueryable(client, tableName, indexName);
    System.out.println("Total count: " + response.getTotalCount());
    System.out.println("Rows: " + response.getRows());
}

Etapa 1: Criar uma tabela de dados

Para criar um search index em uma tabela de dados, defina o número máximo de versões como 1. Defina também o tempo de vida (TTL) da tabela de dados como -1 para indicar que os dados nunca expiram ou desative as atualizações de dados. Neste exemplo, o número máximo de versões é definido como 1 e o TTL como -1.

private static void createTable(
        SyncClient client, String tableName) {
    TableMeta tableMeta = new TableMeta(tableName);
    tableMeta.addPrimaryKeyColumn(
            new PrimaryKeySchema(
                    "product_id", PrimaryKeyType.STRING));

    TableOptions tableOptions = new TableOptions();
    tableOptions.setTimeToLive(-1);
    tableOptions.setMaxVersions(1);

    client.createTable(
            new CreateTableRequest(tableMeta, tableOptions));
}

Etapa 2: Criar um search index

Crie campos de índice para as colunas de atributo category e price. O nome e o tipo de dados de um campo de índice devem ser idênticos aos da coluna de atributo correspondente na tabela de dados.

private static void createSearchIndex(
        SyncClient client, String tableName, String indexName) {
    IndexSchema indexSchema = new IndexSchema();
    indexSchema.setFieldSchemas(Arrays.asList(
            new FieldSchema("category", FieldType.KEYWORD),
            new FieldSchema("price", FieldType.LONG)));

    CreateSearchIndexRequest request =
            new CreateSearchIndexRequest();
    request.setTableName(tableName);
    request.setIndexName(indexName);
    request.setIndexSchema(indexSchema);
    client.createSearchIndex(request);
}

A criação de search indexes ocorre de forma assíncrona. Aguarde até que o status do índice mude para RUNNING e a fase de sincronização mude para INCR antes de consultar dados.

private static final int RETRY_ATTEMPTS = 90;
private static final long RETRY_INTERVAL_MILLIS = 1_000L;

private static void waitUntilSearchIndexIsReady(
        SyncClient client, String tableName, String indexName)
        throws InterruptedException {
    for (int attempt = 1; attempt <= RETRY_ATTEMPTS; attempt++) {
        DescribeSearchIndexRequest request =
                new DescribeSearchIndexRequest();
        request.setTableName(tableName);
        request.setIndexName(indexName);
        request.setIncludeSyncStat(true);

        DescribeSearchIndexResponse response =
                client.describeSearchIndex(request);
        if (response.getIndexStatus() != null
                && response.getIndexStatus().indexStatusEnum
                == DescribeSearchIndexResponse.IndexStatusEnum.RUNNING
                && response.getSyncStat() != null
                && response.getSyncStat().getSyncPhase()
                == SyncStat.SyncPhase.INCR) {
            return;
        }
        Thread.sleep(RETRY_INTERVAL_MILLIS);
    }
    throw new IllegalStateException(
            "Search index did not become ready before timeout.");
}

Etapa 3: Gravar dados de exemplo

Grave três linhas de product. A coluna product_id é a coluna de chave primária. As colunas category e price são colunas de atributo.

private static void putSampleRows(
        SyncClient client, String tableName) {
    putProduct(client, tableName, "product-001", "books", 89L);
    putProduct(client, tableName, "product-002", "books", 129L);
    putProduct(client, tableName, "product-003", "devices", 599L);
}

private static void putProduct(
        SyncClient client,
        String tableName,
        String productId,
        String category,
        long price) {
    PrimaryKey primaryKey =
            PrimaryKeyBuilder.createPrimaryKeyBuilder()
                    .addPrimaryKeyColumn(
                            "product_id",
                            PrimaryKeyValue.fromString(productId))
                    .build();

    RowPutChange rowPutChange =
            new RowPutChange(tableName, primaryKey);
    rowPutChange.addColumn(
            "category", ColumnValue.fromString(category));
    rowPutChange.addColumn(
            "price", ColumnValue.fromLong(price));
    client.putRow(new PutRowRequest(rowPutChange));
}

Etapa 4: Consultar dados

Execute uma term query para corresponder às linhas cujo valor da coluna category seja books. A sincronização de dados para um search index leva algum tempo. O código de exemplo repete a consulta se o resultado ainda não estiver disponível.

private static SearchResponse waitUntilBooksAreQueryable(
        SyncClient client, String tableName, String indexName)
        throws InterruptedException {
    for (int attempt = 1; attempt <= RETRY_ATTEMPTS; attempt++) {
        SearchResponse response =
                queryBooks(client, tableName, indexName);
        if (response.isAllSuccess()
                && response.getTotalCount() == 2L
                && response.getRows().size() == 2) {
            return response;
        }
        Thread.sleep(RETRY_INTERVAL_MILLIS);
    }
    throw new IllegalStateException(
            "Sample rows were not queryable before timeout.");
}

private static SearchResponse queryBooks(
        SyncClient client, String tableName, String indexName) {
    TermQuery termQuery = new TermQuery();
    termQuery.setFieldName("category");
    termQuery.setTerm(ColumnValue.fromString("books"));

    SearchQuery searchQuery = new SearchQuery();
    searchQuery.setQuery(termQuery);
    searchQuery.setLimit(10);
    searchQuery.setTrackTotalCount(
            SearchQuery.TRACK_TOTAL_COUNT);

    SearchRequest.ColumnsToGet columnsToGet =
            new SearchRequest.ColumnsToGet();
    columnsToGet.setReturnAll(true);

    SearchRequest request =
            new SearchRequest(tableName, indexName, searchQuery);
    request.setColumnsToGet(columnsToGet);
    return client.search(request);
}

Se o número total de linhas correspondentes e o número de linhas retornadas forem 2, a consulta foi bem-sucedida.

Limpar recursos

Se não precisar mais dos recursos de exemplo, exclua o search index antes de excluir a tabela de dados.

DeleteSearchIndexRequest deleteIndexRequest =
        new DeleteSearchIndexRequest();
deleteIndexRequest.setTableName("example_table");
deleteIndexRequest.setIndexName("example_index");
client.deleteSearchIndex(deleteIndexRequest);

client.deleteTable(new DeleteTableRequest("example_table"));
client.shutdown();

Próximos passos

  • Para entender o funcionamento, os casos de uso e os limites dos search indexes, consulte Search index.

  • Para obter detalhes sobre ordenação de índice, TTL, colunas virtuais e outros recursos de índice, consulte Create a search index.

  • Para saber mais sobre outros tipos de consulta e como ordenar, agregar ou deduplicar resultados, consulte Data query.