AWS SDK를 사용하여 TTL이 포함된 DynamoDB 항목 업데이트 - Amazon DynamoDB

AWS SDK를 사용하여 TTL이 포함된 DynamoDB 항목 업데이트

다음 코드 예제에서는 항목의 TTL을 업데이트하는 방법을 보여줍니다.

Java
SDK for Java 2.x

테이블의 기존 DynamoDB 항목에서 TTL을 업데이트합니다.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; import software.amazon.awssdk.utils.ImmutableMap; import java.util.Map; import java.util.Optional; // Get current time in epoch second format final long currentTime = System.currentTimeMillis() / 1000; // Calculate expiration time 90 days from now in epoch second format final long expireDate = currentTime + (90 * 24 * 60 * 60); // An expression that defines one or more attributes to be updated, the action to be performed on them, and new values for them. final String updateExpression = "SET updatedAt=:c, expireAt=:e"; final ImmutableMap<String, AttributeValue> keyMap = ImmutableMap.of("primaryKey", AttributeValue.fromS(primaryKey), "sortKey", AttributeValue.fromS(sortKey)); final Map<String, AttributeValue> expressionAttributeValues = ImmutableMap.of( ":c", AttributeValue.builder().s(String.valueOf(currentTime)).build(), ":e", AttributeValue.builder().s(String.valueOf(expireDate)).build() ); final UpdateItemRequest request = UpdateItemRequest.builder() .tableName(tableName) .key(keyMap) .updateExpression(updateExpression) .expressionAttributeValues(expressionAttributeValues) .build(); try (DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build()) { final UpdateItemResponse response = ddb.updateItem(request); System.out.println(tableName + " UpdateItem operation with TTL successful. Request id is " + response.responseMetadata().requestId()); } catch (ResourceNotFoundException e) { System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName); System.exit(1); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.exit(0);
  • API 세부 정보는 AWS SDK for Java 2.x API 참조UpdateItem을 참조하십시오.

JavaScript
SDK for JavaScript (v3)
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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); 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');
  • API 세부 정보는 AWS SDK for JavaScript API 참조UpdateItem을 참조하십시오.

Python
SDK for Python(Boto3)
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 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')
  • API 세부 정보는 AWS SDK for Python (Boto3) API 참조UpdateItem를 참조하십시오.

AWS SDK 개발자 가이드 및 코드 예시의 전체 목록은 AWS SDK와 함께 DynamoDB 사용 단원을 참조하세요. 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.