使用 SDK for Java 2.x 的 DynamoDB 示例 - Amazon SDK for Java 2.x
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

使用 SDK for Java 2.x 的 DynamoDB 示例

以下代码示例向您展示了如何在 DynamoDB 中使用来执行操作和实现常见场景。 Amazon SDK for Java 2.x

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景是展示如何通过在同一服务中调用多个函数来完成特定任务任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

开始使用

以下代码示例演示了如何开始使用 DynamoDB。

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

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.ListTablesRequest; import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListTables { public static void main(String[] args) { System.out.println("Listing your Amazon DynamoDB tables:\n"); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); listAllTables(ddb); ddb.close(); } public static void listAllTables(DynamoDbClient ddb) { boolean moreTables = true; String lastName = null; while (moreTables) { try { ListTablesResponse response = null; if (lastName == null) { ListTablesRequest request = ListTablesRequest.builder().build(); response = ddb.listTables(request); } else { ListTablesRequest request = ListTablesRequest.builder() .exclusiveStartTableName(lastName).build(); response = ddb.listTables(request); } List<String> tableNames = response.tableNames(); if (tableNames.size() > 0) { for (String curName : tableNames) { System.out.format("* %s\n", curName); } } else { System.out.println("No tables found!"); System.exit(0); } lastName = response.lastEvaluatedTableName(); if (lastName == null) { moreTables = false; } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } System.out.println("\nDone!"); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考ListTables中的。

操作

以下代码示例演示如何使用 BatchGetItem

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

展示如何使用服务客户端获取批量项目。

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.BatchGetItemRequest; import software.amazon.awssdk.services.dynamodb.model.BatchGetItemResponse; import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Before running this Java V2 code example, set up your development environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class BatchReadItems { public static void main(String[] args){ final String usage = """ Usage: <tableName> Where: tableName - The Amazon DynamoDB table (for example, Music).\s """; String tableName = "Music"; Region region = Region.US_EAST_1; DynamoDbClient dynamoDbClient = DynamoDbClient.builder() .region(region) .build(); getBatchItems(dynamoDbClient, tableName); } public static void getBatchItems(DynamoDbClient dynamoDbClient, String tableName) { // Define the primary key values for the items you want to retrieve. Map<String, AttributeValue> key1 = new HashMap<>(); key1.put("Artist", AttributeValue.builder().s("Artist1").build()); Map<String, AttributeValue> key2 = new HashMap<>(); key2.put("Artist", AttributeValue.builder().s("Artist2").build()); // Construct the batchGetItem request. Map<String, KeysAndAttributes> requestItems = new HashMap<>(); requestItems.put(tableName, KeysAndAttributes.builder() .keys(List.of(key1, key2)) .projectionExpression("Artist, SongTitle") .build()); BatchGetItemRequest batchGetItemRequest = BatchGetItemRequest.builder() .requestItems(requestItems) .build(); // Make the batchGetItem request. BatchGetItemResponse batchGetItemResponse = dynamoDbClient.batchGetItem(batchGetItemRequest); // Extract and print the retrieved items. Map<String, List<Map<String, AttributeValue>>> responses = batchGetItemResponse.responses(); if (responses.containsKey(tableName)) { List<Map<String, AttributeValue>> musicItems = responses.get(tableName); for (Map<String, AttributeValue> item : musicItems) { System.out.println("Artist: " + item.get("Artist").s() + ", SongTitle: " + item.get("SongTitle").s()); } } else { System.out.println("No items retrieved."); } } }

展示如何使用服务客户端和分页工具获取批量项目。

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.BatchGetItemRequest; import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class BatchGetItemsPaginator { public static void main(String[] args){ final String usage = """ Usage: <tableName> Where: tableName - The Amazon DynamoDB table (for example, Music).\s """; String tableName = "Music"; Region region = Region.US_EAST_1; DynamoDbClient dynamoDbClient = DynamoDbClient.builder() .region(region) .build(); getBatchItemsPaginator(dynamoDbClient, tableName) ; } public static void getBatchItemsPaginator(DynamoDbClient dynamoDbClient, String tableName) { // Define the primary key values for the items you want to retrieve. Map<String, AttributeValue> key1 = new HashMap<>(); key1.put("Artist", AttributeValue.builder().s("Artist1").build()); Map<String, AttributeValue> key2 = new HashMap<>(); key2.put("Artist", AttributeValue.builder().s("Artist2").build()); // Construct the batchGetItem request. Map<String, KeysAndAttributes> requestItems = new HashMap<>(); requestItems.put(tableName, KeysAndAttributes.builder() .keys(List.of(key1, key2)) .projectionExpression("Artist, SongTitle") .build()); BatchGetItemRequest batchGetItemRequest = BatchGetItemRequest.builder() .requestItems(requestItems) .build(); // Use batchGetItemPaginator for paginated requests. dynamoDbClient.batchGetItemPaginator(batchGetItemRequest).stream() .flatMap(response -> response.responses().getOrDefault(tableName, Collections.emptyList()).stream()) .forEach(item -> { System.out.println("Artist: " + item.get("Artist").s() + ", SongTitle: " + item.get("SongTitle").s()); }); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考BatchGetItem中的。

以下代码示例演示如何使用 BatchWriteItem

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

使用服务客户端将许多项目插入到表中。

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.BatchWriteItemRequest; import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.PutRequest; import software.amazon.awssdk.services.dynamodb.model.WriteRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Before running this Java V2 code example, set up your development environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class BatchWriteItems { public static void main(String[] args){ final String usage = """ Usage: <tableName> Where: tableName - The Amazon DynamoDB table (for example, Music).\s """; String tableName = "Music"; Region region = Region.US_EAST_1; DynamoDbClient dynamoDbClient = DynamoDbClient.builder() .region(region) .build(); addBatchItems(dynamoDbClient, tableName); } public static void addBatchItems(DynamoDbClient dynamoDbClient, String tableName) { // Specify the updates you want to perform. List<WriteRequest> writeRequests = new ArrayList<>(); // Set item 1. Map<String, AttributeValue> item1Attributes = new HashMap<>(); item1Attributes.put("Artist", AttributeValue.builder().s("Artist1").build()); item1Attributes.put("Rating", AttributeValue.builder().s("5").build()); item1Attributes.put("Comments", AttributeValue.builder().s("Great song!").build()); item1Attributes.put("SongTitle", AttributeValue.builder().s("SongTitle1").build()); writeRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item1Attributes).build()).build()); // Set item 2. Map<String, AttributeValue> item2Attributes = new HashMap<>(); item2Attributes.put("Artist", AttributeValue.builder().s("Artist2").build()); item2Attributes.put("Rating", AttributeValue.builder().s("4").build()); item2Attributes.put("Comments", AttributeValue.builder().s("Nice melody.").build()); item2Attributes.put("SongTitle", AttributeValue.builder().s("SongTitle2").build()); writeRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item2Attributes).build()).build()); try { // Create the BatchWriteItemRequest. BatchWriteItemRequest batchWriteItemRequest = BatchWriteItemRequest.builder() .requestItems(Map.of(tableName, writeRequests)) .build(); // Execute the BatchWriteItem operation. BatchWriteItemResponse batchWriteItemResponse = dynamoDbClient.batchWriteItem(batchWriteItemRequest); // Process the response. System.out.println("Batch write successful: " + batchWriteItemResponse); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } }

使用增强型客户端将许多项目插入到表中。

import com.example.dynamodb.Customer; import com.example.dynamodb.Music; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.WriteBatch; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneOffset; /* * Before running this code example, create an Amazon DynamoDB table named Customer with these columns: * - id - the id of the record that is the key * - custName - the customer name * - email - the email value * - registrationDate - an instant value when the item was added to the table * * Also, ensure that you have set up your development environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class EnhancedBatchWriteItems { public static void main(String[] args) { Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); putBatchRecords(enhancedClient); ddb.close(); } public static void putBatchRecords(DynamoDbEnhancedClient enhancedClient) { try { DynamoDbTable<Customer> customerMappedTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); DynamoDbTable<Music> musicMappedTable = enhancedClient.table("Music", TableSchema.fromBean(Music.class)); LocalDate localDate = LocalDate.parse("2020-04-07"); LocalDateTime localDateTime = localDate.atStartOfDay(); Instant instant = localDateTime.toInstant(ZoneOffset.UTC); Customer record2 = new Customer(); record2.setCustName("Fred Pink"); record2.setId("id110"); record2.setEmail("fredp@noserver.com"); record2.setRegistrationDate(instant); Customer record3 = new Customer(); record3.setCustName("Susan Pink"); record3.setId("id120"); record3.setEmail("spink@noserver.com"); record3.setRegistrationDate(instant); Customer record4 = new Customer(); record4.setCustName("Jerry orange"); record4.setId("id101"); record4.setEmail("jorange@noserver.com"); record4.setRegistrationDate(instant); BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest = BatchWriteItemEnhancedRequest .builder() .writeBatches( WriteBatch.builder(Customer.class) // add items to the Customer // table .mappedTableResource(customerMappedTable) .addPutItem(builder -> builder.item(record2)) .addPutItem(builder -> builder.item(record3)) .addPutItem(builder -> builder.item(record4)) .build(), WriteBatch.builder(Music.class) // delete an item from the Music // table .mappedTableResource(musicMappedTable) .addDeleteItem(builder -> builder.key( Key.builder().partitionValue( "Famous Band") .build())) .build()) .build(); // Add three items to the Customer table and delete one item from the Music // table. enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest); System.out.println("done"); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考BatchWriteItem中的。

以下代码示例演示如何使用 CreateTable

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateTable { public static void main(String[] args) { final String usage = """ Usage: <tableName> <key> Where: tableName - The Amazon DynamoDB table to create (for example, Music3). key - The key for the Amazon DynamoDB table (for example, Artist). """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String tableName = args[0]; String key = args[1]; System.out.println("Creating an Amazon DynamoDB table " + tableName + " with a simple primary key: " + key); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); String result = createTable(ddb, tableName, key); System.out.println("New table is " + result); ddb.close(); } public static String createTable(DynamoDbClient ddb, String tableName, String key) { DynamoDbWaiter dbWaiter = ddb.waiter(); CreateTableRequest request = CreateTableRequest.builder() .attributeDefinitions(AttributeDefinition.builder() .attributeName(key) .attributeType(ScalarAttributeType.S) .build()) .keySchema(KeySchemaElement.builder() .attributeName(key) .keyType(KeyType.HASH) .build()) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(10L) .writeCapacityUnits(10L) .build()) .tableName(tableName) .build(); String newTable; try { CreateTableResponse response = ddb.createTable(request); DescribeTableRequest tableRequest = DescribeTableRequest.builder() .tableName(tableName) .build(); // Wait until the Amazon DynamoDB table is created. WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); waiterResponse.matched().response().ifPresent(System.out::println); newTable = response.tableDescription().tableName(); return newTable; } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } return ""; } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考CreateTable中的。

以下代码示例演示如何使用 DeleteItem

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

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.DeleteItemRequest; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import java.util.HashMap; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteItem { public static void main(String[] args) { final String usage = """ Usage: <tableName> <key> <keyval> Where: tableName - The Amazon DynamoDB table to delete the item from (for example, Music3). key - The key used in the Amazon DynamoDB table (for example, Artist).\s keyval - The key value that represents the item to delete (for example, Famous Band). """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String tableName = args[0]; String key = args[1]; String keyVal = args[2]; System.out.format("Deleting item \"%s\" from %s\n", keyVal, tableName); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); deleteDynamoDBItem(ddb, tableName, key, keyVal); ddb.close(); } public static void deleteDynamoDBItem(DynamoDbClient ddb, String tableName, String key, String keyVal) { HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put(key, AttributeValue.builder() .s(keyVal) .build()); DeleteItemRequest deleteReq = DeleteItemRequest.builder() .tableName(tableName) .key(keyToGet) .build(); try { ddb.deleteItem(deleteReq); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考DeleteItem中的。

以下代码示例演示如何使用 DeleteTable

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteTable { public static void main(String[] args) { final String usage = """ Usage: <tableName> Where: tableName - The Amazon DynamoDB table to delete (for example, Music3). **Warning** This program will delete the table that you specify! """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String tableName = args[0]; System.out.format("Deleting the Amazon DynamoDB table %s...\n", tableName); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); deleteDynamoDBTable(ddb, tableName); ddb.close(); } public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { DeleteTableRequest request = DeleteTableRequest.builder() .tableName(tableName) .build(); try { ddb.deleteTable(request); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println(tableName + " was successfully deleted!"); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考DeleteTable中的。

以下代码示例演示如何使用 DescribeTable

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription; import software.amazon.awssdk.services.dynamodb.model.TableDescription; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DescribeTable { public static void main(String[] args) { final String usage = """ Usage: <tableName> Where: tableName - The Amazon DynamoDB table to get information about (for example, Music3). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String tableName = args[0]; System.out.format("Getting description for %s\n\n", tableName); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); describeDymamoDBTable(ddb, tableName); ddb.close(); } public static void describeDymamoDBTable(DynamoDbClient ddb, String tableName) { DescribeTableRequest request = DescribeTableRequest.builder() .tableName(tableName) .build(); try { TableDescription tableInfo = ddb.describeTable(request).table(); if (tableInfo != null) { System.out.format("Table name : %s\n", tableInfo.tableName()); System.out.format("Table ARN : %s\n", tableInfo.tableArn()); System.out.format("Status : %s\n", tableInfo.tableStatus()); System.out.format("Item count : %d\n", tableInfo.itemCount()); System.out.format("Size (bytes): %d\n", tableInfo.tableSizeBytes()); ProvisionedThroughputDescription throughputInfo = tableInfo.provisionedThroughput(); System.out.println("Throughput"); System.out.format(" Read Capacity : %d\n", throughputInfo.readCapacityUnits()); System.out.format(" Write Capacity: %d\n", throughputInfo.writeCapacityUnits()); List<AttributeDefinition> attributes = tableInfo.attributeDefinitions(); System.out.println("Attributes"); for (AttributeDefinition a : attributes) { System.out.format(" %s (%s)\n", a.attributeName(), a.attributeType()); } } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("\nDone!"); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考DescribeTable中的。

以下代码示例演示如何使用 DescribeTimeToLive

适用于 Java 的 SDK 2.x

描述现有 DynamoDB 表中的 TTL 配置。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DescribeTimeToLiveRequest; import software.amazon.awssdk.services.dynamodb.model.DescribeTimeToLiveResponse; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import java.util.Optional; final DescribeTimeToLiveRequest request = DescribeTimeToLiveRequest.builder() .tableName(tableName) .build(); try (DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build()) { final DescribeTimeToLiveResponse response = ddb.describeTimeToLive(request); System.out.println(tableName + " description of time to live is " + response.toString()); } 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 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考DescribeTimeToLive中的。

以下代码示例演示如何使用 GetItem

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

使用从表中获取项目 DynamoDbClient。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * To get an item from an Amazon DynamoDB table using the AWS SDK for Java V2, * its better practice to use the * Enhanced Client, see the EnhancedGetItem example. */ public class GetItem { public static void main(String[] args) { final String usage = """ Usage: <tableName> <key> <keyVal> Where: tableName - The Amazon DynamoDB table from which an item is retrieved (for example, Music3).\s key - The key used in the Amazon DynamoDB table (for example, Artist).\s keyval - The key value that represents the item to get (for example, Famous Band). """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String tableName = args[0]; String key = args[1]; String keyVal = args[2]; System.out.format("Retrieving item \"%s\" from \"%s\"\n", keyVal, tableName); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); getDynamoDBItem(ddb, tableName, key, keyVal); ddb.close(); } public static void getDynamoDBItem(DynamoDbClient ddb, String tableName, String key, String keyVal) { HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put(key, AttributeValue.builder() .s(keyVal) .build()); GetItemRequest request = GetItemRequest.builder() .key(keyToGet) .tableName(tableName) .build(); try { // If there is no matching item, GetItem does not return any data. Map<String, AttributeValue> returnedItem = ddb.getItem(request).item(); if (returnedItem.isEmpty()) System.out.format("No item found with the key %s!\n", key); else { Set<String> keys = returnedItem.keySet(); System.out.println("Amazon DynamoDB table attributes: \n"); for (String key1 : keys) { System.out.format("%s: %s\n", key1, returnedItem.get(key1).toString()); } } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考GetItem中的。

以下代码示例演示如何使用 ListTables

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

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.ListTablesRequest; import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListTables { public static void main(String[] args) { System.out.println("Listing your Amazon DynamoDB tables:\n"); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); listAllTables(ddb); ddb.close(); } public static void listAllTables(DynamoDbClient ddb) { boolean moreTables = true; String lastName = null; while (moreTables) { try { ListTablesResponse response = null; if (lastName == null) { ListTablesRequest request = ListTablesRequest.builder().build(); response = ddb.listTables(request); } else { ListTablesRequest request = ListTablesRequest.builder() .exclusiveStartTableName(lastName).build(); response = ddb.listTables(request); } List<String> tableNames = response.tableNames(); if (tableNames.size() > 0) { for (String curName : tableNames) { System.out.format("* %s\n", curName); } } else { System.out.println("No tables found!"); System.exit(0); } lastName = response.lastEvaluatedTableName(); if (lastName == null) { moreTables = false; } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } System.out.println("\nDone!"); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考ListTables中的。

以下代码示例演示如何使用 PutItem

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

使用将项目放入表格中DynamoDbClient

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.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import java.util.HashMap; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * To place items into an Amazon DynamoDB table using the AWS SDK for Java V2, * its better practice to use the * Enhanced Client. See the EnhancedPutItem example. */ public class PutItem { public static void main(String[] args) { final String usage = """ Usage: <tableName> <key> <keyVal> <albumtitle> <albumtitleval> <awards> <awardsval> <Songtitle> <songtitleval> Where: tableName - The Amazon DynamoDB table in which an item is placed (for example, Music3). key - The key used in the Amazon DynamoDB table (for example, Artist). keyval - The key value that represents the item to get (for example, Famous Band). albumTitle - The Album title (for example, AlbumTitle). AlbumTitleValue - The name of the album (for example, Songs About Life ). Awards - The awards column (for example, Awards). AwardVal - The value of the awards (for example, 10). SongTitle - The song title (for example, SongTitle). SongTitleVal - The value of the song title (for example, Happy Day). **Warning** This program will place an item that you specify into a table! """; if (args.length != 9) { System.out.println(usage); System.exit(1); } String tableName = args[0]; String key = args[1]; String keyVal = args[2]; String albumTitle = args[3]; String albumTitleValue = args[4]; String awards = args[5]; String awardVal = args[6]; String songTitle = args[7]; String songTitleVal = args[8]; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); putItemInTable(ddb, tableName, key, keyVal, albumTitle, albumTitleValue, awards, awardVal, songTitle, songTitleVal); System.out.println("Done!"); ddb.close(); } public static void putItemInTable(DynamoDbClient ddb, String tableName, String key, String keyVal, String albumTitle, String albumTitleValue, String awards, String awardVal, String songTitle, String songTitleVal) { HashMap<String, AttributeValue> itemValues = new HashMap<>(); itemValues.put(key, AttributeValue.builder().s(keyVal).build()); itemValues.put(songTitle, AttributeValue.builder().s(songTitleVal).build()); itemValues.put(albumTitle, AttributeValue.builder().s(albumTitleValue).build()); itemValues.put(awards, AttributeValue.builder().s(awardVal).build()); PutItemRequest request = PutItemRequest.builder() .tableName(tableName) .item(itemValues) .build(); try { PutItemResponse response = ddb.putItem(request); System.out.println(tableName + " was 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.err.println("Be sure that it exists and that you've typed its name correctly!"); System.exit(1); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考PutItem中的。

以下代码示例演示如何使用 Query

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

使用查询表DynamoDbClient

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.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; import java.util.HashMap; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * To query items from an Amazon DynamoDB table using the AWS SDK for Java V2, * its better practice to use the * Enhanced Client. See the EnhancedQueryRecords example. */ public class Query { public static void main(String[] args) { final String usage = """ Usage: <tableName> <partitionKeyName> <partitionKeyVal> Where: tableName - The Amazon DynamoDB table to put the item in (for example, Music3). partitionKeyName - The partition key name of the Amazon DynamoDB table (for example, Artist). partitionKeyVal - The value of the partition key that should match (for example, Famous Band). """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String tableName = args[0]; String partitionKeyName = args[1]; String partitionKeyVal = args[2]; // For more information about an alias, see: // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html String partitionAlias = "#a"; System.out.format("Querying %s", tableName); System.out.println(""); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); int count = queryTable(ddb, tableName, partitionKeyName, partitionKeyVal, partitionAlias); System.out.println("There were " + count + " record(s) returned"); ddb.close(); } public static int queryTable(DynamoDbClient ddb, String tableName, String partitionKeyName, String partitionKeyVal, String partitionAlias) { // Set up an alias for the partition key name in case it's a reserved word. HashMap<String, String> attrNameAlias = new HashMap<String, String>(); attrNameAlias.put(partitionAlias, partitionKeyName); // Set up mapping of the partition name with the value. HashMap<String, AttributeValue> attrValues = new HashMap<>(); attrValues.put(":" + partitionKeyName, AttributeValue.builder() .s(partitionKeyVal) .build()); QueryRequest queryReq = QueryRequest.builder() .tableName(tableName) .keyConditionExpression(partitionAlias + " = :" + partitionKeyName) .expressionAttributeNames(attrNameAlias) .expressionAttributeValues(attrValues) .build(); try { QueryResponse response = ddb.query(queryReq); return response.count(); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } return -1; } }

使用 DynamoDbClient 和二级索引查询表。

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.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; import java.util.HashMap; import java.util.Map; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * Create the Movies table by running the Scenario example and loading the Movie * data from the JSON file. Next create a secondary * index for the Movies table that uses only the year column. Name the index * **year-index**. For more information, see: * * https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html */ public class QueryItemsUsingIndex { public static void main(String[] args) { String tableName = "Movies"; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); queryIndex(ddb, tableName); ddb.close(); } public static void queryIndex(DynamoDbClient ddb, String tableName) { try { Map<String, String> expressionAttributesNames = new HashMap<>(); expressionAttributesNames.put("#year", "year"); Map<String, AttributeValue> expressionAttributeValues = new HashMap<>(); expressionAttributeValues.put(":yearValue", AttributeValue.builder().n("2013").build()); QueryRequest request = QueryRequest.builder() .tableName(tableName) .indexName("year-index") .keyConditionExpression("#year = :yearValue") .expressionAttributeNames(expressionAttributesNames) .expressionAttributeValues(expressionAttributeValues) .build(); System.out.println("=== Movie Titles ==="); QueryResponse response = ddb.query(request); response.items() .forEach(movie -> System.out.println(movie.get("title").s())); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 Query

以下代码示例演示如何使用 Scan

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

使用扫描亚马逊 DynamoDB 表。DynamoDbClient

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.ScanRequest; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; import java.util.Map; import java.util.Set; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * To scan items from an Amazon DynamoDB table using the AWS SDK for Java V2, * its better practice to use the * Enhanced Client, See the EnhancedScanRecords example. */ public class DynamoDBScanItems { public static void main(String[] args) { final String usage = """ Usage: <tableName> Where: tableName - The Amazon DynamoDB table to get information from (for example, Music3). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String tableName = args[0]; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); scanItems(ddb, tableName); ddb.close(); } public static void scanItems(DynamoDbClient ddb, String tableName) { try { ScanRequest scanRequest = ScanRequest.builder() .tableName(tableName) .build(); ScanResponse response = ddb.scan(scanRequest); for (Map<String, AttributeValue> item : response.items()) { Set<String> keys = item.keySet(); for (String key : keys) { System.out.println("The key name is " + key + "\n"); System.out.println("The value is " + item.get(key).s()); } } } catch (DynamoDbException e) { e.printStackTrace(); System.exit(1); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 Scan

以下代码示例演示如何使用 UpdateItem

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

使用更新表中的项目DynamoDbClient

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.AttributeAction; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import java.util.HashMap; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * To update an Amazon DynamoDB table using the AWS SDK for Java V2, its better * practice to use the * Enhanced Client, See the EnhancedModifyItem example. */ public class UpdateItem { public static void main(String[] args) { final String usage = """ Usage: <tableName> <key> <keyVal> <name> <updateVal> Where: tableName - The Amazon DynamoDB table (for example, Music3). key - The name of the key in the table (for example, Artist). keyVal - The value of the key (for example, Famous Band). name - The name of the column where the value is updated (for example, Awards). updateVal - The value used to update an item (for example, 14). Example: UpdateItem Music3 Artist Famous Band Awards 14 """; if (args.length != 5) { System.out.println(usage); System.exit(1); } String tableName = args[0]; String key = args[1]; String keyVal = args[2]; String name = args[3]; String updateVal = args[4]; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); updateTableItem(ddb, tableName, key, keyVal, name, updateVal); ddb.close(); } public static void updateTableItem(DynamoDbClient ddb, String tableName, String key, String keyVal, String name, String updateVal) { HashMap<String, AttributeValue> itemKey = new HashMap<>(); itemKey.put(key, AttributeValue.builder() .s(keyVal) .build()); HashMap<String, AttributeValueUpdate> updatedValues = new HashMap<>(); updatedValues.put(name, AttributeValueUpdate.builder() .value(AttributeValue.builder().s(updateVal).build()) .action(AttributeAction.PUT) .build()); UpdateItemRequest request = UpdateItemRequest.builder() .tableName(tableName) .key(itemKey) .attributeUpdates(updatedValues) .build(); try { ddb.updateItem(request); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("The Amazon DynamoDB table was updated!"); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考UpdateItem中的。

以下代码示例演示如何使用 UpdateTimeToLive

适用于 Java 的 SDK 2.x

在现有 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!");

在现有 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 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 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考UpdateTimeToLive中的。

场景

以下代码示例显示了如何有条件地更新项目的 TTL。

适用于 Java 的 SDK 2.x
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazon.samplelib.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; public class UpdateTTLConditional { public static void main(String[] args) { final String usage = """ Usage: <tableName> <primaryKey> <sortKey> <newTtlAttribute> <region> Where: tableName - The Amazon DynamoDB table being queried. primaryKey - The name of the primary key. Also known as the hash or partition key. sortKey - The name of the sort key. Also known as the range attribute. newTtlAttribute - New attribute name (as part of the update command) region (optional) - The AWS region that the Amazon DynamoDB table is located in. (Default: us-east-1) """; // Optional "region" parameter - if args list length is NOT 3 or 4, short-circuit exit. if (!(args.length == 4 || args.length == 5)) { System.out.println(usage); System.exit(1); } final String tableName = args[0]; final String primaryKey = args[1]; final String sortKey = args[2]; final String newTtlAttribute = args[3]; Region region = Optional.ofNullable(args[4]).isEmpty() ? Region.US_EAST_1 : Region.of(args[4]); // 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 newTtlAttribute = :val1"; // A condition that must be satisfied in order for a conditional update to succeed. final String conditionExpression = "expireAt > :val2"; final ImmutableMap<String, AttributeValue> keyMap = ImmutableMap.of("primaryKey", AttributeValue.fromS(primaryKey), "sortKey", AttributeValue.fromS(sortKey)); final Map<String, AttributeValue> expressionAttributeValues = ImmutableMap.of( ":val1", AttributeValue.builder().s(newTtlAttribute).build(), ":val2", AttributeValue.builder().s(String.valueOf(expireDate)).build() ); final UpdateItemRequest request = UpdateItemRequest.builder() .tableName(tableName) .key(keyMap) .updateExpression(updateExpression) .conditionExpression(conditionExpression) .expressionAttributeValues(expressionAttributeValues) .build(); try (DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build()) { final UpdateItemResponse response = ddb.updateItem(request); System.out.println(tableName + " UpdateItem operation with conditional 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 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考UpdateItem中的。

以下代码示例显示如何使用 TTL 创建项目。

适用于 Java 的 SDK 2.x
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazon.samplelib.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.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.utils.ImmutableMap; import java.io.Serializable; import java.util.Map; import java.util.Optional; public class CreateTTL { public static void main(String[] args) { final String usage = """ Usage: <tableName> <primaryKey> <sortKey> <region> Where: tableName - The Amazon DynamoDB table being queried. primaryKey - The name of the primary key. Also known as the hash or partition key. sortKey - The name of the sort key. Also known as the range attribute. region (optional) - The AWS region that the Amazon DynamoDB table is located in. (Default: us-east-1) """; // Optional "region" parameter - if args list length is NOT 3 or 4, short-circuit exit. if (!(args.length == 3 || args.length == 4)) { System.out.println(usage); System.exit(1); } String tableName = args[0]; String primaryKey = args[1]; String sortKey = args[2]; Region region = Optional.ofNullable(args[3]).isEmpty() ? Region.US_EAST_1 : Region.of(args[3]); // Get current time in epoch second format final long createDate = System.currentTimeMillis() / 1000; // Calculate expiration time 90 days from now in epoch second format final long expireDate = createDate + (90 * 24 * 60 * 60); final ImmutableMap<String, ? extends Serializable> itemMap = ImmutableMap.of("primaryKey", primaryKey, "sortKey", sortKey, "creationDate", createDate, "expireAt", expireDate); final PutItemRequest request = PutItemRequest.builder() .tableName(tableName) .item((Map<String, AttributeValue>) itemMap) .build(); try (DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build()) { final PutItemResponse response = ddb.putItem(request); System.out.println(tableName + " PutItem 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 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考PutItem中的。

以下代码示例展示了如何:

  • 创建可保存电影数据的表。

  • 在表中加入单一电影,获取并更新此电影。

  • 向 JSON 示例文件的表中写入电影数据。

  • 查询在给定年份发行的电影。

  • 扫描在年份范围内发行的电影。

  • 删除表中的电影后再删除表。

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

创建 DynamoDB 表。

// Create a table with a Sort key. public static void createTable(DynamoDbClient ddb, String tableName) { DynamoDbWaiter dbWaiter = ddb.waiter(); ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<>(); // Define attributes. attributeDefinitions.add(AttributeDefinition.builder() .attributeName("year") .attributeType("N") .build()); attributeDefinitions.add(AttributeDefinition.builder() .attributeName("title") .attributeType("S") .build()); ArrayList<KeySchemaElement> tableKey = new ArrayList<>(); KeySchemaElement key = KeySchemaElement.builder() .attributeName("year") .keyType(KeyType.HASH) .build(); KeySchemaElement key2 = KeySchemaElement.builder() .attributeName("title") .keyType(KeyType.RANGE) .build(); // Add KeySchemaElement objects to the list. tableKey.add(key); tableKey.add(key2); CreateTableRequest request = CreateTableRequest.builder() .keySchema(tableKey) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(10L) .writeCapacityUnits(10L) .build()) .attributeDefinitions(attributeDefinitions) .tableName(tableName) .build(); try { CreateTableResponse response = ddb.createTable(request); DescribeTableRequest tableRequest = DescribeTableRequest.builder() .tableName(tableName) .build(); // Wait until the Amazon DynamoDB table is created. WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); waiterResponse.matched().response().ifPresent(System.out::println); String newTable = response.tableDescription().tableName(); System.out.println("The " + newTable + " was successfully created."); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } }

创建帮助函数以下载并提取示例 JSON 文件。

// Load data into the table. public static void loadData(DynamoDbClient ddb, String tableName, String fileName) throws IOException { DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); DynamoDbTable<Movies> mappedTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); Iterator<JsonNode> iter = rootNode.iterator(); ObjectNode currentNode; int t = 0; while (iter.hasNext()) { // Only add 200 Movies to the table. if (t == 200) break; currentNode = (ObjectNode) iter.next(); int year = currentNode.path("year").asInt(); String title = currentNode.path("title").asText(); String info = currentNode.path("info").toString(); Movies movies = new Movies(); movies.setYear(year); movies.setTitle(title); movies.setInfo(info); // Put the data into the Amazon DynamoDB Movie table. mappedTable.putItem(movies); t++; } }

从表中获取项目。

public static void getItem(DynamoDbClient ddb) { HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put("year", AttributeValue.builder() .n("1933") .build()); keyToGet.put("title", AttributeValue.builder() .s("King Kong") .build()); GetItemRequest request = GetItemRequest.builder() .key(keyToGet) .tableName("Movies") .build(); try { Map<String, AttributeValue> returnedItem = ddb.getItem(request).item(); if (returnedItem != null) { Set<String> keys = returnedItem.keySet(); System.out.println("Amazon DynamoDB table attributes: \n"); for (String key1 : keys) { System.out.format("%s: %s\n", key1, returnedItem.get(key1).toString()); } } else { System.out.format("No item found with the key %s!\n", "year"); } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } }

完整示例。

/** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * This Java example performs these tasks: * * 1. Creates the Amazon DynamoDB Movie table with partition and sort key. * 2. Puts data into the Amazon DynamoDB table from a JSON document using the * Enhanced client. * 3. Gets data from the Movie table. * 4. Adds a new item. * 5. Updates an item. * 6. Uses a Scan to query items using the Enhanced client. * 7. Queries all items where the year is 2013 using the Enhanced Client. * 8. Deletes the table. */ public class Scenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); public static void main(String[] args) throws IOException { final String usage = """ Usage: <fileName> Where: fileName - The path to the moviedata.json file that you can download from the Amazon DynamoDB Developer Guide. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String tableName = "Movies"; String fileName = args[0]; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon DynamoDB example scenario."); System.out.println(DASHES); System.out.println(DASHES); System.out.println( "1. Creating an Amazon DynamoDB table named Movies with a key named year and a sort key named title."); createTable(ddb, tableName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("2. Loading data into the Amazon DynamoDB table."); loadData(ddb, tableName, fileName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("3. Getting data from the Movie table."); getItem(ddb); System.out.println(DASHES); System.out.println(DASHES); System.out.println("4. Putting a record into the Amazon DynamoDB table."); putRecord(ddb); System.out.println(DASHES); System.out.println(DASHES); System.out.println("5. Updating a record."); updateTableItem(ddb, tableName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("6. Scanning the Amazon DynamoDB table."); scanMovies(ddb, tableName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("7. Querying the Movies released in 2013."); queryTable(ddb); System.out.println(DASHES); System.out.println(DASHES); System.out.println("8. Deleting the Amazon DynamoDB table."); deleteDynamoDBTable(ddb, tableName); System.out.println(DASHES); ddb.close(); } // Create a table with a Sort key. public static void createTable(DynamoDbClient ddb, String tableName) { DynamoDbWaiter dbWaiter = ddb.waiter(); ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<>(); // Define attributes. attributeDefinitions.add(AttributeDefinition.builder() .attributeName("year") .attributeType("N") .build()); attributeDefinitions.add(AttributeDefinition.builder() .attributeName("title") .attributeType("S") .build()); ArrayList<KeySchemaElement> tableKey = new ArrayList<>(); KeySchemaElement key = KeySchemaElement.builder() .attributeName("year") .keyType(KeyType.HASH) .build(); KeySchemaElement key2 = KeySchemaElement.builder() .attributeName("title") .keyType(KeyType.RANGE) .build(); // Add KeySchemaElement objects to the list. tableKey.add(key); tableKey.add(key2); CreateTableRequest request = CreateTableRequest.builder() .keySchema(tableKey) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(10L) .writeCapacityUnits(10L) .build()) .attributeDefinitions(attributeDefinitions) .tableName(tableName) .build(); try { CreateTableResponse response = ddb.createTable(request); DescribeTableRequest tableRequest = DescribeTableRequest.builder() .tableName(tableName) .build(); // Wait until the Amazon DynamoDB table is created. WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); waiterResponse.matched().response().ifPresent(System.out::println); String newTable = response.tableDescription().tableName(); System.out.println("The " + newTable + " was successfully created."); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } // Query the table. public static void queryTable(DynamoDbClient ddb) { try { DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); DynamoDbTable<Movies> custTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); QueryConditional queryConditional = QueryConditional .keyEqualTo(Key.builder() .partitionValue(2013) .build()); // Get items in the table and write out the ID value. Iterator<Movies> results = custTable.query(queryConditional).items().iterator(); String result = ""; while (results.hasNext()) { Movies rec = results.next(); System.out.println("The title of the movie is " + rec.getTitle()); System.out.println("The movie information is " + rec.getInfo()); } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } // Scan the table. public static void scanMovies(DynamoDbClient ddb, String tableName) { System.out.println("******* Scanning all movies.\n"); try { DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); DynamoDbTable<Movies> custTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); Iterator<Movies> results = custTable.scan().items().iterator(); while (results.hasNext()) { Movies rec = results.next(); System.out.println("The movie title is " + rec.getTitle()); System.out.println("The movie year is " + rec.getYear()); } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } // Load data into the table. public static void loadData(DynamoDbClient ddb, String tableName, String fileName) throws IOException { DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); DynamoDbTable<Movies> mappedTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); Iterator<JsonNode> iter = rootNode.iterator(); ObjectNode currentNode; int t = 0; while (iter.hasNext()) { // Only add 200 Movies to the table. if (t == 200) break; currentNode = (ObjectNode) iter.next(); int year = currentNode.path("year").asInt(); String title = currentNode.path("title").asText(); String info = currentNode.path("info").toString(); Movies movies = new Movies(); movies.setYear(year); movies.setTitle(title); movies.setInfo(info); // Put the data into the Amazon DynamoDB Movie table. mappedTable.putItem(movies); t++; } } // Update the record to include show only directors. public static void updateTableItem(DynamoDbClient ddb, String tableName) { HashMap<String, AttributeValue> itemKey = new HashMap<>(); itemKey.put("year", AttributeValue.builder().n("1933").build()); itemKey.put("title", AttributeValue.builder().s("King Kong").build()); HashMap<String, AttributeValueUpdate> updatedValues = new HashMap<>(); updatedValues.put("info", AttributeValueUpdate.builder() .value(AttributeValue.builder().s("{\"directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack\"]") .build()) .action(AttributeAction.PUT) .build()); UpdateItemRequest request = UpdateItemRequest.builder() .tableName(tableName) .key(itemKey) .attributeUpdates(updatedValues) .build(); try { ddb.updateItem(request); } catch (ResourceNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Item was updated!"); } public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { DeleteTableRequest request = DeleteTableRequest.builder() .tableName(tableName) .build(); try { ddb.deleteTable(request); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println(tableName + " was successfully deleted!"); } public static void putRecord(DynamoDbClient ddb) { try { DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); DynamoDbTable<Movies> table = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); // Populate the Table. Movies record = new Movies(); record.setYear(2020); record.setTitle("My Movie2"); record.setInfo("no info"); table.putItem(record); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Added a new movie to the table."); } public static void getItem(DynamoDbClient ddb) { HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put("year", AttributeValue.builder() .n("1933") .build()); keyToGet.put("title", AttributeValue.builder() .s("King Kong") .build()); GetItemRequest request = GetItemRequest.builder() .key(keyToGet) .tableName("Movies") .build(); try { Map<String, AttributeValue> returnedItem = ddb.getItem(request).item(); if (returnedItem != null) { Set<String> keys = returnedItem.keySet(); System.out.println("Amazon DynamoDB table attributes: \n"); for (String key1 : keys) { System.out.format("%s: %s\n", key1, returnedItem.get(key1).toString()); } } else { System.out.format("No item found with the key %s!\n", "year"); } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } }

以下代码示例展示了如何:

  • 通过运行多个 SELECT 语句来获取一批项目。

  • 通过运行多个 INSERT 语句来添加一批项目。

  • 通过运行多个 UPDATE 语句来更新一批项目。

  • 通过运行多个 DELETE 语句来删除一批项目。

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

public class ScenarioPartiQLBatch { public static void main(String[] args) throws IOException { String tableName = "MoviesPartiQBatch"; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); System.out.println("******* Creating an Amazon DynamoDB table named " + tableName + " with a key named year and a sort key named title."); createTable(ddb, tableName); System.out.println("******* Adding multiple records into the " + tableName + " table using a batch command."); putRecordBatch(ddb); System.out.println("******* Updating multiple records using a batch command."); updateTableItemBatch(ddb); System.out.println("******* Deleting multiple records using a batch command."); deleteItemBatch(ddb); System.out.println("******* Deleting the Amazon DynamoDB table."); deleteDynamoDBTable(ddb, tableName); ddb.close(); } public static void createTable(DynamoDbClient ddb, String tableName) { DynamoDbWaiter dbWaiter = ddb.waiter(); ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<>(); // Define attributes. attributeDefinitions.add(AttributeDefinition.builder() .attributeName("year") .attributeType("N") .build()); attributeDefinitions.add(AttributeDefinition.builder() .attributeName("title") .attributeType("S") .build()); ArrayList<KeySchemaElement> tableKey = new ArrayList<>(); KeySchemaElement key = KeySchemaElement.builder() .attributeName("year") .keyType(KeyType.HASH) .build(); KeySchemaElement key2 = KeySchemaElement.builder() .attributeName("title") .keyType(KeyType.RANGE) // Sort .build(); // Add KeySchemaElement objects to the list. tableKey.add(key); tableKey.add(key2); CreateTableRequest request = CreateTableRequest.builder() .keySchema(tableKey) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(new Long(10)) .writeCapacityUnits(new Long(10)) .build()) .attributeDefinitions(attributeDefinitions) .tableName(tableName) .build(); try { CreateTableResponse response = ddb.createTable(request); DescribeTableRequest tableRequest = DescribeTableRequest.builder() .tableName(tableName) .build(); // Wait until the Amazon DynamoDB table is created. WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter .waitUntilTableExists(tableRequest); waiterResponse.matched().response().ifPresent(System.out::println); String newTable = response.tableDescription().tableName(); System.out.println("The " + newTable + " was successfully created."); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void putRecordBatch(DynamoDbClient ddb) { String sqlStatement = "INSERT INTO MoviesPartiQBatch VALUE {'year':?, 'title' : ?, 'info' : ?}"; try { // Create three movies to add to the Amazon DynamoDB table. // Set data for Movie 1. List<AttributeValue> parameters = new ArrayList<>(); AttributeValue att1 = AttributeValue.builder() .n(String.valueOf("2022")) .build(); AttributeValue att2 = AttributeValue.builder() .s("My Movie 1") .build(); AttributeValue att3 = AttributeValue.builder() .s("No Information") .build(); parameters.add(att1); parameters.add(att2); parameters.add(att3); BatchStatementRequest statementRequestMovie1 = BatchStatementRequest.builder() .statement(sqlStatement) .parameters(parameters) .build(); // Set data for Movie 2. List<AttributeValue> parametersMovie2 = new ArrayList<>(); AttributeValue attMovie2 = AttributeValue.builder() .n(String.valueOf("2022")) .build(); AttributeValue attMovie2A = AttributeValue.builder() .s("My Movie 2") .build(); AttributeValue attMovie2B = AttributeValue.builder() .s("No Information") .build(); parametersMovie2.add(attMovie2); parametersMovie2.add(attMovie2A); parametersMovie2.add(attMovie2B); BatchStatementRequest statementRequestMovie2 = BatchStatementRequest.builder() .statement(sqlStatement) .parameters(parametersMovie2) .build(); // Set data for Movie 3. List<AttributeValue> parametersMovie3 = new ArrayList<>(); AttributeValue attMovie3 = AttributeValue.builder() .n(String.valueOf("2022")) .build(); AttributeValue attMovie3A = AttributeValue.builder() .s("My Movie 3") .build(); AttributeValue attMovie3B = AttributeValue.builder() .s("No Information") .build(); parametersMovie3.add(attMovie3); parametersMovie3.add(attMovie3A); parametersMovie3.add(attMovie3B); BatchStatementRequest statementRequestMovie3 = BatchStatementRequest.builder() .statement(sqlStatement) .parameters(parametersMovie3) .build(); // Add all three movies to the list. List<BatchStatementRequest> myBatchStatementList = new ArrayList<>(); myBatchStatementList.add(statementRequestMovie1); myBatchStatementList.add(statementRequestMovie2); myBatchStatementList.add(statementRequestMovie3); BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() .statements(myBatchStatementList) .build(); BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest); System.out.println("ExecuteStatement successful: " + response.toString()); System.out.println("Added new movies using a batch command."); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void updateTableItemBatch(DynamoDbClient ddb) { String sqlStatement = "UPDATE MoviesPartiQBatch SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?"; List<AttributeValue> parametersRec1 = new ArrayList<>(); // Update three records. AttributeValue att1 = AttributeValue.builder() .n(String.valueOf("2022")) .build(); AttributeValue att2 = AttributeValue.builder() .s("My Movie 1") .build(); parametersRec1.add(att1); parametersRec1.add(att2); BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder() .statement(sqlStatement) .parameters(parametersRec1) .build(); // Update record 2. List<AttributeValue> parametersRec2 = new ArrayList<>(); AttributeValue attRec2 = AttributeValue.builder() .n(String.valueOf("2022")) .build(); AttributeValue attRec2a = AttributeValue.builder() .s("My Movie 2") .build(); parametersRec2.add(attRec2); parametersRec2.add(attRec2a); BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder() .statement(sqlStatement) .parameters(parametersRec2) .build(); // Update record 3. List<AttributeValue> parametersRec3 = new ArrayList<>(); AttributeValue attRec3 = AttributeValue.builder() .n(String.valueOf("2022")) .build(); AttributeValue attRec3a = AttributeValue.builder() .s("My Movie 3") .build(); parametersRec3.add(attRec3); parametersRec3.add(attRec3a); BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder() .statement(sqlStatement) .parameters(parametersRec3) .build(); // Add all three movies to the list. List<BatchStatementRequest> myBatchStatementList = new ArrayList<>(); myBatchStatementList.add(statementRequestRec1); myBatchStatementList.add(statementRequestRec2); myBatchStatementList.add(statementRequestRec3); BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() .statements(myBatchStatementList) .build(); try { BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest); System.out.println("ExecuteStatement successful: " + response.toString()); System.out.println("Updated three movies using a batch command."); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Item was updated!"); } public static void deleteItemBatch(DynamoDbClient ddb) { String sqlStatement = "DELETE FROM MoviesPartiQBatch WHERE year = ? and title=?"; List<AttributeValue> parametersRec1 = new ArrayList<>(); // Specify three records to delete. AttributeValue att1 = AttributeValue.builder() .n(String.valueOf("2022")) .build(); AttributeValue att2 = AttributeValue.builder() .s("My Movie 1") .build(); parametersRec1.add(att1); parametersRec1.add(att2); BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder() .statement(sqlStatement) .parameters(parametersRec1) .build(); // Specify record 2. List<AttributeValue> parametersRec2 = new ArrayList<>(); AttributeValue attRec2 = AttributeValue.builder() .n(String.valueOf("2022")) .build(); AttributeValue attRec2a = AttributeValue.builder() .s("My Movie 2") .build(); parametersRec2.add(attRec2); parametersRec2.add(attRec2a); BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder() .statement(sqlStatement) .parameters(parametersRec2) .build(); // Specify record 3. List<AttributeValue> parametersRec3 = new ArrayList<>(); AttributeValue attRec3 = AttributeValue.builder() .n(String.valueOf("2022")) .build(); AttributeValue attRec3a = AttributeValue.builder() .s("My Movie 3") .build(); parametersRec3.add(attRec3); parametersRec3.add(attRec3a); BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder() .statement(sqlStatement) .parameters(parametersRec3) .build(); // Add all three movies to the list. List<BatchStatementRequest> myBatchStatementList = new ArrayList<>(); myBatchStatementList.add(statementRequestRec1); myBatchStatementList.add(statementRequestRec2); myBatchStatementList.add(statementRequestRec3); BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() .statements(myBatchStatementList) .build(); try { ddb.batchExecuteStatement(batchRequest); System.out.println("Deleted three movies using a batch command."); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { DeleteTableRequest request = DeleteTableRequest.builder() .tableName(tableName) .build(); try { ddb.deleteTable(request); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println(tableName + " was successfully deleted!"); } private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, List<AttributeValue> parameters) { ExecuteStatementRequest request = ExecuteStatementRequest.builder() .statement(statement) .parameters(parameters) .build(); return ddb.executeStatement(request); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考BatchExecuteStatement中的。

以下代码示例展示了如何:

  • 通过运行 SELECT 语句来获取项目。

  • 通过运行 INSERT 语句来添加项目。

  • 通过运行 UPDATE 语句来更新项目。

  • 通过运行 DELETE 语句来删除项目。

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

public class ScenarioPartiQ { public static void main(String[] args) throws IOException { final String usage = """ Usage: <fileName> Where: fileName - The path to the moviedata.json file that you can download from the Amazon DynamoDB Developer Guide. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String fileName = args[0]; String tableName = "MoviesPartiQ"; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); System.out.println( "******* Creating an Amazon DynamoDB table named MoviesPartiQ with a key named year and a sort key named title."); createTable(ddb, tableName); System.out.println("******* Loading data into the MoviesPartiQ table."); loadData(ddb, fileName); System.out.println("******* Getting data from the MoviesPartiQ table."); getItem(ddb); System.out.println("******* Putting a record into the MoviesPartiQ table."); putRecord(ddb); System.out.println("******* Updating a record."); updateTableItem(ddb); System.out.println("******* Querying the movies released in 2013."); queryTable(ddb); System.out.println("******* Deleting the Amazon DynamoDB table."); deleteDynamoDBTable(ddb, tableName); ddb.close(); } public static void createTable(DynamoDbClient ddb, String tableName) { DynamoDbWaiter dbWaiter = ddb.waiter(); ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<>(); // Define attributes. attributeDefinitions.add(AttributeDefinition.builder() .attributeName("year") .attributeType("N") .build()); attributeDefinitions.add(AttributeDefinition.builder() .attributeName("title") .attributeType("S") .build()); ArrayList<KeySchemaElement> tableKey = new ArrayList<>(); KeySchemaElement key = KeySchemaElement.builder() .attributeName("year") .keyType(KeyType.HASH) .build(); KeySchemaElement key2 = KeySchemaElement.builder() .attributeName("title") .keyType(KeyType.RANGE) // Sort .build(); // Add KeySchemaElement objects to the list. tableKey.add(key); tableKey.add(key2); CreateTableRequest request = CreateTableRequest.builder() .keySchema(tableKey) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(new Long(10)) .writeCapacityUnits(new Long(10)) .build()) .attributeDefinitions(attributeDefinitions) .tableName(tableName) .build(); try { CreateTableResponse response = ddb.createTable(request); DescribeTableRequest tableRequest = DescribeTableRequest.builder() .tableName(tableName) .build(); // Wait until the Amazon DynamoDB table is created. WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); waiterResponse.matched().response().ifPresent(System.out::println); String newTable = response.tableDescription().tableName(); System.out.println("The " + newTable + " was successfully created."); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } // Load data into the table. public static void loadData(DynamoDbClient ddb, String fileName) throws IOException { String sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}"; JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); Iterator<JsonNode> iter = rootNode.iterator(); ObjectNode currentNode; int t = 0; List<AttributeValue> parameters = new ArrayList<>(); while (iter.hasNext()) { // Add 200 movies to the table. if (t == 200) break; currentNode = (ObjectNode) iter.next(); int year = currentNode.path("year").asInt(); String title = currentNode.path("title").asText(); String info = currentNode.path("info").toString(); AttributeValue att1 = AttributeValue.builder() .n(String.valueOf(year)) .build(); AttributeValue att2 = AttributeValue.builder() .s(title) .build(); AttributeValue att3 = AttributeValue.builder() .s(info) .build(); parameters.add(att1); parameters.add(att2); parameters.add(att3); // Insert the movie into the Amazon DynamoDB table. executeStatementRequest(ddb, sqlStatement, parameters); System.out.println("Added Movie " + title); parameters.remove(att1); parameters.remove(att2); parameters.remove(att3); t++; } } public static void getItem(DynamoDbClient ddb) { String sqlStatement = "SELECT * FROM MoviesPartiQ where year=? and title=?"; List<AttributeValue> parameters = new ArrayList<>(); AttributeValue att1 = AttributeValue.builder() .n("2012") .build(); AttributeValue att2 = AttributeValue.builder() .s("The Perks of Being a Wallflower") .build(); parameters.add(att1); parameters.add(att2); try { ExecuteStatementResponse response = executeStatementRequest(ddb, sqlStatement, parameters); System.out.println("ExecuteStatement successful: " + response.toString()); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void putRecord(DynamoDbClient ddb) { String sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}"; try { List<AttributeValue> parameters = new ArrayList<>(); AttributeValue att1 = AttributeValue.builder() .n(String.valueOf("2020")) .build(); AttributeValue att2 = AttributeValue.builder() .s("My Movie") .build(); AttributeValue att3 = AttributeValue.builder() .s("No Information") .build(); parameters.add(att1); parameters.add(att2); parameters.add(att3); executeStatementRequest(ddb, sqlStatement, parameters); System.out.println("Added new movie."); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void updateTableItem(DynamoDbClient ddb) { String sqlStatement = "UPDATE MoviesPartiQ SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?"; List<AttributeValue> parameters = new ArrayList<>(); AttributeValue att1 = AttributeValue.builder() .n(String.valueOf("2013")) .build(); AttributeValue att2 = AttributeValue.builder() .s("The East") .build(); parameters.add(att1); parameters.add(att2); try { executeStatementRequest(ddb, sqlStatement, parameters); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Item was updated!"); } // Query the table where the year is 2013. public static void queryTable(DynamoDbClient ddb) { String sqlStatement = "SELECT * FROM MoviesPartiQ where year = ? ORDER BY year"; try { List<AttributeValue> parameters = new ArrayList<>(); AttributeValue att1 = AttributeValue.builder() .n(String.valueOf("2013")) .build(); parameters.add(att1); // Get items in the table and write out the ID value. ExecuteStatementResponse response = executeStatementRequest(ddb, sqlStatement, parameters); System.out.println("ExecuteStatement successful: " + response.toString()); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { DeleteTableRequest request = DeleteTableRequest.builder() .tableName(tableName) .build(); try { ddb.deleteTable(request); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println(tableName + " was successfully deleted!"); } private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, List<AttributeValue> parameters) { ExecuteStatementRequest request = ExecuteStatementRequest.builder() .statement(statement) .parameters(parameters) .build(); return ddb.executeStatement(request); } private static void processResults(ExecuteStatementResponse executeStatementResult) { System.out.println("ExecuteStatement successful: " + executeStatementResult.toString()); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考ExecuteStatement中的。

以下代码示例显示如何查询 TTL 项目。

适用于 Java 的 SDK 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.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.utils.ImmutableMap; import java.util.Map; import java.util.Optional; // Get current time in epoch second format (comparing against expiry attribute) final long currentTime = System.currentTimeMillis() / 1000; // A string that contains conditions that DynamoDB applies after the Query operation, but before the data is returned to you. final String keyConditionExpression = "#pk = :pk"; // The condition that specifies the key values for items to be retrieved by the Query action. final String filterExpression = "#ea > :ea"; final Map<String, String> expressionAttributeNames = ImmutableMap.of( "#pk", "primaryKey", "#ea", "expireAt"); final Map<String, AttributeValue> expressionAttributeValues = ImmutableMap.of( ":pk", AttributeValue.builder().s(primaryKey).build(), ":ea", AttributeValue.builder().s(String.valueOf(currentTime)).build() ); final QueryRequest request = QueryRequest.builder() .tableName(tableName) .keyConditionExpression(keyConditionExpression) .filterExpression(filterExpression) .expressionAttributeNames(expressionAttributeNames) .expressionAttributeValues(expressionAttributeValues) .build(); try (DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build()) { final QueryResponse response = ddb.query(request); System.out.println(tableName + " Query operation with TTL successful. Request id is " + response.responseMetadata().requestId()); // Print the items that are not expired for (Map<String, AttributeValue> item : response.items()) { System.out.println(item.toString()); } } 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 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 Query

以下代码示例显示如何更新项目的 TTL。

适用于 Java 的 SDK 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 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考UpdateItem中的。

无服务器示例

以下代码示例演示如何实现 Lambda 函数,该函数接收通过从 DynamoDB 流接收记录而触发的事件。该函数检索 DynamoDB 有效负载,并记录下记录内容。

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

使用 Java 将 DynamoDB 事件与 Lambda 结合使用。

import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class example implements RequestHandler<DynamodbEvent, Void> { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); @Override public Void handleRequest(DynamodbEvent event, Context context) { System.out.println(GSON.toJson(event)); event.getRecords().forEach(this::logDynamoDBRecord); return null; } private void logDynamoDBRecord(DynamodbStreamRecord record) { System.out.println(record.getEventID()); System.out.println(record.getEventName()); System.out.println("DynamoDB Record: " + GSON.toJson(record.getDynamodb())); } }

以下代码示例演示如何为接收来自 DynamoDB 流的事件的 Lambda 函数实现部分批量响应。该函数在响应中报告批处理项目失败,并指示 Lambda 稍后重试这些消息。

适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

报告使用 Java 通过 Lambda 进行 DynamoDB 批处理项目失败。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; import com.amazonaws.services.lambda.runtime.events.StreamsEventResponse; import com.amazonaws.services.lambda.runtime.events.models.dynamodb.StreamRecord; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ProcessDynamodbRecords implements RequestHandler<DynamodbEvent, Serializable> { @Override public StreamsEventResponse handleRequest(DynamodbEvent input, Context context) { List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new ArrayList<>(); String curRecordSequenceNumber = ""; for (DynamodbEvent.DynamodbStreamRecord dynamodbStreamRecord : input.getRecords()) { try { //Process your record StreamRecord dynamodbRecord = dynamodbStreamRecord.getDynamodb(); curRecordSequenceNumber = dynamodbRecord.getSequenceNumber(); } catch (Exception e) { /* Since we are working with streams, we can return the failed item immediately. Lambda will immediately begin to retry processing from this failed item onwards. */ batchItemFailures.add(new StreamsEventResponse.BatchItemFailure(curRecordSequenceNumber)); return new StreamsEventResponse(batchItemFailures); } } return new StreamsEventResponse(); } }