

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 DynamoDB 中啟用存留時間 (TTL)
<a name="time-to-live-ttl-how-to"></a>

**注意**  
為協助偵錯與驗證 TTL 功能是否正常運作，項目的 TTL 值會以純文字形式記錄在 DynamoDB 診斷日誌中。

您可以在 Amazon DynamoDB 主控台、 AWS Command Line Interface (AWS CLI) 中啟用 TTL，或使用 [Amazon DynamoDB API 參考](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/)與任何支援的 AWS SDKs。在所有分割區啟用 TTL 約需一小時。

## 使用 AWS 主控台啟用 DynamoDB TTL
<a name="time-to-live-ttl-how-to-enable-console"></a>

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/) 開啟 DynamoDB 主控台。

1. 選擇 **Tables (資料表)**，然後選擇您想要修改的資料表。

1. 在**附加設定**分頁的**存留時間 (TTL)**區段中，選取**開啟**以啟用 TTL。

1. 在資料表上啟用 TTL 時，DynamoDB 會要求您識別服務在判斷項目是否符合過期資格時將尋找的特定屬性名稱。如下所示的 TTL 屬性名稱區分大小寫，且必須與讀寫操作中定義的屬性一致。若不一致，過期項目將無法被刪除。若要重新命名 TTL 屬性，您必須先停用 TTL，然後使用新的屬性名稱重新啟用。停用後，TTL 仍會在約 30 分鐘內持續處理刪除作業。還原資料表後，必須重新設定 TTL。  
![\[DynamoDB 用於判定項目是否符合過期條件的區分大小寫 TTL 屬性名稱。\]](http://docs.aws.amazon.com/zh_tw/amazondynamodb/latest/developerguide/images/EnableTTL-Settings.png)

1. (選用) 您可以模擬到期日期與時間，並比對部分項目以進行測試。這將提供項目範例清單，並確認其中包含設定了 TTL 屬性名稱與到期時間的項目。

啟用 TTL 後，當您在 DynamoDB 主控台檢視項目時，TTL 屬性會顯示為 **TTL**。您可以將滑鼠游標懸停到屬性上，來檢視項目過期的日期和時間。

## 使用 API 啟用 DynamoDB TTL
<a name="time-to-live-ttl-how-to-enable-api"></a>

------
#### [ Python ]

您可以透過 [UpdateTimeToLive](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/update_time_to_live.html) 操作以程式碼啟用 TTL。

```
import boto3


def enable_ttl(table_name, ttl_attribute_name):
    """
    Enables TTL on DynamoDB table for a given attribute name
        on success, returns a status code of 200
        on error, throws an exception

    :param table_name: Name of the DynamoDB table
    :param ttl_attribute_name: The name of the TTL attribute being provided to the table.
    """
    try:
        dynamodb = boto3.client('dynamodb')

        # Enable TTL on an existing DynamoDB table
        response = dynamodb.update_time_to_live(
            TableName=table_name,
            TimeToLiveSpecification={
                'Enabled': True,
                'AttributeName': ttl_attribute_name
            }
        )

        # In the returned response, check for a successful status code.
        if response['ResponseMetadata']['HTTPStatusCode'] == 200:
            print("TTL has been enabled successfully.")
        else:
            print(f"Failed to enable TTL, status code {response['ResponseMetadata']['HTTPStatusCode']}")
    except Exception as ex:
        print("Couldn't enable TTL in table %s. Here's why: %s" % (table_name, ex))
        raise


# your values
enable_ttl('your-table-name', 'expirationDate')
```

您可以使用 [DescribeTimeToLive](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/describe_time_to_live.html) 操作確認 TTL 是否已啟用，該操作會回報資料表的 TTL 狀態。`TimeToLive` 狀態可能為 `ENABLED` 或 `DISABLED`。

```
# create a DynamoDB client
dynamodb = boto3.client('dynamodb')

# set the table name
table_name = 'YourTable'

# describe TTL
response = dynamodb.describe_time_to_live(TableName=table_name)
```

------
#### [ JavaScript ]

您可以透過 [UpdateTimeToLiveCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-dynamodb/Class/UpdateTimeToLiveCommand/) 操作以程式碼啟用 TTL。

```
import { DynamoDBClient, UpdateTimeToLiveCommand } from "@aws-sdk/client-dynamodb";

const enableTTL = async (tableName, ttlAttribute) => {

    const client = new DynamoDBClient({});

    const params = {
        TableName: tableName,
        TimeToLiveSpecification: {
            Enabled: true,
            AttributeName: ttlAttribute
        }
    };

    try {
        const response = await client.send(new UpdateTimeToLiveCommand(params));
        if (response.$metadata.httpStatusCode === 200) {
            console.log(`TTL enabled successfully for table ${tableName}, using attribute name ${ttlAttribute}.`);
        } else {
            console.log(`Failed to enable TTL for table ${tableName}, response object: ${response}`);
        }
        return response;
    } catch (e) {
        console.error(`Error enabling TTL: ${e}`);
        throw e;
    }
};

// call with your own values
enableTTL('ExampleTable', 'exampleTtlAttribute');
```

------

## 使用 啟用存留時間 AWS CLI
<a name="time-to-live-ttl-how-to-enable-cli-sdk"></a>

1. 啟用 `TTLExample` 表中的 TTL。

   ```
   aws dynamodb update-time-to-live --table-name TTLExample --time-to-live-specification "Enabled=true, AttributeName=ttl"
   ```

1. 描述 `TTLExample` 表中的 TTL。

   ```
   aws dynamodb describe-time-to-live --table-name TTLExample
   {
       "TimeToLiveDescription": {
           "AttributeName": "ttl",
           "TimeToLiveStatus": "ENABLED"
       }
   }
   ```

1. 使用 BASH shell 及 AWS CLI，將項目新增至已設定存留時間屬性的 `TTLExample` 資料表。

   ```
   EXP=`date -d '+5 days' +%s`
   aws dynamodb put-item --table-name "TTLExample" --item '{"id": {"N": "1"}, "ttl": {"N": "'$EXP'"}}'
   ```

此範例建立的過期時間為從目前的日期開始加 5 天。然後，將過期時間轉換成 Epoch 時間格式，最終將項目新增到 "`TTLExample`" 表。

**注意**  
 設定存留時間過期數值的其中一種方式，是計算要新增到過期時間的秒數。例如，5 天等於 432,000 秒。但是通常建議從日期開始操作。

取得目前時間的 Epoch 時間格式非常容易，如以下範例所示。
+ Linux 終端機：`date +%s`
+ Python：`import time; int(time.time())`
+ Java：`System.currentTimeMillis() / 1000L`
+ JavaScript：`Math.floor(Date.now() / 1000)`

## 使用 啟用 DynamoDB TTL CloudFormation
<a name="time-to-live-ttl-how-to-enable-cf"></a>

```
AWSTemplateFormatVersion: "2010-09-09"
Resources:
  TTLExampleTable:
    Type: AWS::DynamoDB::Table
    Description: "A DynamoDB table with TTL Specification enabled"
    Properties:
      AttributeDefinitions:
        - AttributeName: "Album"
          AttributeType: "S"
        - AttributeName: "Artist"
          AttributeType: "S"
      KeySchema:
        - AttributeName: "Album"
          KeyType: "HASH"
        - AttributeName: "Artist"
          KeyType: "RANGE"
      ProvisionedThroughput:
        ReadCapacityUnits: "5"
        WriteCapacityUnits: "5"
      TimeToLiveSpecification:
        AttributeName: "TTLExampleAttribute"
        Enabled: true
```

您可以在[此處](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-table-timetolivespecification.html)找到有關在 CloudFormation 範本中使用 TTL 的其他詳細資訊。