만료된 항목 작업 - Amazon DynamoDB

만료된 항목 작업

삭제 보류 중인 만료된 항목은 읽기 및 쓰기 작업에서 필터링할 수 있습니다. 이는 만료된 데이터가 더 이상 유효하지 않아 사용해서는 안 되는 시나리오에서 유용합니다. 필터링되지 않은 경우 백그라운드 프로세스에서 삭제될 때까지 읽기 및 쓰기 작업에 계속 표시됩니다.

참고

이러한 항목은 삭제되기 전까지는 여전히 스토리지 및 읽기 비용에 포함됩니다.

TTL 삭제는 DynamoDB Streams에서 식별할 수 있지만 삭제가 발생한 리전에서만 식별할 수 있습니다. 글로벌 테이블 리전에 복제된 TTL 삭제는 삭제가 복제되는 리전의 DynamoDB 스트림에서 식별할 수 없습니다.

읽기 작업에서 만료된 항목 필터링

스캔쿼리와 같은 읽기 작업의 경우 필터 표현식을 사용하여 삭제 보류 중인 만료된 항목을 필터링할 수 있습니다. 아래 코드 스니펫에서 볼 수 있듯이 필터 표현식은 TTL 시간이 현재 시간과 같거나 그보다 전인 항목을 필터링할 수 있습니다. 이 작업은 현재 시간을 변수(now)로 가져오는 대입문을 통해 수행되며, 이 대입문은 epoch 시간 형식의 int로 변환됩니다.

Python
import boto3 from datetime import datetime def query_dynamodb_items(table_name, partition_key): """ :param table_name: Name of the DynamoDB table :param partition_key: :return: """ try: # Initialize a DynamoDB resource dynamodb = boto3.resource('dynamodb', region_name='us-east-1') # Specify your table table = dynamodb.Table(table_name) # Get the current time in epoch format current_time = int(datetime.now().timestamp()) # Perform the query operation with a filter expression to exclude expired items # response = table.query( # KeyConditionExpression=boto3.dynamodb.conditions.Key('partitionKey').eq(partition_key), # FilterExpression=boto3.dynamodb.conditions.Attr('expireAt').gt(current_time) # ) response = table.query( KeyConditionExpression=dynamodb.conditions.Key('partitionKey').eq(partition_key), FilterExpression=dynamodb.conditions.Attr('expireAt').gt(current_time) ) # Print the items that are not expired for item in response['Items']: print(item) except Exception as e: print(f"Error querying items: {e}") # Call the function with your values query_dynamodb_items('Music', 'your-partition-key-value')

업데이트 작업의 출력은 createdAt 시간은 변경되지 않았지만 updatedAtexpireAt 시간은 업데이트되었음을 보여줍니다. 이제 expireAt 시간은 마지막 업데이트 시점인 2023년 10월 19일 목요일 오후 1:27:15로부터 90일로 설정되었습니다.

partition_key createdAt updatedAt expireAt attribute_1 attribute_2

some_value

2023-07-17 14:11:05.322323 2023-07-19 13:27:15.213423 1697722035 새 값 some_value
Javascript
import { DynamoDBClient, QueryCommand } from "@aws-sdk/client-dynamodb"; import { marshall, unmarshall } from "@aws-sdk/util-dynamodb"; async function queryDynamoDBItems(tableName, region, primaryKey) { const client = new DynamoDBClient({ region: region, endpoint: `https://dynamodb.${region}.amazonaws.com` }); const currentTime = Math.floor(Date.now() / 1000); const params = { TableName: tableName, KeyConditionExpression: "#pk = :pk", FilterExpression: "#ea > :ea", ExpressionAttributeNames: { "#pk": "primaryKey", "#ea": "expireAt" }, ExpressionAttributeValues: marshall({ ":pk": primaryKey, ":ea": currentTime }) }; try { const { Items } = await client.send(new QueryCommand(params)); Items.forEach(item => { console.log(unmarshall(item)) }); return Items; } catch (err) { console.error(`Error querying items: ${err}`); throw err; } } //enter your own values here queryDynamoDBItems('your-table-name', 'your-partition-key-value');

만료된 항목에 조건부 쓰기

조건식을 사용하면 만료된 항목에 대한 쓰기를 방지할 수 있습니다. 아래 코드 스니펫은 만료 시간이 현재 시간보다 큰지를 확인하는 조건부 업데이트입니다. true인 경우 쓰기 작업이 계속됩니다.

Python
import boto3 from datetime import datetime, timedelta from botocore.exceptions import ClientError def update_dynamodb_item(table_name, region, primary_key, sort_key, ttl_attribute): """ Updates an existing record in a DynamoDB table with a new or updated TTL attribute. :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. :param ttl_attribute: name of the TTL attribute in the target DynamoDB table :return: """ try: dynamodb = boto3.resource('dynamodb', region_name=region) table = dynamodb.Table(table_name) # Generate updated TTL in epoch second format updated_expiration_time = int((datetime.now() + timedelta(days=90)).timestamp()) # Define the update expression for adding/updating a new attribute update_expression = "SET newAttribute = :val1" # Define the condition expression for checking if 'ttlExpirationDate' is not expired condition_expression = "ttlExpirationDate > :val2" # Define the expression attribute values expression_attribute_values = { ':val1': ttl_attribute, ':val2': updated_expiration_time } response = table.update_item( Key={ 'primaryKey': primary_key, 'sortKey': sort_key }, UpdateExpression=update_expression, ConditionExpression=condition_expression, ExpressionAttributeValues=expression_attribute_values ) print("Item updated successfully.") return response['ResponseMetadata']['HTTPStatusCode'] # Ideally a 200 OK except ClientError as e: if e.response['Error']['Code'] == "ConditionalCheckFailedException": print("Condition check failed: Item's 'ttlExpirationDate' is expired.") else: print(f"Error updating item: {e}") except Exception as e: print(f"Error updating item: {e}") # replace with your values update_dynamodb_item('your-table-name', 'us-east-1', 'your-partition-key-value', 'your-sort-key-value', 'your-ttl-attribute-value')

업데이트 작업의 출력은 createdAt 시간은 변경되지 않았지만 updatedAtexpireAt 시간은 업데이트되었음을 보여줍니다. 이제 expireAt 시간은 마지막 업데이트 시점인 2023년 10월 19일 목요일 오후 1:27:15로부터 90일로 설정되었습니다.

partition_key createdAt updatedAt expireAt attribute_1 attribute_2

some_value

2023-07-17 14:11:05.322323 2023-07-19 13:27:15.213423 1697722035 새 값 some_value
Javascript
import { DynamoDBClient, UpdateItemCommand } from "@aws-sdk/client-dynamodb"; import { marshall, unmarshall } from "@aws-sdk/util-dynamodb"; // Example function to update an item in a DynamoDB table. // The function should take the table name, region, partition key, sort key, and new attribute as arguments. // The function should use the DynamoDB client to update the item. // The function should return the updated item. // The function should handle errors and exceptions. const updateDynamoDBItem = async (tableName, region, partitionKey, sortKey, newAttribute) => { const client = new DynamoDBClient({ region: region, endpoint: `https://dynamodb.${region}.amazonaws.com` }); const currentTime = Math.floor(Date.now() / 1000); const params = { TableName: tableName, Key: marshall({ artist: partitionKey, album: sortKey }), UpdateExpression: "SET newAttribute = :newAttribute", ConditionExpression: "expireAt > :expiration", ExpressionAttributeValues: marshall({ ':newAttribute': newAttribute, ':expiration': currentTime }), ReturnValues: "ALL_NEW" }; try { const response = await client.send(new UpdateItemCommand(params)); const responseData = unmarshall(response.Attributes); console.log("Item updated successfully: ", responseData); return responseData; } catch (error) { if (error.name === "ConditionalCheckFailedException") { console.log("Condition check failed: Item's 'expireAt' is expired."); } else { console.error("Error updating item: ", error); } throw error; } }; // Enter your values here updateDynamoDBItem('your-table-name', "us-east-1",'your-partition-key-value', 'your-sort-key-value', 'your-new-attribute-value');

DynamoDB Streams에서 삭제된 항목 식별

스트림 레코드에는 사용자 ID 필드 Records[<index>].userIdentity가 포함되어 있습니다. TTL 프로세스에 의해 삭제된 항목은 다음 필드를 갖습니다.

Records[<index>].userIdentity.type "Service" Records[<index>].userIdentity.principalId "dynamodb.amazonaws.com"

다음 JSON은 단일 스트림 레코드의 해당 부분을 보여줍니다.

"Records": [ { ... "userIdentity": { "type": "Service", "principalId": "dynamodb.amazonaws.com" } ... } ]