Interfacce programmatiche che funzionano con DynamoDB - Amazon DynamoDB

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à.

Interfacce programmatiche che funzionano con DynamoDB

Ognuno AWS SDKfornisce 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 disponibili variano a seconda del linguaggio di programmazione AWS SDK utilizzato.

Interfacce programmatiche disponibili in diverse versioni AWS SDKs per lavorare con DynamoDB.

Nella sezione seguente sono descritte alcune delle interfacce disponibili con AWS SDK for Java come esempio (Non tutte le interfacce sono disponibili in tutte.) AWS SDKs

Interfacce di basso livello che funzionano con DynamoDB

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

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 AWS SDK è disponibile in ogni lingua specifica.

Il seguente programma Java utilizza l'interfaccia di basso livello di AWS SDK for 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 compatibili con DynamoDB

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

Il seguente programma Java utilizza l'interfaccia documento di AWS SDK for 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 com.amazonaws.services.dynamodbv2.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 com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.GetItemOutcome; import com.amazonaws.services.dynamodbv2.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

Alcune AWS SDKs forniscono un'interfaccia di persistenza degli oggetti in cui non si eseguono direttamente operazioni sul 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 in Java AWS SDKs e. NET. 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(); } }