Interfacce programmatiche che funzionano con DynamoDB - Amazon DynamoDB

Interfacce programmatiche che funzionano con DynamoDB

Ciascun SDK AWS fornisce una o più interfacce programmatiche per lavorare con Amazon DynamoDB. Queste interfacce spaziano da semplici wrapper DynamoDB di basso livello a livelli di persistenza basati sugli oggetti. Le interfacce specifiche disponibili dipendono dal linguaggio di programmazione e dall'SDK AWS in uso.

Interfacce programmatiche disponibili in diversi SDK AWS per lavorare con DynamoDB.

Nella sezione seguente sono descritte alcune delle interfacce disponibili con AWS SDK per Java come esempio Non tutte le interfacce sono disponibili in tutti gli SDK AWS.

Interfacce di basso livello che funzionano con DynamoDB

Ogni SDK AWS specifico del linguaggio fornisce un'interfaccia di basso livello per Amazon DynamoDB, con metodi che assomigliano molto alle richieste API DynamoDB di basso livello.

In alcuni casi, sarà necessario identificare i tipi di dati degli attributi utilizzando Descrittori del tipo di dati, ad esempio S per stringa o N per numero

Nota

Un'interfaccia di basso livello è disponibile in ogni SDK AWS specifico per il linguaggio.

Il seguente programma Java utilizza l'interfaccia di basso livello di AWS SDK per Java.

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); } } }

Interfacce documentali che funzionano con DynamoDB

Molti SDK AWS forniscono un’interfaccia documentale, che consente di eseguire operazioni del piano dati (creazione, lettura, aggiornamento, eliminazione) su tabelle e indici. Con un’interfaccia documentale, non è necessario specificare Descrittori del tipo di dati. I tipi di dati sono impliciti nella semantica dei dati stessi. Questi SDK AWS forniscono anche metodi per convertire facilmente documenti JSON da e verso tipi di dati nativi di Amazon DynamoDB.

Nota

Le interfacce documentali sono disponibili negli SDK AWS per Java, .NET, Node.js e negli SDK per JavaScript.

Il seguente programma Java utilizza l’interfaccia documentale di AWS SDK per Java. Il programma crea un oggetto Table che rappresenta la tabella Music e quindi chiede all'oggetto di utilizzare GetItem per recuperare una canzone. Il programma restituisce quindi l'anno in cui è uscita la canzone.

La classe software.amazon.dynamodb.document.DynamoDB implementa l'interfaccia di documento di DynamoDB. Notare come DynamoDB funge da wrapper per il client di basso livello (AmazonDynamoDB).

package com.amazonaws.codesamples.gsg; import software.amazon.dynamodb.AmazonDynamoDB; import software.amazon.dynamodb.AmazonDynamoDBClientBuilder; import software.amazon.dynamodb.document.DynamoDB; import software.amazon.dynamodb.document.GetItemOutcome; import software.amazon.dynamodb.document.Table; public class MusicDocumentDemo { public static void main(String[] args) { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); DynamoDB docClient = new DynamoDB(client); Table table = docClient.getTable("Music"); GetItemOutcome outcome = table.getItemOutcome( "Artist", "No One You Know", "SongTitle", "Call Me Today"); int year = outcome.getItem().getInt("Year"); System.out.println("The song was released in " + year); } }

Interfacce di persistenza degli oggetti che funzionano con DynamoDB

Alcuni SDK AWS forniscono un'interfaccia di persistenza degli oggetti in cui non si eseguono direttamente operazioni del piano dati. Invece, è possibile creare oggetti che rappresentano elementi nelle tabelle e negli indici di Amazon DynamoDB e interagire solo con quegli oggetti. Ciò consente di scrivere codice incentrato sugli oggetti piuttosto che codice incentrato sul database.

Nota

Le interfacce di persistenza degli oggetti sono disponibili negli SDK per Java e .NET di AWS. Per ulteriori informazioni, consulta Interfacce di programmazione di livello superiore per DynamoDB per Dynamo DB.

import com.example.dynamodb.Customer; 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.GetItemEnhancedRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import com.example.dynamodb.Customer; 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.GetItemEnhancedRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; /* * 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. Be sure one of the id values is `id101` * - custName - the customer name * - email - the email value * - registrationDate - an instant value when the item was added to the table. These values * need to be in the form of `YYYY-MM-DDTHH:mm:ssZ`, such as 2022-07-11T00:00:00Z * * 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 EnhancedGetItem { 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(); getItem(enhancedClient); ddb.close(); } public static String getItem(DynamoDbEnhancedClient enhancedClient) { Customer result = null; try { DynamoDbTable<Customer> table = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); Key key = Key.builder() .partitionValue("id101").sortValue("tred@noserver.com") .build(); // Get the item by using the key. result = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); System.out.println("******* The description value is " + result.getCustName()); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } return result.getCustName(); } }