计算生存时间 (TTL) - Amazon DynamoDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

计算生存时间 (TTL)

实现 TTL 的常用方法是根据项目的创建时间或上次更新时间为其设置过期时间。这可以通过在createdAt和时间updatedAt戳中添加时间来完成。例如,可以将新创建项目的 TTL 设置为 createdAt + 90 天。商品更新后,TTL 可以重新计算为 + 90 天。updatedAt

计算出的到期时间必须采用 epoch 格式,以秒为单位。要考虑过期和删除,TTL 不能超过过去五年。如果您使用任何其他格式,TTL 进程将忽略该项目。如果您将过期日期设置为将来的某个时候您希望商品过期,则该商品将在该时间之后过期。例如,假设您将到期日期设置为 1724241326(即 2024 年 8 月 21 日星期一 11:55:26(格林威治标准时间))。该物品将在指定时间后过期。

创建物品并设置存活时间

以下示例演示了如何使用作expireAt为 TTL 属性名称来计算创建新项目时的过期时间。赋值语句以变量形式获取当前时间。在示例中,过期时间计算为从当前时间算起 90 天。然后将时间转换为纪元格式,并在 TTL 属性中保存为整数数据类型。

Python
import boto3 from datetime import datetime, timedelta def create_dynamodb_item(table_name, region, primary_key, sort_key): """ Creates a DynamoDB item with an attached expiry attribute. :param table_name: Table name for the boto3 resource to target when creating an item :param region: string representing the AWS region. Example: `us-east-1` :param primary_key: one attribute known as the partition key. :param sort_key: Also known as a range attribute. :return: Void (nothing) """ try: dynamodb = boto3.resource('dynamodb', region_name=region) table = dynamodb.Table(table_name) # Get the current time in epoch second format current_time = int(datetime.now().timestamp()) # Calculate the expiration time (90 days from now) in epoch second format expiration_time = int((datetime.now() + timedelta(days=90)).timestamp()) item = { 'primaryKey': primary_key, 'sortKey': sort_key, 'creationDate': current_time, 'expirationDate': expiration_time } table.put_item(Item=item) print("Item created successfully.") except Exception as e: print(f"Error creating item: {e}") raise # Use your own values create_dynamodb_item('your-table-name', 'us-west-2', 'your-partition-key-value', 'your-sort-key-value')
Javascript

在此请求中,我们添加了计算新创建项目的过期时间的逻辑:

import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb"; function createDynamoDBItem(table_name, region, partition_key, sort_key) { const client = new DynamoDBClient({ region: region, endpoint: `https://dynamodb.${region}.amazonaws.com` }); // Get the current time in epoch second format const current_time = Math.floor(new Date().getTime() / 1000); // Calculate the expireAt time (90 days from now) in epoch second format const expire_at = Math.floor((new Date().getTime() + 90 * 24 * 60 * 60 * 1000) / 1000); // Create DynamoDB item const item = { 'partitionKey': {'S': partition_key}, 'sortKey': {'S': sort_key}, 'createdAt': {'N': current_time.toString()}, 'expireAt': {'N': expire_at.toString()} }; const putItemCommand = new PutItemCommand({ TableName: table_name, Item: item, ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, }); client.send(putItemCommand, function(err, data) { if (err) { console.log("Exception encountered when creating item %s, here's what happened: ", data, ex); throw err; } else { console.log("Item created successfully: %s.", data); return data; } }); } // use your own values createDynamoDBItem('your-table-name', 'us-east-1', 'your-partition-key-value', 'your-sort-key-value');

更新物品并刷新生存时间

此示例是上一节示例的延续。如果更新了项目,则可以重新计算过期时间。以下示例将expireAt时间戳重新计算为从当前时间算起 90 天。

Python
import boto3 from datetime import datetime, timedelta def update_dynamodb_item(table_name, region, primary_key, sort_key): """ Update an existing DynamoDB item with a TTL. :param table_name: Name of the DynamoDB table :param region: AWS Region of the table - example `us-east-1` :param primary_key: one attribute known as the partition key. :param sort_key: Also known as a range attribute. :return: Void (nothing) """ try: # Create the DynamoDB resource. dynamodb = boto3.resource('dynamodb', region_name=region) table = dynamodb.Table(table_name) # Get the current time in epoch second format current_time = int(datetime.now().timestamp()) # Calculate the expireAt time (90 days from now) in epoch second format expire_at = int((datetime.now() + timedelta(days=90)).timestamp()) table.update_item( Key={ 'partitionKey': primary_key, 'sortKey': sort_key }, UpdateExpression="set updatedAt=:c, expireAt=:e", ExpressionAttributeValues={ ':c': current_time, ':e': expire_at }, ) print("Item updated successfully.") except Exception as e: print(f"Error updating item: {e}") # Replace with your own values update_dynamodb_item('your-table-name', 'us-west-2', 'your-partition-key-value', 'your-sort-key-value')

更新操作的输出显示,虽然createdAt时间不变,但updatedAtexpireAt时间已更新。现在,expireAt时间设置为自上次更新时间(即2023年10月19日星期四下午 1:27:15)起的90天。

partition_key createdAt updatedAt expireAT 属性_1 属性_2

一些值

2023-07-17 14:11:05.322 323 2023-07-19 13:27:15.213 423 1697722035 new_value 一些值
Javascript
import { DynamoDBClient, UpdateItemCommand } from "@aws-sdk/client-dynamodb"; import { marshall, unmarshall } from "@aws-sdk/util-dynamodb"; async function updateDynamoDBItem(tableName, region, partitionKey, sortKey) { const client = new DynamoDBClient({ region: region, endpoint: `https://dynamodb.${region}.amazonaws.com` }); const currentTime = Math.floor(Date.now() / 1000); const expireAt = Math.floor((Date.now() + 90 * 24 * 60 * 60 * 1000) / 1000); ////is there a better way to do this? const params = { TableName: tableName, Key: marshall({ partitionKey: partitionKey, sortKey: sortKey }), UpdateExpression: "SET updatedAt = :c, expireAt = :e", ExpressionAttributeValues: marshall({ ":c": currentTime, ":e": expireAt }), }; try { const data = await client.send(new UpdateItemCommand(params)); const responseData = unmarshall(data.Attributes); console.log("Item updated successfully: %s", responseData); return responseData; } catch (err) { console.error("Error updating item:", err); throw err; } } //enter your values here updateDynamoDBItem('your-table-name', 'us-east-1', 'your-partition-key-value', 'your-sort-key-value');

本简介中讨论的 TTL 示例演示了一种确保表格中仅保留最近更新的项目的方法。更新的项目会延长其使用寿命,而未更新的项目将在创建后过期并免费删除,从而减少存储空间并保持表格整洁。