搭UpdateTimeToLive配 AWS 開發套件或 CLI 使用 - Amazon DynamoDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

UpdateTimeToLive配 AWS 開發套件或 CLI 使用

下列程式碼範例會示範如何使用UpdateTimeToLive

CLI
AWS CLI

更新表格上的「即時時間」設定的步驟

下列update-time-to-live範例會啟用指定資料表上的存留時間。

aws dynamodb update-time-to-live \ --table-name MusicCollection \ --time-to-live-specification Enabled=true,AttributeName=ttl

輸出:

{ "TimeToLiveSpecification": { "Enabled": true, "AttributeName": "ttl" } }

如需詳細資訊,請參閱 Amazon DynamoDB 開發人員指南中的存留時間。

  • 如需 API 詳細資訊,請參閱AWS CLI 命令參考UpdateTimeToLive中的。

Java
適用於 Java 2.x 的 SDK

在現有 DynamoDB 資料表上啟用 TTL。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.services.dynamodb.model.TimeToLiveSpecification; import software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveRequest; import software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveResponse; import java.util.Optional; final TimeToLiveSpecification ttlSpecification = TimeToLiveSpecification.builder() .attributeName(ttlAttributeName) .enabled(true) .build(); final UpdateTimeToLiveRequest request = UpdateTimeToLiveRequest.builder() .tableName(tableName) .timeToLiveSpecification(ttlSpecification) .build(); try (DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build()) { final UpdateTimeToLiveResponse response = ddb.updateTimeToLive(request); System.out.println(tableName + " had its TTL successfully updated. The 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.out.println("Done!");

停用現有動態資料表上的 TTL。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.services.dynamodb.model.TimeToLiveSpecification; import software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveRequest; import software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveResponse; import java.util.Optional; final Region region = Optional.ofNullable(args[2]).isEmpty() ? Region.US_EAST_1 : Region.of(args[2]); final TimeToLiveSpecification ttlSpecification = TimeToLiveSpecification.builder() .attributeName(ttlAttributeName) .enabled(false) .build(); final UpdateTimeToLiveRequest request = UpdateTimeToLiveRequest.builder() .tableName(tableName) .timeToLiveSpecification(ttlSpecification) .build(); try (DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build()) { final UpdateTimeToLiveResponse response = ddb.updateTimeToLive(request); System.out.println(tableName + " had its TTL successfully updated. The 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.out.println("Done!");
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考UpdateTimeToLive中的。

JavaScript
適用於 JavaScript (v3) 的開發套件

在現有 DynamoDB 資料表上啟用 TTL。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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');

停用現有動態資料表上的 TTL。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { DynamoDBClient, UpdateTimeToLiveCommand } from "@aws-sdk/client-dynamodb"; const disableTTL = async (tableName, ttlAttribute) => { const client = new DynamoDBClient({}); const params = { TableName: tableName, TimeToLiveSpecification: { Enabled: false, AttributeName: ttlAttribute } }; try { const response = await client.send(new UpdateTimeToLiveCommand(params)); if (response.$metadata.httpStatusCode === 200) { console.log(`TTL disabled successfully for table ${tableName}, using attribute name ${ttlAttribute}.`); } else { console.log(`Failed to disable TTL for table ${tableName}, response object: ${response}`); } return response; } catch (e) { console.error(`Error disabling TTL: ${e}`); throw e; } }; // call with your own values disableTTL('ExampleTable', 'exampleTtlAttribute');
  • 如需 API 詳細資訊,請參閱 AWS SDK for JavaScript API 參考UpdateTimeToLive中的。

Python
適用於 Python (Boto3) 的 SDK

在現有 DynamoDB 資料表上啟用 TTL。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 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']}") return response 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', 'expireAt')

停用現有動態資料表上的 TTL。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import boto3 def disable_ttl(table_name, ttl_attribute_name): """ Disables 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 being modified :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': False, 'AttributeName': ttl_attribute_name } ) # In the returned response, check for a successful status code. if response['ResponseMetadata']['HTTPStatusCode'] == 200: print("TTL has been disabled successfully.") else: print(f"Failed to disable TTL, status code {response['ResponseMetadata']['HTTPStatusCode']}") except Exception as ex: print("Couldn't disable TTL in table %s. Here's why: %s" % (table_name, ex)) raise # your values disable_ttl('your-table-name', 'expireAt')
  • 如需 API 的詳細資訊,請參閱AWS 開發套件UpdateTimeToLive中的 Python (博托 3) API 參考。

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱搭配開發套件使用 DynamoDB AWS。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。