Update a DynamoDB item with a TTL using an Amazon SDK - Amazon DynamoDB
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Update a DynamoDB item with a TTL using an Amazon SDK

The following code examples show how to update an item's TTL.

Java
SDK for Java 2.x

Update TTL on an existing DynamoDB item in a table.

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);
  • For API details, see UpdateItem in Amazon SDK for Java 2.x API Reference.

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');
  • For API details, see UpdateItem in Amazon SDK for JavaScript API Reference.

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')
  • For API details, see UpdateItem in Amazon SDK for Python (Boto3) API Reference.

For a complete list of Amazon SDK developer guides and code examples, see Using DynamoDB with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.