启用生存时间(TTL) - Amazon DynamoDB

启用生存时间(TTL)

您可以在 Amazon DynamoDB 控制台中,在 AWS Command Line Interface(AWS CLI)中,或者对于任何支持的 AWS SDK 使用 Amazon DynamoDB API 参考,来启用 TTL。在所有分区中启用 TTL 大约需要一个小时。

  1. 登录 AWS Management Console,打开 DynamoDB 控制台:https://console.aws.amazon.com/dynamodb/

  2. 选择,然后选择您要修改的表。

  3. 其它设置选项卡的生存时间(TTL) 部分中,选择开启来启用 TTL。

  4. 在表上启用 TTL 时,DynamoDB 要求您标识此服务在确定项目是否符合过期条件时将查找的特定属性名称。如下所示的 TTL 属性名称区分大小写,并且必须与读取和写入操作中定义的属性相匹配。不匹配将导致已过期的项目被取消删除。重命名 TTL 属性需要您禁用 TTL,然后使用新属性重新启用它。禁用后,TTL 将在大约 30 分钟内继续处理删除。必须对已恢复的表重新配置 TTL。

    区分大小写的 TTL 属性名称,DynamoDB 使用该属性来确定项目是否符合过期条件。
  5. (可选)您可以通过模拟过期日期和时间并匹配几个项目来执行测试。这为您提供了项目的样本列表,并确认有些项目包含随过期时间提供的 TTL 属性名称。

TTL 启用后,当您在 DynamoDB 控制台上查看项目时,TTL 属性被标记为 TTL。您可以通过将指针悬停在属性上来查看项目过期的日期和时间。

Python

您可以使用 UpdateTimeToLive 操作通过代码启用 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 操作确认 TTL 已启用,该操作描述了表上的 TTL 状态。TimeToLive 状态为 ENABLEDDISABLED

# 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 操作通过代码启用 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');
  1. TTLExample 表上启用 TTL。

    aws dynamodb update-time-to-live --table-name TTLExample --time-to-live-specification "Enabled=true, AttributeName=ttl"
  2. TTLExample 表上描述 TTL。

    aws dynamodb describe-time-to-live --table-name TTLExample { "TimeToLiveDescription": { "AttributeName": "ttl", "TimeToLiveStatus": "ENABLED" } }
  3. 通过使用 BASH shell 和 TTLExample 设置生存时间属性将项目添加至 AWS CLI 表。

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

此示例从当前日期开始,并在当前日期上增加 5 天来创建过期时间。然后,它将过期时间转换为纪元时间格式,以便最终添加项目到“TTLExample”表。

注意

为生存时间设置过期值的一种方式是计算添加到过期时间的秒数。例如,5 天是 432000 秒。但是,人们通常习惯于从某个日期算起。

获取当前时间的纪元时间格式非常简单,如下例中所示。

  • Linux 终端:date +%s

  • Python:import time; int(time.time())

  • Java:System.currentTimeMillis() / 1000L

  • JavaScript: Math.floor(Date.now() / 1000)

  1. TTLExample 表上启用 TTL。

    aws dynamodb update-time-to-live --table-name TTLExample --time-to-live-specification "Enabled=true, AttributeName=ttl"
  2. TTLExample 表上描述 TTL。

    aws dynamodb describe-time-to-live --table-name TTLExample { "TimeToLiveDescription": { "AttributeName": "ttl", "TimeToLiveStatus": "ENABLED" } }
  3. 通过使用 BASH shell 和 TTLExample 设置生存时间属性将项目添加至 AWS CLI 表。

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

此示例从当前日期开始,并在当前日期上增加 5 天来创建过期时间。然后,它将过期时间转换为纪元时间格式,以便最终添加项目到“TTLExample”表。

注意

为生存时间设置过期值的一种方式是计算添加到过期时间的秒数。例如,5 天是 432000 秒。但是,人们通常习惯于从某个日期算起。

获取当前时间的纪元时间格式非常简单,如下例中所示。

  • Linux 终端:date +%s

  • Python:import time; int(time.time())

  • Java:System.currentTimeMillis() / 1000L

  • JavaScript: Math.floor(Date.now() / 1000)