資料生命週期(Time To Live,簡稱TTL)是多元索引的一個屬性,即資料的儲存時間。多元索引會自動清理超過儲存時間的資料,減少使用者的資料存放區空間,降低儲存成本。

前提條件

  • 已初始化OTSClient。具體操作,請參見初始化
  • 已建立資料表。

注意事項

  • 使用多元索引生命週期功能,必須禁用資料表的UpdateRow更新寫入功能,避免一些語義上的問題:

    由於資料表TTL是屬性列層級生效的,而多元索引TTL是整行生效的,如果存在UpdateRow寫入操作,當系統清理資料表中資料時,資料表中部分欄位值已刪除而部分欄位值未刪除,但是多元索引中整行資料均未刪除,則會造成資料表和多元索引中的資料不一致。

    如果業務有UpdateRow更新寫入操作,請查看是否能改為PutRow覆蓋寫入操作。

  • 多元索引的TTL取值範圍為-1或者int32的正整數(單位為秒),其中-1表示永久儲存,int32最大值換算為年大約為68年。
  • 多元索引的TTL和資料表的TTL是獨立的,多元索引的TTL值必須小於或等於資料表的TTL值。當需要同時調小多元索引TTL和資料表TTL時,請先調整多元索引TTL,再調整資料表TTL。
  • 多元索引每天會自動清理已到期的資料,到期資料的清理粒度為“天”,因此您仍然可以查詢到某一時刻已到期但是還未及時清理的資料,多元索引會在下一次清理到期資料時自動清理這些到期資料。
  • 資料表和多元索引的TTL更新後,系統會在下一次清理到期資料時自動清理資料表和多元索引中的存量到期資料。

使用流程

  1. 禁用資料表UpdateRow更新寫入操作。
    public void disableTableUpdate(SyncClient client) {
        UpdateTableRequest updateTableRequest = new UpdateTableRequest(tableName);
        TableOptions options = new TableOptions();
        // 禁用資料表Update更新寫入操作,請確保資料表無Update寫入操作,避免影響業務。
        options.setAllowUpdate(false);
        updateTableRequest.setTableOptionsForUpdate(options);
        client.updateTable(updateTableRequest);
    }
  2. 設定多元索引生命週期。

    禁用資料表UpdateRow更新寫入操作後,您可以在建立多元索引時指定TTL或者為已有多元索引指定TTL。

    • 建立多元索引時指定TTL
      // 請使用5.12.0及以上版本的Java SDK。
      public void createIndexWithTTL(SyncClient client) {
          int days = 7;
          CreateSearchIndexRequest createRequest = new CreateSearchIndexRequest();
          createRequest.setTableName(tableName);
          createRequest.setIndexName(indexName);
          createRequest.setIndexSchema(indexSchema);
          // 設定多元索引TTL。
          createRequest.setTimeToLiveInDays(days);
          client.createSearchIndex(createRequest);
      }
    • 為已有多元索引指定TTL
      // 請使用5.12.0及以上版本的Java SDK。
      public void updateIndexWithTTL(SyncClient client) {
          int days = 7;
          UpdateSearchIndexRequest updateSearchIndexRequest = new UpdateSearchIndexRequest(tableName, indexName);
          // 更新多元索引TTL。
          updateSearchIndexRequest.setTimeToLiveInDays(days);
          client.updateSearchIndex(updateSearchIndexRequest);
      }
  3. 多元索引的TTL和資料表的TTL是獨立的。如果需要使用資料表TTL,請為資料表設定TTL。
    public void updateTableTTL(SyncClient client) {
        int days = 7;
        UpdateTableRequest updateTableRequest = new UpdateTableRequest(tableName);
        TableOptions options = new TableOptions();
        options.setTimeToLiveInDays(days);
        updateTableRequest.setTableOptionsForUpdate(options);
        client.updateTable(updateTableRequest);
    }