Uso de elementos en DynamoDB - AWS SDK for Java 2.x

Uso de elementos en DynamoDB

En DynamoDB, un elemento es una colección de atributos, cada uno de los cuales tiene un nombre y un valor. Los valores de los atributos pueden ser escalares, conjuntos o tipos de documentos. Para obtener más información, consulte Reglas de nomenclatura y tipos de datos en la Guía para desarrolladores de Amazon DynamoDB.

Recuperar (obtener) un elemento de una tabla

Llame al método getItem de DynamoDbClient y pase un objeto GetItemRequest con el nombre de la tabla y el valor de clave principal del elemento que desee. Este método devuelve un objeto GetItemResponse con todos los atributos de dicho elemento. Puede especificar una o varias expresiones de proyección en GetItemRequest para recuperar atributos específicos.

Puede utilizar el método item() del objeto GetItemResponse para recuperar un mapa de pares de clave (cadena) y valor (AttributeValue) asociados al elemento.

Importaciones

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;

Código de

public static void getDynamoDBItem(DynamoDbClient ddb,String tableName,String key,String keyVal ) { HashMap<String,AttributeValue> keyToGet = new HashMap<String,AttributeValue>(); keyToGet.put(key, AttributeValue.builder() .s(keyVal).build()); GetItemRequest request = GetItemRequest.builder() .key(keyToGet) .tableName(tableName) .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", key); } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } }

Consulte el ejemplo completo en GitHub.

Recuperar (obtener) un elemento de una tabla usando el cliente asíncrono

Invoque el método getItem del DynamoDbAsyncClient y pásele un objeto GetItemRequest con el nombre de la tabla y el valor de la clave principal del elemento que desee.

Puede devolver una instancia de recopilación con todos los atributos de ese elemento (consulte el siguiente ejemplo).

Importaciones

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;

Código de

public static void getItem(DynamoDbAsyncClient client, String tableName, String key, String keyVal) { HashMap<String, AttributeValue> keyToGet = new HashMap<String, AttributeValue>(); keyToGet.put(key, AttributeValue.builder() .s(keyVal).build()); try { // Create a GetItemRequest instance GetItemRequest request = GetItemRequest.builder() .key(keyToGet) .tableName(tableName) .build(); // Invoke the DynamoDbAsyncClient object's getItem java.util.Collection<AttributeValue> returnedItem = client.getItem(request).join().item().values(); // Convert Set to Map Map<String, AttributeValue> map = returnedItem.stream().collect(Collectors.toMap(AttributeValue::s, s->s)); Set<String> keys = map.keySet(); for (String sinKey : keys) { System.out.format("%s: %s\n", sinKey, map.get(sinKey).toString()); } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); }

Consulte el ejemplo completo en GitHub.

Agregar un nuevo elemento a una tabla

Cree un mapa de pares de clave-valor que represente los atributos del elemento. Estos deben incluir valores para los campos de la clave principal de la tabla. Si el elemento identificado por la clave principal ya existe, la solicitud actualiza sus campos.

nota

Si la tabla designada no existe para su cuenta y región, se produce una excepción ResourceNotFoundException.

Importaciones

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.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import java.util.HashMap;

Código de

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<String,AttributeValue>(); // Add all content to the table 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 { ddb.putItem(request); System.out.println(tableName +" was successfully updated"); } 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); } }

Consulte el ejemplo completo en GitHub.

Actualizar un elemento existente en una tabla

Puede actualizar un atributo de un elemento que ya existe en una tabla mediante el método updateItem de DynamoDbClient, proporcionando el nombre de la tabla, el valor de clave principal y un mapa de los campos que se van a actualizar.

nota

Si la tabla designada no existe para su cuenta y región o si el elemento identificado por la clave principal que ha pasado no existe, se produce una excepción ResourceNotFoundException.

Importaciones

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.ResourceNotFoundException; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import java.util.HashMap;

Código de

public static void updateTableItem(DynamoDbClient ddb, String tableName, String key, String keyVal, String name, String updateVal){ HashMap<String,AttributeValue> itemKey = new HashMap<String,AttributeValue>(); itemKey.put(key, AttributeValue.builder().s(keyVal).build()); HashMap<String,AttributeValueUpdate> updatedValues = new HashMap<String,AttributeValueUpdate>(); // Update the column specified by name with updatedVal 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 (ResourceNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Done!"); }

Consulte el ejemplo completo en GitHub.

Eliminar un elemento existente en una tabla

Puede eliminar un elemento que existe en una tabla utilizando el método deleteItem de DynamoDbClient y proporcionando un nombre de tabla, así como el valor de clave principal.

nota

Si la tabla designada no existe para su cuenta y región o si el elemento identificado por la clave principal que ha pasado no existe, se produce una excepción ResourceNotFoundException.

Importaciones

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;

Código de

public static void deleteDynamoDBItem(DynamoDbClient ddb, String tableName, String key, String keyVal) { HashMap<String,AttributeValue> keyToGet = new HashMap<String,AttributeValue>(); 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); } }

Consulte el ejemplo completo en GitHub.

Más información