Todos os produtos
Search
Central de documentação

Tablestore:Especifique o TTL de um índice de pesquisa

Última atualização: Jul 03, 2026

O tempo de vida (TTL) é um atributo de um índice de pesquisa que define o período de retenção de dados. O Tablestore exclui automaticamente os dados que ultrapassam esse período para reduzir o uso e os custos de armazenamento.

Pré-requisitos

Observações de uso

  • Esta exigência evita inconsistências de dados entre a tabela de dados e o índice de pesquisa.

    O TTL de uma tabela de dados aplica-se por coluna de atributo, enquanto o TTL de um índice de pesquisa aplica-se à linha inteira. Se você utilizar uma operação UpdateRow, o Tablestore poderá excluir algumas colunas da tabela de dados enquanto a linha correspondente permanece no índice de pesquisa, causando dessincronização.

    Caso precise atualizar dados, utilize a operação PutRow para sobrescrever a linha inteira.

  • O TTL de um índice de pesquisa, especificado em segundos, pode ser -1 ou um inteiro positivo de 32 bits. O valor -1 indica que os dados são armazenados permanentemente. O valor máximo corresponde a aproximadamente 68 anos.

  • O TTL de um índice de pesquisa é independente do TTL da tabela de dados. O valor do TTL do índice de pesquisa deve ser menor ou igual ao valor do TTL da tabela de dados. Ao reduzir ambos os TTLs, diminua primeiro o TTL do índice de pesquisa e, em seguida, o TTL da tabela de dados.

  • O Tablestore limpa automaticamente os dados expirados dos índices de pesquisa diariamente. Você ainda pode consultar dados expirados até que sejam removidos durante esse processo de limpeza.

  • Após atualizar o TTL de uma tabela de dados e de um índice de pesquisa, o Tablestore remove quaisquer dados recém-expirados no próximo ciclo de limpeza.

Procedimento

  1. Desative a operação UpdateRow em uma tabela de dados.

    O código de exemplo a seguir mostra como desativar a operação UpdateRow em uma tabela de dados:

    func disableTableUpdate(client *tablestore.TableStoreClient) {
        request := &tablestore.UpdateTableRequest{
           TableName: "TableName",
           TableOption: &tablestore.TableOption{
              TimeToAlive:               -1,    // Use the default value for the TTL of a data table. The default value is -1. 
              MaxVersion:                1,     // Use the default value for max versions. The default value is 1. 
              DeviationCellVersionInSec: 86400, // Use the default value for max version offset. The default value is 86400. Unit: seconds. 
              // Disable the UpdateRow operation on a data table to ensure business continuity. If a TTL is configured for the search index of a data table, you cannot allow updates to the data table. 
              AllowUpdate: proto.Bool(false),
          },
       }
        resp, err := client.UpdateTable(request)
        if err != nil {
           fmt.Println("error :", err)
           return
       }
        fmt.Println("UpdateTable finished, requestId:", resp.ResponseInfo.RequestId)
    }
  2. Especifique o TTL de um índice de pesquisa.

    Após desativar a operação UpdateRow em uma tabela de dados, especifique o TTL de um índice de pesquisa ao criar o índice ou altere o TTL de um índice existente.

    Especifique o TTL ao criar um índice de pesquisa

    O código de exemplo a seguir mostra como criar um índice de pesquisa. Neste exemplo, o índice consiste em duas colunas: a coluna col1 do tipo String e a coluna col2 do tipo Long. O TTL do índice de pesquisa é de sete dias.

    func createIndexWithTTL(client *tablestore.TableStoreClient) {
        request := &tablestore.CreateSearchIndexRequest{}
        request.TableName = "<TABLE_NAME>"
        request.IndexName = "<SEARCH_INDEX_NAME>"
        schemas := []*tablestore.FieldSchema{}
        field1 := &tablestore.FieldSchema{
            FieldName:        proto.String("col1"), // Specify the column name by calling the proto.String method. This method is used to request a string pointer. 
            FieldType:        tablestore.FieldType_KEYWORD, // Specify the column type. 
            Index:            proto.Bool(true),             // Enable indexing for the column. 
            EnableSortAndAgg: proto.Bool(true),             // Enable sorting and aggregation. 
        }
        field2 := &tablestore.FieldSchema{
            FieldName:        proto.String("col2"),
            FieldType:        tablestore.FieldType_LONG,
            Index:            proto.Bool(true),
            EnableSortAndAgg: proto.Bool(true),
        }
        schemas = append(schemas, field1, field2)
        request.IndexSchema = &tablestore.IndexSchema{
            FieldSchemas: schemas, // Specify the columns that are included in the search index. 
        }
        request.TimeToLive = proto.Int32(3600 * 24 * 7) // Set the TTL of the search index to seven days. 
        resp, err := client.CreateSearchIndex(request)
        if err != nil {
           fmt.Println("error :", err)
           return
       }
        fmt.Println("createIndexWithTTL finished, requestId:", resp.ResponseInfo.RequestId)
    }

    Altere o TTL de um índice de pesquisa existente

    O código de exemplo a seguir mostra como definir o TTL de um índice de pesquisa existente para sete dias:

    func updateIndexWithTTL(client *tablestore.TableStoreClient) {
        request := &tablestore.UpdateSearchIndexRequest{}
        request.TableName = "TableName"
        request.IndexName = "IndexName"
        request.TimeToLive = proto.Int32(3600 * 24 * 7) // Set the TTL of the search index to seven days. 
        resp, err := client.UpdateSearchIndex(request)
        if err != nil {
           fmt.Println("error :", err)
           return
       }
        fmt.Println("updateIndexWithTTL finished, requestId:", resp.ResponseInfo.RequestId)
    }
  3. O TTL de um índice de pesquisa é independente do TTL da tabela de dados para a qual o índice foi criado. Caso deseje usar o recurso de TTL para uma tabela de dados, especifique o TTL da tabela.

    O código de exemplo a seguir mostra como definir o TTL de uma tabela de dados para sete dias:

    // Set the TTL of the data table to seven days. 
    func updateTableTTL(client *tablestore.TableStoreClient) {
        request := &tablestore.UpdateTableRequest{
            TableName: "TableName",
            TableOption: &tablestore.TableOption{
                TimeToAlive:               3600 * 24 * 7, // Set the TTL of the data table to seven days. Make sure that the TTL of the data table is greater than or equal to the TTL of the search index that is created for the data table. 
                MaxVersion:                1,             // Use the default value for max versions. The default value is 1. 
                DeviationCellVersionInSec: 86400,         // Use the default value for max version offset. The default value is 86400. Unit: seconds. 
                // Disable the UpdateRow operation on a data table to ensure business continuity. If a TTL is configured for the search index of a data table, you cannot allow updates to the data table. 
                AllowUpdate: proto.Bool(false),
            },
        }
        resp, err := client.UpdateTable(request)
        if err != nil {
            fmt.Println("error :", err)
            return
        }
        fmt.Println("UpdateTable finished, requestId:", resp.ResponseInfo.RequestId)
    }

Perguntas frequentes

[O que fazer se a mensagem de erro [table ttl] must be bigger than or equal search index ttl for retornada ao modificar o TTL de uma tabela de dados?](t2633375.xdita#)

Referências