使用 Amazon SDK 从 DynamoDB 表中获取项目 - Amazon DynamoDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon SDK 从 DynamoDB 表中获取项目

以下代码示例显示如何从 DynamoDB 表中获取项目。

C++
适用于 C++ 的 SDK
提示

要了解如何设置和运行此示例,请参阅 GitHub

Aws::Client::ClientConfiguration clientConfig; Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfig); Aws::DynamoDB::Model::GetItemRequest req; // Set up the request. req.SetTableName(table); Aws::DynamoDB::Model::AttributeValue hashKey; hashKey.SetS(keyval); req.AddKey(key, hashKey); // Retrieve the item's fields and values const Aws::DynamoDB::Model::GetItemOutcome& result = dynamoClient.GetItem(req); if (result.IsSuccess()) { // Reference the retrieved fields/values. const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>& item = result.GetResult().GetItem(); if (item.size() > 0) { // Output each retrieved field and its value. for (const auto& i : item) std::cout << "Values: " << i.first << ": " << i.second.GetS() << std::endl; } else { std::cout << "No item found with the key " << key << std::endl; } } else { std::cout << "Failed to get item: " << result.GetError().GetMessage(); }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 GetItem

Go
SDK for Go V2
提示

要了解如何设置和运行此示例,请参阅 GitHub

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples. // It contains a DynamoDB service client that is used to act on the specified table. type TableBasics struct { DynamoDbClient *dynamodb.Client TableName string } // GetMovie gets movie data from the DynamoDB table by using the primary composite key // made of title and year. func (basics TableBasics) GetMovie(title string, year int) (Movie, error) { movie := Movie{Title: title, Year: year} response, err := basics.DynamoDbClient.GetItem(context.TODO(), &dynamodb.GetItemInput{ Key: movie.GetKey(), TableName: aws.String(basics.TableName), }) if err != nil { log.Printf("Couldn't get info about %v. Here's why: %v\n", title, err) } else { err = attributevalue.UnmarshalMap(response.Item, &movie) if err != nil { log.Printf("Couldn't unmarshal response. Here's why: %v\n", err) } } return movie, err }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 GetItem

Java
SDK for Java 2.x
提示

要了解如何设置和运行此示例,请参阅 GitHub

使用 DynamoDbClient 从表中获取项目。

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; }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 GetItem

JavaScript
SDK for JavaScript V3
提示

要了解如何设置和运行此示例,请参阅 GitHub

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "REGION"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建 DynamoDB 文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

从表中获取项目。

import { GetCommand } from "@aws-sdk/lib-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; // Set the parameters. export const params = { TableName: "TABLE_NAME", Key: { primaryKey: "VALUE_1", sortKey: "VALUE_2", }, }; export const getItem = async () => { try { const data = await ddbDocClient.send(new GetCommand(params)); console.log("Success :", data.Item); } catch (err) { console.log("Error", err); } }; getItem();

使用 PartiQL 从表中获取项目。

// Import required AWS SDK clients and commands for Node.js. import { ExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient"; const tableName = process.argv[2]; const movieTitle1 = process.argv[3]; export const run = async (tableName, movieTitle1) => { const params = { Statement: "SELECT * FROM " + tableName + " where title=?", Parameters: [{ S: movieTitle1 }], }; try { const data = await ddbDocClient.send(new ExecuteStatementCommand(params)); for (let i = 0; i < data.Items.length; i++) { console.log( "Success. The query return the following data. Item " + i, data.Items[i].year, data.Items[i].title, data.Items[i].info ); } return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieTitle1);

使用 PartiQL 从表中批量获取项目。

// Import required AWS SDK clients and commands for Node.js. import { BatchExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const movieYear2 = process.argv[5]; const movieTitle2 = process.argv[6]; export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2 ) => { const params = { Statements: [ { Statement: "SELECT * FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }, { Statement: "SELECT * FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle2 }, { N: movieYear2 }], }, ], }; try { const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); for (let i = 0; i < data.Responses.length; i++) { console.log(data.Responses[i].Item.year); console.log(data.Responses[i].Item.title); } return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1, movieYear2, movieTitle2);
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 GetItem

SDK for JavaScript V2
提示

要了解如何设置和运行此示例,请参阅 GitHub

从表中获取项目。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); var params = { TableName: 'TABLE', Key: { 'KEY_NAME': {N: '001'} }, ProjectionExpression: 'ATTRIBUTE_NAME' }; // Call DynamoDB to read the item from the table ddb.getItem(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Item); } });

使用 DynamoDB 文档客户端从表中获取项目。

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); var params = { TableName: 'EPISODES_TABLE', Key: {'KEY_NAME': VALUE} }; docClient.get(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Item); } });
Kotlin
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

提示

要了解如何设置和运行此示例,请参阅 GitHub

suspend fun getSpecificItem(tableNameVal: String, keyName: String, keyVal: String) { val keyToGet = mutableMapOf<String, AttributeValue>() keyToGet[keyName] = AttributeValue.S(keyVal) val request = GetItemRequest { key = keyToGet tableName = tableNameVal } DynamoDbClient { region = "us-east-1" }.use { ddb -> val returnedItem = ddb.getItem(request) val numbersMap = returnedItem.item numbersMap?.forEach { key1 -> println(key1.key) println(key1.value) } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 GetItem

Python
适用于 Python (Boto3) 的 SDK
提示

要了解如何设置和运行此示例,请参阅 GitHub

class Movies: """Encapsulates an Amazon DynamoDB table of movie data.""" def __init__(self, dyn_resource): """ :param dyn_resource: A Boto3 DynamoDB resource. """ self.dyn_resource = dyn_resource self.table = None def get_movie(self, title, year): """ Gets movie data from the table for a specific movie. :param title: The title of the movie. :param year: The release year of the movie. :return: The data about the requested movie. """ try: response = self.table.get_item(Key={'year': year, 'title': title}) except ClientError as err: logger.error( "Couldn't get movie %s from table %s. Here's why: %s: %s", title, self.table.name, err.response['Error']['Code'], err.response['Error']['Message']) raise else: return response['Item']
  • 有关 API 详细信息,请参阅《适用于 Python (Boto3) 的 Amazon SDK API 参考》中的 GetItem

Ruby
SDK for Ruby
提示

要了解如何设置和运行此示例,请参阅 GitHub

# Gets movie data from the table for a specific movie. # # @param title [String] The title of the movie. # @param year [Integer] The release year of the movie. # @return [Hash] The data about the requested movie. def get_movie(title, year) response = @table.get_item(key: {"year" => year, "title" => title}) rescue Aws::Errors::ServiceError => e puts("Couldn't get movie #{title} from table #{@table.name}. Here's why:") puts("\t#{e.code}: #{e.message}") raise else response.item end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 GetItem

有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 结合使用 DynamoDB 与 Amazon SDK。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。