Ci sono altri AWS SDK esempi disponibili nel repository AWS Doc SDK Examples
Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.
Esempi SDK di utilizzo di DynamoDB per Java 2.x
I seguenti esempi di codice mostrano come eseguire azioni e implementare scenari comuni utilizzando AWS SDK for Java 2.x con DynamoDB.
Le basi sono esempi di codice che mostrano come eseguire le operazioni essenziali all'interno di un servizio.
Le operazioni sono estratti di codice da programmi più grandi e devono essere eseguite nel contesto. Mentre le azioni mostrano come richiamare le singole funzioni di servizio, è possibile visualizzare le azioni nel loro contesto nei relativi scenari.
Gli scenari sono esempi di codice che mostrano come eseguire attività specifiche richiamando più funzioni all'interno di un servizio o combinandole con altre Servizi AWS.
Ogni esempio include un collegamento al codice sorgente completo, in cui è possibile trovare istruzioni su come configurare ed eseguire il codice nel contesto.
Nozioni di base
Gli esempi di codice seguenti mostrano come iniziare a utilizzare DynamoDB.
- SDKper Java 2.x
-
Nota
C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. 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!"); } }
-
Per API i dettagli, vedi ListTables AWS SDK for Java 2.xAPIReference.
-
Nozioni di base
L'esempio di codice seguente mostra come:
Crea una tabella in grado di contenere i dati del filmato.
Inserisci, ottieni e aggiorna un singolo filmato nella tabella.
Scrivi i dati del filmato sulla tabella a partire da un JSON file di esempio.
Esegui una query sui filmati che sono stati rilasciati in un dato anno.
Cerca i filmati che sono stati distribuiti in diversi anni.
Elimina un filmato dalla tabella, quindi elimina la tabella.
- SDKper Java 2.x
-
Nota
C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. Creazione di una tabella 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); } }
Crea una funzione di supporto per scaricare ed estrarre il JSON file di esempio.
// 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++; } }
Ottieni un elemento da una tabella
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); } }
Esempio completo.
/** * 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); } } }
-
Per API i dettagli, consultate i seguenti argomenti in AWS SDK for Java 2.x APIRiferimento.
-
Azioni
Il seguente esempio di codice mostra come utilizzareBatchGetItem
.
- SDKper Java 2.x
-
Nota
C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. mostra come ottenere articoli in batch utilizzando il client di servizio.
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."); } } }
mostra come ottenere articoli in batch utilizzando il client di servizio e un impaginatore.
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()); }); } }
-
Per API i dettagli, vedere BatchGetItemin AWS SDK for Java 2.x API Reference.
-
Il seguente esempio di codice mostra come utilizzareBatchWriteItem
.
- SDKper Java 2.x
-
Nota
C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. Inserisce molti elementi in una tabella utilizzando il client di servizio.
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); } } }
Inserisce molti elementi in una tabella utilizzando il client avanzato.
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); } } }
-
Per API i dettagli, vedere BatchWriteItemin AWS SDK for Java 2.x APIReference.
-
Il seguente esempio di codice mostra come utilizzareCreateTable
.
- SDKper Java 2.x
-
Nota
C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. 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 ""; } }
-
Per API i dettagli, vedi CreateTable AWS SDK for Java 2.xAPIReference.
-
Il seguente esempio di codice mostra come utilizzareDeleteItem
.
- SDKper Java 2.x
-
Nota
C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. 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); } } }
-
Per API i dettagli, vedi DeleteItem AWS SDK for Java 2.xAPIReference.
-
Il seguente esempio di codice mostra come utilizzareDeleteTable
.
- SDKper Java 2.x
-
Nota
C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. 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!"); } }
-
Per API i dettagli, vedi DeleteTable AWS SDK for Java 2.xAPIReference.
-
Il seguente esempio di codice mostra come utilizzareDescribeTable
.
- SDKper Java 2.x
-
Nota
C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. 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!"); } }
-
Per API i dettagli, vedi DescribeTable AWS SDK for Java 2.xAPIReference.
-
Il seguente esempio di codice mostra come utilizzareDescribeTimeToLive
.
- SDKper Java 2.x
-
Descrivi la TTL configurazione su una tabella DynamoDB esistente.
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);
-
Per API i dettagli, consulta la sezione DescribeTimeToLiveReference AWS SDK for Java 2.x API.
-
Il seguente esempio di codice mostra come utilizzareGetItem
.
- SDKper Java 2.x
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. Ottiene un elemento da una tabella utilizzando 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); } } }
-
Per API i dettagli, vedere GetItemin AWS SDK for Java 2.x APIReference.
-
Il seguente esempio di codice mostra come utilizzareListTables
.
- SDKper Java 2.x
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. 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!"); } }
-
Per API i dettagli, vedi ListTables AWS SDK for Java 2.xAPIReference.
-
Il seguente esempio di codice mostra come utilizzarePutItem
.
- SDKper Java 2.x
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. Mette un elemento in una tabella utilizzando 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); } } }
-
Per API i dettagli, vedere PutItemin AWS SDK for Java 2.x APIReference.
-
Il seguente esempio di codice mostra come utilizzareQuery
.
- SDKper Java 2.x
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. Interroga una tabella utilizzando 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; } }
Esegue query su una tabella utilizzando
DynamoDbClient
e un indice secondario.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); } } }
-
Per API i dettagli, vedere Query in AWS SDK for Java 2.x APIReference.
-
Il seguente esempio di codice mostra come utilizzareScan
.
- SDKper Java 2.x
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. Esegue la scansione di una tabella Amazon DynamoDB utilizzando 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); } } }
-
Per API i dettagli, consulta Scan in Reference.AWS SDK for Java 2.x API
-
Il seguente esempio di codice mostra come utilizzareUpdateItem
.
- SDKper Java 2.x
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. Aggiorna un elemento in una tabella utilizzando 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!"); } }
-
Per API i dettagli, vedere UpdateItemin AWS SDK for Java 2.x APIReference.
-
Il seguente esempio di codice mostra come utilizzareUpdateTimeToLive
.
- SDKper Java 2.x
-
Abilita TTL su una tabella DynamoDB esistente.
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!");
Disabilita TTL su una tabella DynamoDB esistente.
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!");
-
Per API i dettagli, consulta la sezione UpdateTimeToLiveReference AWS SDK for Java 2.x API.
-
Scenari
Il seguente esempio di codice mostra come creare un'applicazione che invia dati a una tabella Amazon DynamoDB e ti avvisa quando un utente aggiorna la tabella.
- SDKper Java 2.x
-
Mostra come creare un'applicazione Web dinamica che invia dati utilizzando Amazon API DynamoDB Java e invia un messaggio di testo utilizzando Amazon Simple Notification Service Java. API
Per il codice sorgente completo e le istruzioni su come configurarlo ed eseguirlo, consulta l'esempio completo su. GitHub
Servizi utilizzati in questo esempio
DynamoDB
Amazon SNS
Il seguente esempio di codice mostra come aggiornare in modo condizionale un elemento. TTL
- SDKper Java 2.x
-
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); } }
-
Per API i dettagli, vedere UpdateItemin AWS SDK for Java 2.x APIReference.
-
Nell'esempio di codice seguente viene illustrato come creare un'applicazione serverless che consente agli utenti di gestire le foto mediante etichette.
- SDKper Java 2.x
-
Mostra come sviluppare un'applicazione per la gestione delle risorse fotografiche che rileva le etichette nelle immagini utilizzando Amazon Rekognition e le archivia per recuperarle in seguito.
Per il codice sorgente completo e le istruzioni su come configurarlo ed eseguirlo, vedi l'esempio completo su GitHub
. Per approfondire l'origine di questo esempio, consulta il post su AWS Community
. Servizi utilizzati in questo esempio
APIGateway
DynamoDB
Lambda
Amazon Rekognition
Amazon S3
Amazon SNS
Il seguente esempio di codice mostra come creare una tabella con la velocità effettiva calda abilitata.
- SDKper Java 2.x
-
Crea una tabella DynamoDB con un'impostazione di throughput calda.
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.GlobalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; import software.amazon.awssdk.services.dynamodb.model.WarmThroughput; public static WarmThroughput buildWarmThroughput(final Long readUnitsPerSecond, final Long writeUnitsPerSecond) { return WarmThroughput.builder() .readUnitsPerSecond(readUnitsPerSecond) .writeUnitsPerSecond(writeUnitsPerSecond) .build(); } public static ProvisionedThroughput buildProvisionedThroughput(final Long readCapacityUnits, final Long writeCapacityUnits) { return ProvisionedThroughput.builder() .readCapacityUnits(readCapacityUnits) .writeCapacityUnits(writeCapacityUnits) .build(); } private static AttributeDefinition buildAttributeDefinition(final String attributeName, final ScalarAttributeType scalarAttributeType) { return AttributeDefinition.builder() .attributeName(attributeName) .attributeType(scalarAttributeType) .build(); } private static KeySchemaElement buildKeySchemaElement(final String attributeName, final KeyType keyType) { return KeySchemaElement.builder() .attributeName(attributeName) .keyType(keyType) .build(); } public static void createDynamoDBTable(DynamoDbClient ddb, String tableName, String partitionKey, String sortKey, String miscellaneousKeyAttribute, String nonKeyAttribute, Long tableReadCapacityUnits, Long tableWriteCapacityUnits, Long tableWarmReadUnitsPerSecond, Long tableWarmWriteUnitsPerSecond, String globalSecondaryIndexName, Long globalSecondaryIndexReadCapacityUnits, Long globalSecondaryIndexWriteCapacityUnits, Long globalSecondaryIndexWarmReadUnitsPerSecond, Long globalSecondaryIndexWarmWriteUnitsPerSecond) { // Define the table attributes final AttributeDefinition partitionKeyAttribute = buildAttributeDefinition(partitionKey, ScalarAttributeType.S); final AttributeDefinition sortKeyAttribute = buildAttributeDefinition(sortKey, ScalarAttributeType.S); final AttributeDefinition miscellaneousKeyAttributeDefinition = buildAttributeDefinition(miscellaneousKeyAttribute, ScalarAttributeType.N); final AttributeDefinition[] attributeDefinitions = {partitionKeyAttribute, sortKeyAttribute, miscellaneousKeyAttributeDefinition}; // Define the table key schema final KeySchemaElement partitionKeyElement = buildKeySchemaElement(partitionKey, KeyType.HASH); final KeySchemaElement sortKeyElement = buildKeySchemaElement(sortKey, KeyType.RANGE); final KeySchemaElement[] keySchema = {partitionKeyElement, sortKeyElement}; // Define the provisioned throughput for the table final ProvisionedThroughput provisionedThroughput = buildProvisionedThroughput(tableReadCapacityUnits, tableWriteCapacityUnits); // Define the Global Secondary Index (GSI) final KeySchemaElement globalSecondaryIndexPartitionKeyElement = buildKeySchemaElement(sortKey, KeyType.HASH); final KeySchemaElement globalSecondaryIndexSortKeyElement = buildKeySchemaElement(miscellaneousKeyAttribute, KeyType.RANGE); final KeySchemaElement[] gsiKeySchema = {globalSecondaryIndexPartitionKeyElement, globalSecondaryIndexSortKeyElement}; final Projection gsiProjection = Projection.builder() .projectionType(String.valueOf(ProjectionType.INCLUDE)) .nonKeyAttributes(nonKeyAttribute) .build(); final ProvisionedThroughput gsiProvisionedThroughput = buildProvisionedThroughput(globalSecondaryIndexReadCapacityUnits, globalSecondaryIndexWriteCapacityUnits); // Define the warm throughput for the Global Secondary Index (GSI) final WarmThroughput gsiWarmThroughput = buildWarmThroughput(globalSecondaryIndexWarmReadUnitsPerSecond, globalSecondaryIndexWarmWriteUnitsPerSecond); final GlobalSecondaryIndex globalSecondaryIndex = GlobalSecondaryIndex.builder() .indexName(globalSecondaryIndexName) .keySchema(gsiKeySchema) .projection(gsiProjection) .provisionedThroughput(gsiProvisionedThroughput) .warmThroughput(gsiWarmThroughput) .build(); // Define the warm throughput for the table final WarmThroughput tableWarmThroughput = buildWarmThroughput(tableWarmReadUnitsPerSecond, tableWarmWriteUnitsPerSecond); final CreateTableRequest request = CreateTableRequest.builder() .tableName(tableName) .attributeDefinitions(attributeDefinitions) .keySchema(keySchema) .provisionedThroughput(provisionedThroughput) .globalSecondaryIndexes(globalSecondaryIndex) .warmThroughput(tableWarmThroughput) .build(); CreateTableResponse response = ddb.createTable(request); System.out.println(response); }
-
Per i API dettagli, consulta CreateTablela sezione Reference.AWS SDK for Java 2.x API
-
Il seguente esempio di codice mostra come creare un'applicazione Web che tiene traccia degli elementi di lavoro in una tabella Amazon DynamoDB e utilizza Amazon Simple Email Service (SESAmazon) per inviare report.
- SDKper Java 2.x
-
Mostra come utilizzare Amazon DynamoDB per creare un'applicazione Web API dinamica che tenga traccia dei dati di lavoro di DynamoDB.
Per il codice sorgente completo e le istruzioni su come configurarlo ed eseguirlo, consulta l'esempio completo su. GitHub
Servizi utilizzati in questo esempio
DynamoDB
Amazon SES
Il seguente esempio di codice mostra come creare un elemento conTTL.
- SDKper Java 2.x
-
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); } }
-
Per API i dettagli, vedere PutItemin AWS SDK for Java 2.x APIReference.
-
Il seguente esempio di codice mostra come creare un'app che utilizza Amazon Rekognition per rilevare i dispositivi di protezione PPE individuale () nelle immagini.
- SDKper Java 2.x
-
Mostra come creare una AWS Lambda funzione che rileva le immagini con dispositivi di protezione individuale.
Per il codice sorgente completo e le istruzioni su come configurarlo ed eseguirlo, guarda l'esempio completo su GitHub
. Servizi utilizzati in questo esempio
DynamoDB
Amazon Rekognition
Amazon S3
Amazon SES
Il seguente esempio di codice mostra come configurare l'uso di DynamoDB da parte di un'applicazione per monitorare le prestazioni.
- SDKper Java 2.x
-
Questo esempio mostra come configurare un'applicazione Java per monitorare le prestazioni di DynamoDB. L'applicazione invia i dati metrici a CloudWatch cui è possibile monitorare le prestazioni.
Per il codice sorgente completo e le istruzioni su come configurarlo ed eseguirlo, guarda l'esempio completo su GitHub
. Servizi utilizzati in questo esempio
CloudWatch
DynamoDB
L'esempio di codice seguente mostra come:
Ottieni un batch di elementi eseguendo più SELECT istruzioni.
Aggiungi un batch di elementi eseguendo più INSERT istruzioni.
Aggiorna un batch di elementi eseguendo più UPDATE istruzioni.
Eliminare un batch di elementi eseguendo più DELETE istruzioni.
- SDKper Java 2.x
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. 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); // Update multiple movies by using the BatchExecute statement. String title1 = "Star Wars"; int year1 = 1977; String title2 = "Wizard of Oz"; int year2 = 1939; System.out.println("Query two movies."); getBatch(ddb, tableName, title1, title2, year1, year2); 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 boolean getBatch(DynamoDbClient ddb, String tableName, String title1, String title2, int year1, int year2) { String getBatch = "SELECT * FROM " + tableName + " WHERE title = ? AND year = ?"; List<BatchStatementRequest> statements = new ArrayList<>(); statements.add(BatchStatementRequest.builder() .statement(getBatch) .parameters(AttributeValue.builder().s(title1).build(), AttributeValue.builder().n(String.valueOf(year1)).build()) .build()); statements.add(BatchStatementRequest.builder() .statement(getBatch) .parameters(AttributeValue.builder().s(title2).build(), AttributeValue.builder().n(String.valueOf(year2)).build()) .build()); BatchExecuteStatementRequest batchExecuteStatementRequest = BatchExecuteStatementRequest.builder() .statements(statements) .build(); try { BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchExecuteStatementRequest); if (!response.responses().isEmpty()) { response.responses().forEach(r -> { System.out.println(r.item().get("title") + "\\t" + r.item().get("year")); }); return true; } else { System.out.println("Couldn't find either " + title1 + " or " + title2 + "."); return false; } } catch (DynamoDbException e) { System.err.println(e.getMessage()); return false; } } 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(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); } } 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("1977") .build(); AttributeValue att2 = AttributeValue.builder() .s("Star Wars") .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("1939") .build(); AttributeValue attMovie2A = AttributeValue.builder() .s("Wizard of Oz") .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); } }
-
Per API i dettagli, vedi BatchExecuteStatement AWS SDK for Java 2.xAPIReference.
-
L'esempio di codice seguente mostra come:
Ottieni un elemento eseguendo una SELECT dichiarazione.
Aggiungi un elemento eseguendo un'INSERTistruzione.
Aggiorna un elemento eseguendo un'UPDATEistruzione.
Eliminare un elemento eseguendo un'DELETEistruzione.
- SDKper Java 2.x
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. 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()); } }
-
Per API i dettagli, vedi ExecuteStatement AWS SDK for Java 2.xAPIReference.
-
Il seguente esempio di codice mostra come eseguire una query per TTL gli elementi.
- SDKper Java 2.x
-
Interroga l'espressione filtrata per raccogliere TTL elementi in una tabella DynamoDB.
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);
-
Per API i dettagli, consulta Query in Reference.AWS SDK for Java 2.x API
-
Il seguente esempio di codice mostra come aggiornare l'impostazione del throughput caldo di una tabella.
- SDKper Java 2.x
-
Aggiorna l'impostazione del throughput caldo su una tabella DynamoDB esistente.
import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndexUpdate; import software.amazon.awssdk.services.dynamodb.model.UpdateGlobalSecondaryIndexAction; import software.amazon.awssdk.services.dynamodb.model.UpdateTableRequest; import software.amazon.awssdk.services.dynamodb.model.WarmThroughput; public static WarmThroughput buildWarmThroughput(final Long readUnitsPerSecond, final Long writeUnitsPerSecond) { return WarmThroughput.builder() .readUnitsPerSecond(readUnitsPerSecond) .writeUnitsPerSecond(writeUnitsPerSecond) .build(); } public static void updateDynamoDBTable(DynamoDbClient ddb, String tableName, Long tableReadUnitsPerSecond, Long tableWriteUnitsPerSecond, String globalSecondaryIndexName, Long globalSecondaryIndexReadUnitsPerSecond, Long globalSecondaryIndexWriteUnitsPerSecond) { final WarmThroughput tableWarmThroughput = buildWarmThroughput(tableReadUnitsPerSecond, tableWriteUnitsPerSecond); final WarmThroughput gsiWarmThroughput = buildWarmThroughput(globalSecondaryIndexReadUnitsPerSecond, globalSecondaryIndexWriteUnitsPerSecond); final GlobalSecondaryIndexUpdate globalSecondaryIndexUpdate = GlobalSecondaryIndexUpdate.builder() .update(UpdateGlobalSecondaryIndexAction.builder() .indexName(globalSecondaryIndexName) .warmThroughput(gsiWarmThroughput) .build() ).build(); final UpdateTableRequest request = UpdateTableRequest.builder() .tableName(tableName) .globalSecondaryIndexUpdates(globalSecondaryIndexUpdate) .warmThroughput(tableWarmThroughput) .build(); try { ddb.updateTable(request); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Done!"); }
-
Per i API dettagli, consulta UpdateTablela sezione Reference.AWS SDK for Java 2.x API
-
Il seguente esempio di codice mostra come aggiornare un articoloTTL.
- SDKper Java 2.x
-
Aggiornamento TTL su un elemento DynamoDB esistente in una tabella.
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);
-
Per API i dettagli, consulta la sezione UpdateItemReference AWS SDK for Java 2.x API.
-
Il seguente esempio di codice mostra come creare una macchina a AWS Step Functions stati che richiama AWS Lambda funzioni in sequenza.
- SDKper Java 2.x
-
Mostra come creare un flusso di lavoro AWS serverless utilizzando AWS Step Functions and. AWS SDK for Java 2.x Ogni fase del flusso di lavoro viene implementata utilizzando una AWS Lambda funzione.
Per il codice sorgente completo e le istruzioni su come configurarlo ed eseguirlo, vedi l'esempio completo su GitHub
. Servizi utilizzati in questo esempio
DynamoDB
Lambda
Amazon SES
Step Functions
Esempi serverless
Il seguente esempio di codice mostra come implementare una funzione Lambda che riceve un evento attivato dalla ricezione di record da un flusso DynamoDB. La funzione recupera il payload DynamoDB e registra il contenuto del record.
- SDKper Java 2.x
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless
. Consumo di un evento DynamoDB con Lambda utilizzando Java.
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())); } }
Il seguente esempio di codice mostra come implementare una risposta batch parziale per le funzioni Lambda che ricevono eventi da un flusso DynamoDB. La funzione riporta gli errori degli elementi batch nella risposta, segnalando a Lambda di riprovare tali messaggi in un secondo momento.
- SDKper Java 2.x
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless
. Segnalazione degli errori degli elementi batch di DynamoDB con Lambda utilizzando Java.
// 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(); } }