- AWS Code Sample demonstrates how to retrieve an item from an Amazon DynamoDB table.

/* Copyright, Inc. or its affiliates. All Rights Reserved. This file is licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.dynamodb; import; import; import; import; import; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Gets an item from an Amazon DynamoDB table * * This code expects that you have AWS credentials set up, as described here: * */ public class GetItem { public static void main(String[] args) { final String USAGE = "\n" + "Usage:\n" + " GetItem <table> <key> <keyVal>\n\n" + "Where:\n" + " table - the table from which an item is retrieved (i.e., Music3)\n" + " key - the key used in the table (i.e., Artist) \n" + " keyval - the key value that represents the item to get (i.e., Famous Band)\n" + " Example:\n" + " Music3 Artist Famous Band\n" + " **Warning** This program will actually retrieve an item\n" + " that you specify!\n"; 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); // Create the DynamoDbClient object Region region = Region.US_WEST_2; DynamoDbClient ddb = DynamoDbClient.builder().region(region).build(); getDynamoDBItem(ddb, tableName, key, keyVal); } 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()); // Create a GetItemRequest object 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("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); } } }

Sample Details

Service: Amazon DynamoDB

Last tested: 2/5/2020

Author: scmacdon - aws

Type: full-example