Étape 3 : lire des données à partir d'une table - Amazon DynamoDB

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Étape 3 : lire des données à partir d'une table

Au cours de cette étape, vous allez relire l'un des éléments que vous avez créés dansÉtape 2 : Écrire des données dans une table. Vous pouvez utiliser la console DynamoDB ou AWS CLI pour lire un élément du Music tableau en spécifiant Artist etSongTitle.

Pour plus d'informations sur les opérations de lecture dans DynamoDB, consultez Lecture d'un élément.

Suivez ces étapes pour lire des données de la table Music à l'aide de la console DynamoDB.

  1. Ouvrez la console DynamoDB à l'adresse. https://console.aws.amazon.com/dynamodb/

  2. Dans le volet de navigation de gauche, choisissez Tables.

  3. Sur la page Tables, choisissez la table musicale.

  4. Sélectionnez Explore table items (Explorer les éléments de la table).

  5. Dans la section Articles renvoyés, consultez la liste des éléments stockés dans le tableau, triés par Artist etSongTitle. Le premier élément de la liste est celui avec l'artiste Acme Band et les SongTitlePartiQL Rocks.

Procédez comme suit : AWS CLI l'exemple lit un élément duMusic. Vous pouvez le faire via API DynamoDB ou partiQLSQL, un langage de requête compatible pour DynamoDB.

DynamoDB API
Note

Le comportement par défaut pour DynamoDB est la lecture éventuellement cohérente. Le paramètre consistent-read est utilisé ci-dessous pour illustrer des lectures cohérentes fortes.

Linux

aws dynamodb get-item --consistent-read \ --table-name Music \ --key '{ "Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}}'

Fenêtres CMD

aws dynamodb get-item --consistent-read ^ --table-name Music ^ --key "{\"Artist\": {\"S\": \"Acme Band\"}, \"SongTitle\": {\"S\": \"Happy Day\"}}"

L'utilisation de get-item renvoie l'exemple de résultat suivant.

{ "Item": { "AlbumTitle": { "S": "Songs About Life" }, "Awards": { "S": "10" }, "Artist": { "S": "Acme Band" }, "SongTitle": { "S": "Happy Day" } } }
PartiQL for DynamoDB

Linux

aws dynamodb execute-statement --statement "SELECT * FROM Music \ WHERE Artist='Acme Band' AND SongTitle='Happy Day'"

Fenêtres CMD

aws dynamodb execute-statement --statement "SELECT * FROM Music WHERE Artist='Acme Band' AND SongTitle='Happy Day'"

L'utilisation de l'instruction PartiQL Select renvoie l'exemple de résultat suivant.

{ "Items": [ { "AlbumTitle": { "S": "Songs About Life" }, "Awards": { "S": "10" }, "Artist": { "S": "Acme Band" }, "SongTitle": { "S": "Happy Day" } } ] }

Pour plus d'informations sur la lecture de données avec PartiQL, consultez Instructions de sélection de PartiQL.

Les exemples de code suivants montrent comment lire un élément d'une table DynamoDB à l'aide d'un AWS SDK.

.NET
AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

/// <summary> /// Gets information about an existing movie from the table. /// </summary> /// <param name="client">An initialized Amazon DynamoDB client object.</param> /// <param name="newMovie">A Movie object containing information about /// the movie to retrieve.</param> /// <param name="tableName">The name of the table containing the movie.</param> /// <returns>A Dictionary object containing information about the item /// retrieved.</returns> public static async Task<Dictionary<string, AttributeValue>> GetItemAsync(AmazonDynamoDBClient client, Movie newMovie, string tableName) { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var request = new GetItemRequest { Key = key, TableName = tableName, }; var response = await client.GetItemAsync(request); return response.Item; }
  • Pour API plus de détails, voir GetItemAWS SDK for .NET APIRéférence.

Bash
AWS CLI avec le script Bash
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

############################################################################# # function dynamodb_get_item # # This function gets an item from a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -k keys -- Path to json file containing the keys that identify the item to get. # [-q query] -- Optional JMESPath query expression. # # Returns: # The item as text output. # And: # 0 - If successful. # 1 - If it fails. ############################################################################ function dynamodb_get_item() { local table_name keys query response local option OPTARG # Required to use getopts command in a function. # ###################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_get_item" echo "Get an item from a DynamoDB table." echo " -n table_name -- The name of the table." echo " -k keys -- Path to json file containing the keys that identify the item to get." echo " [-q query] -- Optional JMESPath query expression." echo "" } query="" while getopts "n:k:q:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; k) keys="${OPTARG}" ;; q) query="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$keys" ]]; then errecho "ERROR: You must provide a keys json file path the -k parameter." usage return 1 fi if [[ -n "$query" ]]; then response=$(aws dynamodb get-item \ --table-name "$table_name" \ --key file://"$keys" \ --output text \ --query "$query") else response=$( aws dynamodb get-item \ --table-name "$table_name" \ --key file://"$keys" \ --output text ) fi local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports get-item operation failed.$response" return 1 fi if [[ -n "$query" ]]; then echo "$response" | sed "/^\t/s/\t//1" # Remove initial tab that the JMSEPath query inserts on some strings. else echo "$response" fi return 0 }

Fonctions utilitaires utilisées dans cet exemple.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • Pour API plus de détails, voir GetItemAWS CLI Référence de commande.

C++
SDKpour C++
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

//! Get an item from an Amazon DynamoDB table. /*! \sa getItem() \param tableName: The table name. \param partitionKey: The partition key. \param partitionValue: The value for the partition key. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::DynamoDB::getItem(const Aws::String &tableName, const Aws::String &partitionKey, const Aws::String &partitionValue, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration); Aws::DynamoDB::Model::GetItemRequest request; // Set up the request. request.SetTableName(tableName); request.AddKey(partitionKey, Aws::DynamoDB::Model::AttributeValue().SetS(partitionValue)); // Retrieve the item's fields and values. const Aws::DynamoDB::Model::GetItemOutcome &outcome = dynamoClient.GetItem(request); if (outcome.IsSuccess()) { // Reference the retrieved fields/values. const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &item = outcome.GetResult().GetItem(); if (!item.empty()) { // 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 " << partitionKey << std::endl; } } else { std::cerr << "Failed to get item: " << outcome.GetError().GetMessage(); } return outcome.IsSuccess(); }
  • Pour API plus de détails, voir GetItemAWS SDK for C++ APIRéférence.

CLI
AWS CLI

Exemple 1 : Pour lire un élément dans un tableau

L'get-itemexemple suivant extrait un élément du MusicCollection tableau. La table possède une clé hash-and-range primaire (ArtistetSongTitle), vous devez donc spécifier ces deux attributs. La commande demande également des informations sur la capacité de lecture consommée par l'opération.

aws dynamodb get-item \ --table-name MusicCollection \ --key file://key.json \ --return-consumed-capacity TOTAL

Contenu de key.json :

{ "Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"} }

Sortie :

{ "Item": { "AlbumTitle": { "S": "Songs About Life" }, "SongTitle": { "S": "Happy Day" }, "Artist": { "S": "Acme Band" } }, "ConsumedCapacity": { "TableName": "MusicCollection", "CapacityUnits": 0.5 } }

Pour plus d'informations, consultez Lire un article dans le guide du développeur Amazon DynamoDB.

Exemple 2 : Pour lire un élément en utilisant une lecture cohérente

L'exemple suivant extrait un élément du MusicCollection tableau à l'aide de lectures très cohérentes.

aws dynamodb get-item \ --table-name MusicCollection \ --key file://key.json \ --consistent-read \ --return-consumed-capacity TOTAL

Contenu de key.json :

{ "Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"} }

Sortie :

{ "Item": { "AlbumTitle": { "S": "Songs About Life" }, "SongTitle": { "S": "Happy Day" }, "Artist": { "S": "Acme Band" } }, "ConsumedCapacity": { "TableName": "MusicCollection", "CapacityUnits": 1.0 } }

Pour plus d'informations, consultez Lire un article dans le guide du développeur Amazon DynamoDB.

Exemple 3 : Pour récupérer les attributs spécifiques d'un article

L'exemple suivant utilise une expression de projection pour récupérer uniquement trois attributs de l'élément souhaité.

aws dynamodb get-item \ --table-name ProductCatalog \ --key '{"Id": {"N": "102"}}' \ --projection-expression "#T, #C, #P" \ --expression-attribute-names file://names.json

Contenu de names.json :

{ "#T": "Title", "#C": "ProductCategory", "#P": "Price" }

Sortie :

{ "Item": { "Price": { "N": "20" }, "Title": { "S": "Book 102 Title" }, "ProductCategory": { "S": "Book" } } }

Pour plus d'informations, consultez Lire un article dans le guide du développeur Amazon DynamoDB.

  • Pour API plus de détails, voir GetItemAWS CLI Référence de commande.

Go
SDKpour Go V2
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

// 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 } // Movie encapsulates data about a movie. Title and Year are the composite primary key // of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key, // and Info is additional data. type Movie struct { Title string `dynamodbav:"title"` Year int `dynamodbav:"year"` Info map[string]interface{} `dynamodbav:"info"` } // GetKey returns the composite primary key of the movie in a format that can be // sent to DynamoDB. func (movie Movie) GetKey() map[string]types.AttributeValue { title, err := attributevalue.Marshal(movie.Title) if err != nil { panic(err) } year, err := attributevalue.Marshal(movie.Year) if err != nil { panic(err) } return map[string]types.AttributeValue{"title": title, "year": year} } // String returns the title, year, rating, and plot of a movie, formatted for the example. func (movie Movie) String() string { return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n", movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"]) }
  • Pour API plus de détails, voir GetItemAWS SDK for Go APIRéférence.

Java
SDKpour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

Récupère un élément d'une table à l'aide du DynamoDbClient.

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); } } }
  • Pour API plus de détails, voir GetItemAWS SDK for Java 2.x APIRéférence.

JavaScript
SDKpour JavaScript (v3)
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

Cet exemple utilise le client de document pour simplifier l'utilisation d'éléments dans DynamoDB. Pour API plus de détails, voir GetCommand.

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, GetCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new GetCommand({ TableName: "AngryAnimals", Key: { CommonName: "Shoebill", }, }); const response = await docClient.send(command); console.log(response); return response; };
  • Pour API plus de détails, voir GetItemAWS SDK for JavaScript APIRéférence.

SDKpour JavaScript (v2)
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

Obtenir un élément d'une table

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

Obtenez un élément d'une table à l'aide du client de document 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
SDKpour Kotlin
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

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) } } }
  • Pour API plus de détails, voir GetItemAWS SDKpour API référence à Kotlin.

PHP
SDK pour PHP
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

$movie = $service->getItemByKey($tableName, $key); echo "\nThe movie {$movie['Item']['title']['S']} was released in {$movie['Item']['year']['N']}.\n"; public function getItemByKey(string $tableName, array $key) { return $this->dynamoDbClient->getItem([ 'Key' => $key['Item'], 'TableName' => $tableName, ]); }
  • Pour API plus de détails, voir GetItemAWS SDK for PHP APIRéférence.

PowerShell
Outils pour PowerShell

Exemple 1 : renvoie l'élément DynamoDB avec la clé de partition et la SongTitle clé de tri Artist.

$key = @{ SongTitle = 'Somewhere Down The Road' Artist = 'No One You Know' } | ConvertTo-DDBItem Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem

Sortie :

Name Value ---- ----- Genre Country SongTitle Somewhere Down The Road Price 1.94 Artist No One You Know CriticRating 9 AlbumTitle Somewhat Famous
  • Pour API plus de détails, voir GetItemAWS Tools for PowerShell Référence de l'applet de commande.

Python
SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

class Movies: """Encapsulates an Amazon DynamoDB table of movie data. Example data structure for a movie record in this table: { "year": 1999, "title": "For Love of the Game", "info": { "directors": ["Sam Raimi"], "release_date": "1999-09-15T00:00:00Z", "rating": 6.3, "plot": "A washed up pitcher flashes through his career.", "rank": 4987, "running_time_secs": 8220, "actors": [ "Kevin Costner", "Kelly Preston", "John C. Reilly" ] } } """ def __init__(self, dyn_resource): """ :param dyn_resource: A Boto3 DynamoDB resource. """ self.dyn_resource = dyn_resource # The table variable is set during the scenario in the call to # 'exists' if the table exists. Otherwise, it is set by 'create_table'. 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"]
  • Pour API plus de détails, voir GetItemAWS SDKpour Python (Boto3) Reference. API

Ruby
SDKpour Ruby
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

class DynamoDBBasics attr_reader :dynamo_resource attr_reader :table def initialize(table_name) client = Aws::DynamoDB::Client.new(region: "us-east-1") @dynamo_resource = Aws::DynamoDB::Resource.new(client: client) @table = @dynamo_resource.table(table_name) end # 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_item(title, year) @table.get_item(key: {"year" => year, "title" => title}) rescue Aws::DynamoDB::Errors::ServiceError => e puts("Couldn't get movie #{title} (#{year}) from table #{@table.name}:\n") puts("\t#{e.code}: #{e.message}") raise end
  • Pour API plus de détails, voir GetItemAWS SDK for Ruby APIRéférence.

SAP ABAP
SDKpour SAP ABAP
Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

TRY. oo_item = lo_dyn->getitem( iv_tablename = iv_table_name it_key = it_key ). DATA(lt_attr) = oo_item->get_item( ). DATA(lo_title) = lt_attr[ key = 'title' ]-value. DATA(lo_year) = lt_attr[ key = 'year' ]-value. DATA(lo_rating) = lt_attr[ key = 'rating' ]-value. MESSAGE 'Movie name is: ' && lo_title->get_s( ) && 'Movie year is: ' && lo_year->get_n( ) && 'Moving rating is: ' && lo_rating->get_n( ) TYPE 'I'. CATCH /aws1/cx_dynresourcenotfoundex. MESSAGE 'The table or index does not exist' TYPE 'E'. ENDTRY.
  • Pour API plus de détails, voir GetItemAWS SDKà titre SAP ABAP API de référence.

Swift
SDKpour Swift
Note

Il s'agit de la documentation d'avant-première d'une SDK version préliminaire. Elle est susceptible d’être modifiée.

Note

Il y en a plus à ce sujet GitHub. Consultez l'exemple complet et apprenez à configurer et à exécuter dans AWS Référentiel d'exemples de code.

import AWSDynamoDB /// Return a `Movie` record describing the specified movie from the Amazon /// DynamoDB table. /// /// - Parameters: /// - title: The movie's title (`String`). /// - year: The movie's release year (`Int`). /// /// - Throws: `MoviesError.ItemNotFound` if the movie isn't in the table. /// /// - Returns: A `Movie` record with the movie's details. func get(title: String, year: Int) async throws -> Movie { guard let client = self.ddbClient else { throw MoviesError.UninitializedClient } let input = GetItemInput( key: [ "year": .n(String(year)), "title": .s(title) ], tableName: self.tableName ) let output = try await client.getItem(input: input) guard let item = output.item else { throw MoviesError.ItemNotFound } let movie = try Movie(withItem: item) return movie }
  • Pour API plus de détails, voir GetItemAWS SDKpour API référence à Swift.

Pour obtenir plus d'exemples avec DynamoDB, consultez Exemples de code pour DynamoDB utilisant AWS SDKs.

Pour mettre à jour les données dans votre table, passez à l' Étape 4 : mettre à jour des données dans une table.