通过 Java SDK 配置多元索引的数据生命周期(Time To Live,TTL),Tablestore 会自动清理超过保存期限的索引数据。
前提条件
开始前,完成以下准备工作:
-
安装 5.12.0 及以上版本的Tablestore Java SDK并初始化客户端。
-
已创建待配置的数据表,并将最大版本数设置为 1。
注意事项
-
使用多元索引生命周期管理功能前,必须禁止数据表通过
UpdateRow更新数据,以避免数据表与多元索引的数据不一致。数据表 TTL 按属性列生效,多元索引 TTL 按整行生效。使用
UpdateRow更新数据时,系统清理过期数据后,数据表可能只保留部分属性列,而多元索引仍保留整行数据。需要更新数据时,请改用
PutRow覆盖整行数据。 -
多元索引 TTL 的单位为秒,取值为
-1或 int32 范围内的正整数。-1表示永久存储,正整数最大值对应的保存时间约为 68 年。 -
多元索引 TTL 与数据表 TTL 独立配置,但多元索引 TTL 必须小于或等于数据表 TTL。如果多元索引的目标 TTL 大于当前数据表 TTL,先增大数据表 TTL;如果同时减小二者,先减小多元索引 TTL。
-
Tablestore 每天自动清理多元索引中的过期数据。在下一次清理完成前,查询仍可能返回已过期但尚未清理的数据。
-
更新数据表或多元索引的 TTL 后,Tablestore 会在下一次清理周期自动清理因 TTL 变更而过期的存量数据。
操作步骤
生命周期配置包括禁止数据表通过 UpdateRow 更新数据、设置多元索引生命周期,以及按需设置数据表生命周期。数据表生命周期不是固定的最后一步,操作顺序必须保证多元索引 TTL 小于或等于数据表 TTL:如果多元索引的目标 TTL 大于当前数据表 TTL,先增大数据表 TTL;如果同时减小二者,先减小多元索引 TTL。
-
禁止数据表通过
UpdateRow更新数据。以下示例禁止
example_table通过UpdateRow更新数据。String tableName = "example_table"; UpdateTableRequest request = new UpdateTableRequest(tableName); TableOptions tableOptions = new TableOptions(); tableOptions.setAllowUpdate(false); request.setTableOptionsForUpdate(tableOptions); client.updateTable(request); -
设置多元索引生命周期。
根据多元索引是否已创建,选择相应的设置方式。
新建索引
创建多元索引时,将生命周期设置为 7 天。
String tableName = "example_table"; String indexName = "example_index"; 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); request.setTimeToLiveInDays(7); client.createSearchIndex(request);已有索引
将已有多元索引的生命周期更新为 7 天。
String tableName = "example_table"; String indexName = "example_index"; UpdateSearchIndexRequest request = new UpdateSearchIndexRequest(tableName, indexName); request.setTimeToLiveInDays(7); client.updateSearchIndex(request); -
按需设置数据表生命周期。
以下示例将
example_table的生命周期设置为 7 天。请根据上述 TTL 约束,在设置多元索引生命周期之前或之后执行此操作。String tableName = "example_table"; UpdateTableRequest request = new UpdateTableRequest(tableName); TableOptions tableOptions = new TableOptions(); tableOptions.setTimeToLiveInDays(7); request.setTableOptionsForUpdate(tableOptions); client.updateTable(request);