

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.

# Mise en route avec DynamoDB
<a name="GettingStartedDynamoDB"></a>

Vous apprendrez à vous connecter aux tables DynamoDB, à les créer et à les gérer dans les sections suivantes.

Avant de commencer, nous vous recommandons de vous familiariser avec les concepts de base d’Amazon DynamoDB. Vous pouvez obtenir un aperçu rapide dans [Qu’est-ce qu’Amazon DynamoDB ?](Introduction.md) et un examen plus approfondi dans [Composants de base d’Amazon DynamoDB](HowItWorks.CoreComponents.md). Passez ensuite aux [prérequis](#GettingStarted.SettingUp.DynamoWebService).

**Note**  
[Lorsque vous vous inscrivez AWS, vous pouvez commencer à utiliser DynamoDB en utilisant AWS le niveau gratuit.](https://aws.amazon.com/free/) Si vous n’avez pas encore profité de tous les avantages de l’offre gratuite pour Amazon DynamoDB, l’exécution des exemples de cette section ne vous coûtera rien. Sinon, vous devrez payer les frais d’utilisation DynamoDB standard à partir du moment où vous créez les tables et jusqu’à ce que vous les supprimiez.  
Si vous ne voulez pas vous inscrire à un compte gratuit, vous pouvez configurer [DynamoDB local (version téléchargeable)](DynamoDBLocal.md) sur votre ordinateur. La version téléchargeable vous permet de développer et de tester des applications localement sans créer de AWS compte ni accéder au service Web DynamoDB.

**Topics**
+ [Ressources Amazon DynamoDB pour les nouveaux utilisateurs](dynamodb-resources-first-time-users.md)
+ [Accès à DynamoDB](AccessingDynamoDB.md)
+ [Conditions préalables](#GettingStarted.SettingUp.DynamoWebService)
+ [Configuration de DynamoDB](SettingUp.md)
+ [Étape 1 : création d’une table dans DynamoDB](getting-started-step-1.md)
+ [Étape 2 : écrire des données dans une table DynamoDB](getting-started-step-2.md)
+ [Étape 3 : lire des données à partir d’une table DynamoDB](getting-started-step-3.md)
+ [Étape 4 : mettre à jour des données dans une table DynamoDB](getting-started-step-4.md)
+ [Étape 5 : interroger des données dans une table DynamoDB](getting-started-step-5.md)
+ [Étape 6 : (Facultatif) supprimer votre table DynamoDB pour nettoyer les ressources](getting-started-step-6.md)
+ [Poursuivre l’apprentissage concernant DynamoDB](getting-started-NextSteps.md)
+ [Générez du code d'infrastructure pour Amazon DynamoDB à l'aide de Console-to-Code](console-to-code.md)

# Ressources Amazon DynamoDB pour les nouveaux utilisateurs
<a name="dynamodb-resources-first-time-users"></a>

Si vous êtes un nouvel utilisateur, nous vous conseillons de commencer par lire les sections suivantes et de vous y référer dès que vous en avez besoin :


|  |  | 
| --- |--- |
|  

**Example**  
**[Points forts du service et prix](https://aws.amazon.com/dynamodb/)**  
Fournit une présentation générale du produit DynamoDB, des cas d'utilisation courants, des points forts des services et des tarifs.  |  

**Example**  
**[Ressources DynamoDB](https://aws.amazon.com/dynamodb/resources/)**  
Des vidéos, des didacticiels et des conseils prescriptifs qui vous présentent le service, les concepts de modélisation des données et les fonctionnalités et fonctionnalités de base.  | 
|  

**Example**  
**[Premiers pas](GettingStartedDynamoDB.md)**  
Informations sur la configuration de DynamoDB, la création d'exemples de tables et le téléchargement de données.  |  

**Example**  
**[Cours de base de DynamoDB](https://explore.skillbuilder.aws/learn/course/external/view/elearning/16104/amazon-dynamodb-basics)**  
Cours numérique gratuit qui enseigne les principes fondamentaux de DynamoDB, notamment la conception des tables, les types de données et les opérations de base.  | 
|  

**Example**  
**[Nuggets DynamoDB](https://www.youtube.com/playlist?list=PLhr1KZpdzukemNOO71Hca0GpjG0QmXwEd)**  
Des didacticiels vidéo courts et ciblés qui expliquent les principaux concepts et fonctionnalités de DynamoDB.  |  

**Example**  
**[Référentiel d'exemples de code DynamoDB](https://github.com/aws-samples/aws-dynamodb-examples)**  
Exemples pratiques de code DynamoDB dans différents langages de programmation.  | 
|  

**Example**  
**[Formation DynamoDB gratuite](https://skillbuilder.aws/learn/WC3K4Y4S5N/amazon-dynamodb-getting-started/)**  
AWS propose des cours de formation numériques gratuits qui abordent les concepts, les fonctionnalités et les meilleures pratiques de DynamoDB.  |  

**Example**  
**[NoSQL Workbench pour DynamoDB](https://youtu.be/p5va6ZX9_o0)**  
Outil visuel unifié qui fournit des fonctionnalités de modélisation des données, de visualisation des données et de développement de requêtes.  | 
|  

**Example**  
**[Modèles de conception DynamoDB](best-practices.md)**  
Bonnes pratiques et exemples de modélisation des données pour différents cas d'utilisation avec des exemples de code pratiques.  |  

**Example**  
**[Tutoriels pratiques](https://aws.amazon.com/tutorials/create-nosql-table/)**  
Step-by-step des didacticiels AWS Management Console qui vous guident à travers les tâches courantes de DynamoDB.  | 
|  

**Example**  
**[Migration vers DynamoDB](migration-guide.md)**  
Présentation du processus, des outils et des stratégies de migration d'une base de données vers DynamoDB.  |  

**Example**  
**[AWS Objectif Well-Architected pour DynamoDB](bp-wal.md)**  
Bonnes pratiques architecturales pour concevoir et exploiter des applications fiables, sécurisées, efficaces et économiques à l'aide de DynamoDB.  | 

## Meilleures pratiques supplémentaires d’Amazon DynamoDB pour les nouveaux utilisateurs
<a name="additional-reading"></a>

Une fois que vous avez terminé les sections précédentes, lisez les sections suivantes :
+  **[Capacité de débit DynamoDB](capacity-mode.md)** 

  Fournit une vue d’ensemble des deux modes de débit disponibles pour DynamoDB et explique comment sélectionner le mode de capacité approprié pour votre application. Le mode à la demande est l’option de débit par défaut et recommandée pour la plupart des charges de travail DynamoDB.
+  **[Bonnes pratiques de conception et d’architecture avec DynamoDB](best-practices.md)** 

  Identifiez et résolvez les problèmes afin d’optimiser les performances et de minimiser les coûts lorsque vous travaillez avec DynamoDB.

## AWS CLI ressources
<a name="new-users-aws-cli-resources"></a>

Si vous souhaitez utiliser l'interface de ligne de AWS commande (AWS CLI), vous pouvez utiliser les documents suivants pour vous aider à démarrer :
+  **Documentation [AWS CLI](https://docs.aws.amazon.com/cli/)** 

   Cette section fournit des informations sur le téléchargement AWS CLI, le AWS CLI fonctionnement de votre système et la fourniture de vos AWS informations d'identification. 
+  **[AWS CLI documentation pour DynamoDB](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/index.html)** 

   Ce document distinct couvre toutes les commandes DynamoDB, y compris la syntaxe et des exemples. AWS CLI 

## Ressources de programmation
<a name="new-user-programming-resources"></a>

Vous pouvez développer des applications pour utiliser l’API DynamoDB avec différents langages de programmation courants. Voici quelques ressources :
+  **[Outils pour Amazon Web Services](https://aws.amazon.com/developer/tools/)** 

   AWS fournit un certain nombre de kits de développement logiciel (SDKs) compatibles avec DynamoDB. Vous pouvez programmer pour DynamoDB en utilisant Java, .NET, PHP, Ruby, ainsi que d’autres langages. Ils SDKs peuvent considérablement simplifier le développement de vos applications en formatant vos demandes adressées à DynamoDB, en analysant les réponses, en fournissant une logique de nouvelle tentative et en gérant les erreurs. 
+  **[Référence de l’API DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/Welcome.html)**

   Si vous ne souhaitez pas utiliser le AWS SDKs, vous pouvez interagir avec DynamoDB directement à l'aide de l'API DynamoDB. Ce document couvre toutes les opérations de l’API DynamoDB, y compris leur syntaxe et des exemples. Cette section fournit des astuces de dépannage et des informations pour créer et authentifier les requêtes et la façon de gérer les réponses. 

# Accès à DynamoDB
<a name="AccessingDynamoDB"></a>

 Vous pouvez accéder à Amazon DynamoDB à l'aide de l'API DynamoDB, AWS Management Console de la AWS CLI() ou AWS Command Line Interface de l'API DynamoDB.

**Topics**
+ [Utilisation de la console](#ConsoleDynamoDB)
+ [À l'aide du AWS CLI](#Tools.CLI)
+ [Utilisation de l’API](#Using.API)
+ [Utilisation de NoSQL Workbench pour DynamoDB](#Using.Workbench)
+ [Plages d’adresses IP](#Using.IPRanges)
+ [Points de terminaison à double pile pour le protocole Internet version 6 () IPv6](#dual-stackipv4-6)

## Utilisation de la console
<a name="ConsoleDynamoDB"></a>

[Vous pouvez accéder au AWS Management Console pour Amazon https://console.aws.amazon.com/dynamodb/ DynamoDB depuis votre domicile.](https://console.aws.amazon.com/dynamodb/home)

Voici certaines des actions que vous pouvez effectuer dans la console DynamoDB :
+ **Gestion des tables** : créez, mettez à jour et supprimez des tables. Le calculateur de capacité peut vous aider à estimer vos besoins en capacité.
+ **Interaction avec les données** : consultez, ajoutez, mettez à jour et supprimez des éléments dans vos tables. Gérez les paramètres de durée de vie (TTL).
+ **Surveillance et analyse** : consultez les tableaux de bord, surveillez et configurez les alarmes et analysez les métriques et les alertes pour vos tables DynamoDB.
+ **Optimisation et extension** : gérez les index secondaires, les flux, les déclencheurs, la capacité réservée et les autres fonctionnalités avancées pour améliorer votre utilisation de DynamoDB.

La console DynamoDB fournit une interface complète vous permettant de gérer vos ressources DynamoDB. Nous vous encourageons à accéder à la console et à interagir avec elle pour en savoir plus.

## À l'aide du AWS CLI
<a name="Tools.CLI"></a>

 Vous pouvez utiliser le AWS Command Line Interface (AWS CLI) pour contrôler plusieurs AWS services à partir de la ligne de commande et les automatiser par le biais de scripts. Vous pouvez utiliser le AWS CLI pour des opérations ad hoc, telles que la création d'une table. Vous pouvez également l’utiliser pour incorporer des opérations Amazon DynamoDB au sein de scripts utilitaires.

 Avant de pouvoir utiliser le AWS CLI avec DynamoDB, vous devez obtenir un ID de clé d'accès et une clé d'accès secrète. Pour de plus amples informations, veuillez consulter [Accorder un accès par programmation](SettingUp.DynamoWebService.md#SettingUp.DynamoWebService.GetCredentials). 

[Pour obtenir la liste complète de toutes les commandes disponibles pour DynamoDB dans AWS CLI le, consultez AWS CLI la référence des commandes.](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/index.html)

**Topics**

### Téléchargement et configuration du AWS CLI
<a name="Tools.CLI.DownloadingAndRunning"></a>

 AWS CLI Il est disponible à l'[adresse http://aws.amazon.com/cli](https://aws.amazon.com/cli). Elle s’exécute sous Windows, macOS ou Linux. Après avoir téléchargé le AWS CLI, procédez comme suit pour l'installer et le configurer :

1. Accédez au [Guide de l’utilisateur AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/).

1. Suivez les instructions d’[Installation de l’ AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/installing.html) et de [Configuration de l’ AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html).

### Utilisation du AWS CLI avec DynamoDB
<a name="Tools.CLI.UsingWithDDB"></a>

Le format de ligne de commande se compose d’un nom d’opération DynamoDB, suivi des paramètres pour cette opération. Il AWS CLI prend en charge une syntaxe abrégée pour les valeurs des paramètres, ainsi que du JSON.

Par exemple, la commande suivante permet de créer une table nommée *Music*. La clé de partition est *Artist* et la clé de tri est *SongTitle*. (Pour une lecture plus facile, les commandes longues dans cette section sont divisées en plusieurs lignes).

```
aws dynamodb create-table \
    --table-name Music \
    --attribute-definitions \
        AttributeName=Artist,AttributeType=S \
        AttributeName=SongTitle,AttributeType=S \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --billing-mode PAY_PER_REQUEST \
    --table-class STANDARD
```

Les commandes suivantes permettent d’ajouter de nouveaux éléments à la table. Ces exemples utilisent une combinaison de la syntaxe raccourcie et de JSON.

```
aws dynamodb put-item \
    --table-name Music \
    --item \
        '{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}, "AlbumTitle": {"S": "Somewhat Famous"}}' \
    --return-consumed-capacity TOTAL

aws dynamodb put-item \
    --table-name Music \
    --item '{
        "Artist": {"S": "Acme Band"},
        "SongTitle": {"S": "Happy Day"},
        "AlbumTitle": {"S": "Songs About Life"} }' \
    --return-consumed-capacity TOTAL
```

Sur la ligne de commande, il peut être difficile de composer un JSON valide. Toutefois, l’ AWS CLI peut lire les fichiers JSON. Par exemple, imaginons l’extrait de code JSON suivant qui est stocké dans un fichier nommé *key-conditions.json*.

```
{
    "Artist": {
        "AttributeValueList": [
            {
                "S": "No One You Know"
            }
        ],
        "ComparisonOperator": "EQ"
    },
    "SongTitle": {
        "AttributeValueList": [
            {
                "S": "Call Me Today"
            }
        ],
        "ComparisonOperator": "EQ"
    }
}
```

Vous pouvez désormais émettre une demande de `Query` à l’aide de l’ AWS CLI. Dans cet exemple, le contenu du fichier *key-conditions.json* est utilisé pour le paramètre `--key-conditions`.

```
aws dynamodb query --table-name Music --key-conditions file://key-conditions.json
```

### Utilisation du AWS CLI avec DynamoDB local
<a name="Tools.CLI.UsingWithDDBLocal"></a>

Ils AWS CLI peuvent également interagir avec DynamoDB local (version téléchargeable) qui s'exécute sur votre ordinateur. Pour ce faire, ajoutez le paramètre suivant pour chaque commande :

`--endpoint-url http://localhost:8000`

L'exemple suivant utilise le AWS CLI pour répertorier les tables d'une base de données locale.

```
aws dynamodb list-tables --endpoint-url http://localhost:8000
```

Si DynamoDB utilise un numéro de port autre que la valeur par défaut (8000), modifiez la valeur `--endpoint-url` en conséquence.

**Note**  
Impossible AWS CLI d'utiliser le DynamoDB local (version téléchargeable) comme point de terminaison par défaut. Par conséquent, vous devez spécifier `--endpoint-url` avec chaque commande. 

## Utilisation de l’API
<a name="Using.API"></a>

 Vous pouvez utiliser le AWS Management Console et le AWS Command Line Interface pour travailler de manière interactive avec Amazon DynamoDB. Toutefois, pour tirer le meilleur parti de DynamoDB, vous pouvez écrire du code d'application à l'aide du. AWS SDKs

[Ils AWS SDKs fournissent une prise en charge étendue de DynamoDB [en](https://aws.amazon.com/sdk-for-java) Java [JavaScript , dans le](https://aws.amazon.com/sdk-for-browser) navigateur[, .NET,](https://aws.amazon.com/sdk-for-net) Node.js[,](https://aws.amazon.com/sdk-for-node-js)[PHP](https://aws.amazon.com/sdk-for-php), [Python](https://aws.amazon.com/sdk-for-python), Ruby[,](https://aws.amazon.com/sdk-for-ruby) C\$1\$1[,](https://aws.amazon.com/sdk-for-cpp) Go [https://aws.amazon.com/sdk-for-go](https://aws.amazon.com/sdk-for-go) Android et iOS.](https://aws.amazon.com/mobile/sdk/)

Avant de pouvoir utiliser le AWS SDKs avec DynamoDB, vous devez obtenir AWS un ID de clé d'accès et une clé d'accès secrète. Pour de plus amples informations, veuillez consulter [Configuration de DynamoDB (service web)](SettingUp.DynamoWebService.md). 

 Pour une présentation détaillée de la programmation d'applications DynamoDB à l'aide AWS SDKs du, voir. [Programmation avec DynamoDB et le AWS SDKs](Programming.md) 

## Utilisation de NoSQL Workbench pour DynamoDB
<a name="Using.Workbench"></a>

Vous pouvez également accéder à DynamoDB en téléchargeant et en utilisant le [NoSQL Workbench pour DynamoDB](workbench.md).

NoSQL Workbench pour Amazon DynamoDB est une application côté client multiplateforme pour le développement et les opérations de base de données moderne. Il est disponible pour Windows, macOS et Linux. NoSQL Workbench est un outil de développement visuel qui propose des fonctionnalités de modélisation de données, de visualisation de données et de développement de requêtes, afin de vous aider à concevoir, créer, interroger et gérer des tables DynamoDB. NoSQL Workbench inclut désormais DynamoDB local en tant que composant facultatif du processus d’installation, ce qui facilite la modélisation des données dans DynamoDB local. Pour en savoir plus sur DynamoDB local et ses exigences, consultez [Configuration de DynamoDB Local (version téléchargeable)](DynamoDBLocal.md).

**Note**  
Le NoSQL Workbench pour DynamoDB ne prend actuellement pas en charge les AWS connexions configurées avec l'authentification à deux facteurs (2FA).

**Modélisation des données**  
NoSQL Workbench pour DynamoDB vous permet de créer des modèles de données ou de concevoir des modèles à partir de modèles de données existants, qui pourront satisfaire les modèles d’accès aux données de votre application. À la fin du processus, vous pouvez également importer et exporter le modèle de données conçu. Pour de plus amples informations, veuillez consulter [Création de modèles de données avec NoSQL Workbench](workbench.Modeler.md).

**Création des opérations**  
NoSQL Workbench fournit une interface utilisateur graphique enrichie pour développer et tester des requêtes. Vous pouvez utiliser le *créateur d’opérations* pour consulter, explorer et interroger des ensembles de données en temps réel. Vous pouvez également utiliser le créateur d’opérations structurées pour créer et réaliser des opérations de plan de données. Il prend en charge les expressions de projection et de condition, et vous permet de générer un exemple de code dans plusieurs langages. Pour de plus amples informations, veuillez consulter [Exploration des jeux de données et des opérations de création avec NoSQL Workbench](workbench.querybuilder.md).

## Plages d’adresses IP
<a name="Using.IPRanges"></a>

Amazon Web Services (AWS) publie ses plages d’adresses IP actuelles au format JSON. Pour afficher les plages actuelles, téléchargez [ip-ranges.json](https://ip-ranges.amazonaws.com/ip-ranges.json). Pour plus d’informations, consultez [AWS IP Address Ranges](https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html) dans le manuel Références générales AWS.

Pour trouver les plages d’adresses IP que vous utilisez pour [accéder aux tables et index DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Operations_Amazon_DynamoDB.html), recherchez la chaîne suivante dans le fichier ip-ranges.json : `"service": "DYNAMODB"`.

**Note**  
Les plages d’adresses IP ne s’appliquent pas aux flux DynamoDB ni à DynamoDB Accelerator (DAX). 

## Points de terminaison à double pile pour le protocole Internet version 6 () IPv6
<a name="dual-stackipv4-6"></a>

DynamoDB propose des points de terminaison à double pile compatibles avec et. IPv4 IPv6 Les conventions de dénomination des points de terminaison sont les suivantes :
+ `dynamodb.<region>.api.aws`
+ `<account-id>.ddb.<region>.api.aws`
+ `streams-dynamodb.<region>.api.aws`
+ `dax.<region>.api.aws`
+ `dynamodb-fips.<region>.api.aws`

*Pour obtenir la liste complète des points de terminaison DynamoDB et de leur disponibilité régionale, consultez la rubrique Points de terminaison et [quotas Amazon DynamoDB dans le guide de référence](https://docs.aws.amazon.com/general/latest/gr/ddb.html) général.AWS *

Pour plus d'informations sur la configuration de la AWS CLI pour utiliser des points de terminaison à double pile, voir la section [Configurer pour utiliser des points de terminaison à double pile pour tous les AWS services](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-endpoints.html#endpoints-dual-stack) du guide de l'interface de *AWS ligne de commande*.

*Pour plus d'informations sur la configuration de vos clients SDK pour utiliser des points de terminaison à double pile, consultez la rubrique Points de terminaison [à double pile et FIPS dans le guide des outils](https://docs.aws.amazon.com/sdkref/latest/guide/feature-endpoints.html) et.AWS SDKs *

Avant d'utiliser DynamoDB IPv6 avec, vous devez mettre à jour votre rôle d'utilisateur IAM ou les politiques basées sur les ressources que vous utilisez pour le filtrage des adresses IP afin d'inclure les plages d'adresses. IPv6 Les politiques de filtrage des adresses IP qui ne tiennent pas compte de IPv6 l'adresse peuvent entraîner des problèmes d'accès. Pour plus d'informations, consultez la section [Opérateurs de condition des adresses IP](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_IPAddress) du *guide AWS Identity and Access Management*.

## Conditions préalables
<a name="GettingStarted.SettingUp.DynamoWebService"></a>

Avant de démarrer le didacticiel Amazon DynamoDB, découvrez comment accéder à DynamoDB dans [Accès à DynamoDB](AccessingDynamoDB.md). Configurez ensuite DynamoDB à l’aide du service Web ou de la version téléchargée localement dans [Configuration de DynamoDB](SettingUp.md). Après cela, passez à [Étape 1 : création d’une table dans DynamoDB](getting-started-step-1.md).

**Note**  
Si vous prévoyez d'interagir avec DynamoDB uniquement via AWS Management Console le, vous n'avez pas besoin AWS de clé d'accès. Suivez les étapes de [la section S'inscrire](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html#SettingUp.DynamoWebService.SignUpForAWS) à AWS, puis passez à[Étape 1 : création d’une table dans DynamoDB](getting-started-step-1.md).
Si vous ne voulez pas vous inscrire à un compte gratuit, vous pouvez configurer [DynamoDB local (version téléchargeable)](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html). Passez ensuite à l’[Étape 1 : création d’une table dans DynamoDB](getting-started-step-1.md). 
Il existe des différences lorsque vous utilisez des commandes CLI dans des terminaux sous Linux et Windows. Le guide suivant présente des commandes formatées pour les terminaux Linux (y compris macOS) et des commandes formatées pour Windows CMD. Choisissez la commande qui convient le mieux à l’application de terminal que vous utilisez. 

# Configuration de DynamoDB
<a name="SettingUp"></a>

 Outre le service Web Amazon DynamoDB AWS , il fournit une version téléchargeable de DynamoDB que vous pouvez exécuter sur votre ordinateur. Elle s’avère utile pour développer et tester du code. Elle permet d’écrire et de tester des applications localement sans accéder au service web DynamoDB. 

 Les rubriques de cette section décrivent comment configurer DynamoDB (version téléchargeable) et le service web DynamoDB. 

**Topics**
+ [Configuration de DynamoDB (service web)](SettingUp.DynamoWebService.md)
+ [Configuration de DynamoDB Local (version téléchargeable)](DynamoDBLocal.md)

# Configuration de DynamoDB (service web)
<a name="SettingUp.DynamoWebService"></a>

 Pour utiliser le service web Amazon DynamoDB : 

1.  [Inscrivez-vous à AWS.](#SettingUp.DynamoWebService.SignUpForAWS) 

1.  [Obtenez une clé d' AWS accès](#SettingUp.DynamoWebService.GetCredentials) (utilisée pour accéder à DynamoDB par programmation). 
**Note**  
 Si vous prévoyez d'interagir avec DynamoDB uniquement via AWS Management Console le, vous n'avez pas besoin de clé AWS d'accès et vous pouvez passer directement à. [Utilisation de la console](AccessingDynamoDB.md#ConsoleDynamoDB) 

1.  [Configurez vos informations d’identification](#SettingUp.DynamoWebService.ConfigureCredentials) (pour accéder à DynamoDB par programme). 

## S'inscrire à AWS
<a name="SettingUp.DynamoWebService.SignUpForAWS"></a>

 Pour utiliser le service DynamoDB, vous devez disposer d'un compte. AWS Si vous n’en avez pas déjà un, vous serez invité à en créer un au moment de l’inscription. Les AWS services auxquels vous vous inscrivez ne vous sont pas facturés, sauf si vous les utilisez. 

**Pour vous inscrire à AWS**

1. Ouvrez l'[https://portal.aws.amazon.com/billing/inscription.](https://portal.aws.amazon.com/billing/signup)

1. Suivez les instructions en ligne.

   Dans le cadre de la procédure d’inscription, vous recevrez un appel téléphonique ou un SMS et vous saisirez un code de vérification en utilisant le clavier numérique du téléphone.

   Lorsque vous vous inscrivez à un Compte AWS, un *Utilisateur racine d'un compte AWS*est créé. Par défaut, seul l’utilisateur racine a accès à l’ensemble des Services AWS et des ressources de ce compte. La meilleure pratique de sécurité consiste à attribuer un accès administratif à un utilisateur, et à utiliser uniquement l’utilisateur racine pour effectuer les [tâches nécessitant un accès utilisateur racine](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks).

## Accorder un accès par programmation
<a name="SettingUp.DynamoWebService.GetCredentials"></a>

 Avant de pouvoir accéder à DynamoDB par programmation ou via AWS Command Line Interface le AWS CLI(), vous devez disposer d'un accès par programmation. Vous n’avez pas besoin d’accès par programmation si vous prévoyez d’utiliser uniquement la console DynamoDB. 

Les utilisateurs ont besoin d'un accès programmatique s'ils souhaitent interagir avec AWS l'extérieur du AWS Management Console. La manière d'accorder un accès programmatique dépend du type d'utilisateur qui y accède AWS.

Pour accorder aux utilisateurs un accès programmatique, choisissez l’une des options suivantes.


****  

| Quel utilisateur a besoin d’un accès programmatique ? | À | Méthode | 
| --- | --- | --- | 
| IAM | (Recommandé) Utilisez les informations d'identification de la console comme informations d'identification temporaires pour signer les demandes programmatiques adressées au AWS CLI AWS SDKs, ou AWS APIs. |  Suivez les instructions de l’interface que vous souhaitez utiliser. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 
|  Identité de la main-d’œuvre (Utilisateurs gérés dans IAM Identity Center)  | Utilisez des informations d'identification temporaires pour signer les demandes programmatiques adressées au AWS CLI AWS SDKs, ou AWS APIs. |  Suivez les instructions de l’interface que vous souhaitez utiliser. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 
| IAM | Utilisez des informations d'identification temporaires pour signer les demandes programmatiques adressées au AWS CLI AWS SDKs, ou AWS APIs. | Suivez les instructions de la section [Utilisation d'informations d'identification temporaires avec AWS les ressources](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) du Guide de l'utilisateur IAM. | 
| IAM | (Non recommandé)Utilisez des informations d'identification à long terme pour signer des demandes programmatiques adressées au AWS CLI AWS SDKs, ou AWS APIs. |  Suivez les instructions de l’interface que vous souhaitez utiliser. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 

## Configuration de vos informations d’identification
<a name="SettingUp.DynamoWebService.ConfigureCredentials"></a>

 Avant de pouvoir accéder à DynamoDB par programmation ou via AWS CLI le, vous devez configurer vos informations d'identification afin d'autoriser vos applications. 

 Il existe plusieurs méthodes pour le faire. Par exemple, vous pouvez créer manuellement le fichier d’informations d’identification pour stocker votre ID de clé d’accès et votre clé d’accès secrète. Vous pouvez également utiliser la AWS CLI commande `aws configure` pour créer automatiquement le fichier. Vous pouvez également utiliser les variables d’environnement. Pour plus d'informations sur la configuration de vos informations d'identification, consultez le guide du développeur du AWS SDK spécifique à la programmation.

 Pour installer et configurer le AWS CLI, voir[À l'aide du AWS CLI](AccessingDynamoDB.md#Tools.CLI). 

## Intégration à d’autres services DynamoDB
<a name="w2aab9c17b9c13"></a>

Vous pouvez intégrer DynamoDB à de nombreux autres services. AWS Pour plus d’informations, consultez les ressources suivantes : 
+ [Utilisation de DynamoDB avec d'autres services AWS](OtherServices.md)
+ [CloudFormation pour DynamoDB](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html)
+ [Utilisation de AWS Backup avec DynamoDB](backuprestore_HowItWorksAWS.md)
+ [Gestion des identités et des accès AWS (IAM) et DynamoDB](identity-and-access-mgmt.md)
+ [Utilisation d’ AWS Lambda avec Amazon DynamoDB](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html)

# Configuration de DynamoDB Local (version téléchargeable)
<a name="DynamoDBLocal"></a>

 La version téléchargeable d’Amazon DynamoDB vous permet d’écrire et de tester des applications sans accéder au service web DynamoDB. Au lieu de cela, la base de données est autonome sur votre ordinateur. Lorsque vous êtes prêt à déployer votre application en production, vous supprimez le point de terminaison local dans le code afin que l’application pointe vers le service web DynamoDB. 

 Disposer de cette version locale vous aide à économiser sur les frais de transfert de données, de stockage de données et de débit. En outre, vous n’avez pas besoin d’une connexion internet pendant que vous développez votre application. 

 DynamoDB local est disponible en [téléchargement](DynamoDBLocal.DownloadingAndRunning.md#DynamoDBLocal.DownloadingAndRunning.title) (nécessite JRE) sous la forme d’une [dépendance Apache Maven](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html#apache-maven) ou d’une [image Docker](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html#docker). 

 Si vous préférez utiliser le service web Amazon DynamoDB, consultez [Configuration de DynamoDB (service web)](SettingUp.DynamoWebService.md). 

**Topics**
+ [Déploiement de DynamoDB localement sur votre ordinateur](DynamoDBLocal.DownloadingAndRunning.md)
+ [Notes d’utilisation de DynamoDB Local](DynamoDBLocal.UsageNotes.md)
+ [Historique des versions de DynamoDB local](DynamoDBLocalHistory.md)
+ [Télémétrie dans DynamoDB Local](DynamoDBLocalTelemetry.md)

# Déploiement de DynamoDB localement sur votre ordinateur
<a name="DynamoDBLocal.DownloadingAndRunning"></a>

**Note**  
DynamoDB local est disponible en trois versions : v3.x (actuelle), v2.x (héritée) et v1.x (obsolète).
DynamoDB v3.x est recommandé pour vos tests et développements locaux.
La migration de DynamoDB local V2.x vers V3.x nécessite la mise à jour des instructions d’importation de `com.amazonaws.services.dynamodbv2` vers `software.amazon.dynamodb` et la mise à jour des dépendances Maven pour les utilisateurs de Maven.
Si vous migrez une application qui utilise le kit SDK pour Java v1.x vers le kit SDK pour Java 2.x, suivez les étapes du [ kit AWS SDK pour Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/migration.html).

## Téléchargement de DynamoDB local
<a name="DynamoDBLocal.DownloadingAndRunning.V2"></a>

Suivez ces étapes pour configurer et exécuter DynamoDB sur votre ordinateur :

**Pour configurer DynamoDB sur votre ordinateur**

1. Téléchargez DynamoDB local gratuitement à partir de l’un des emplacements suivants.  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html)
**Important**  
 Pour exécuter DynamoDB v2.6.0 ou supérieures sur votre ordinateur, vous devez disposer de l’environnement d’exécution Java (JRE) version 17.x ou plus récente. L’application ne fonctionne pas sur les versions antérieures de JRE.

1.  Une fois que vous avez téléchargé l’archive, extrayez le contenu et copiez le répertoire extrait vers un emplacement de votre choix. 

1.  Pour démarrer DynamoDB sur votre ordinateur, ouvrez une fenêtre d’invite de commande, accédez au répertoire où vous avez extrait `DynamoDBLocal.jar`, puis entrez la commande suivante. 

   ```
   java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb
   ```
**Note**  
 Si vous utilisez Windows PowerShell, veillez à inclure le nom du paramètre ou le nom complet et la valeur comme suit :   
 ` java -D"java.library.path=./DynamoDBLocal_lib" -jar DynamoDBLocal.jar `   
 DynamoDB traite les demandes entrantes jusqu’à ce que vous l’arrêtiez. Pour arrêter DynamoDB, tapez Ctrl \$1 C à l’invite de commande.   
 DynamoDB utilise le port 8000 par défaut. Si le port 8000 n'est pas disponible, cette commande lève une exception. Pour obtenir la liste complète des options d’exécution de DynamoDB, y compris `-port`, entrez la commande suivante.   
 ` java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -help ` 

1. Pour pouvoir accéder à DynamoDB par programme ou via l’ AWS Command Line Interface (AWS CLI), vous devez configurer vos informations d’identification pour permettre l’autorisation de vos applications. La version téléchargeable de DynamoDB requiert des informations d’identification pour fonctionner, comme l’illustre l’exemple suivant. 

   ```
   AWS Access Key ID: "fakeMyKeyId"
   AWS Secret Access Key: "fakeSecretAccessKey"
   Default Region Name: "fakeRegion"
   ```

    Vous pouvez utiliser la commande `aws configure` de AWS CLI pour configurer des informations d’identification. Pour de plus amples informations, veuillez consulter [À l'aide du AWS CLI](AccessingDynamoDB.md#Tools.CLI). 

1.  Vous pouvez commencer à écrire des applications. Pour accéder à DynamoDB s'exécutant localement avec AWS CLI le, utilisez le paramètre. `--endpoint-url ` Par exemple, utilisez la commande suivante pour afficher la liste des tables DynamoDB. 

   ```
   aws dynamodb list-tables --endpoint-url http://localhost:8000
   ```

## Exécution de DynamoDB local en tant qu’image Docker
<a name="DynamoDBLocal.DownloadingAndRunning.Docker"></a>

 La version téléchargeable d’Amazon DynamoDB est disponible sous la forme d’une image Docker. Pour plus d’informations, consultez [dynamodb-local](https://hub.docker.com/r/amazon/dynamodb-local). Pour savoir quelle est votre version dans DynamoDB local, saisissez la commande suivante :

```
java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -version
```

 Pour un exemple d'utilisation de DynamoDB local dans le cadre d'une application REST basée sur AWS SAM(), consultez AWS Serverless Application Model l'application [SAM DynamoDB](https://github.com/aws-samples/aws-sam-java-rest) pour la gestion des commandes. Cet exemple d’application montre comment utiliser DynamoDB Local à des fins de test. 

 Si vous souhaitez exécuter une application à conteneurs multiples qui utilise également le conteneur local DynamoDB, utilisez Docker Compose pour définir et exécuter tous les services de votre application, y compris DynamoDB local. 

**Pour installer et exécuter DynamoDB Local avec Docker Compose :**

1.  Téléchargez et installez [Docker Desktop](https://www.docker.com/products/docker-desktop). 

1.  Copiez le code suivant dans un fichier et enregistrez-le sous le nom `docker-compose.yml`. 

   ```
   services:
    dynamodb-local:
      command: "-jar DynamoDBLocal.jar -sharedDb -dbPath ./data"
      image: "amazon/dynamodb-local:latest"
      container_name: dynamodb-local
      ports:
        - "8000:8000"
      volumes:
        - "./docker/dynamodb:/home/dynamodblocal/data"
      working_dir: /home/dynamodblocal
   ```

    Si vous voulez que votre application et DynamoDB Local soient dans des conteneurs distincts, utilisez le fichier yaml suivant : 

   ```
   version: '3.8'
   services:
    dynamodb-local:
      command: "-jar DynamoDBLocal.jar -sharedDb -dbPath ./data"
      image: "amazon/dynamodb-local:latest"
      container_name: dynamodb-local
      ports:
        - "8000:8000"
      volumes:
        - "./docker/dynamodb:/home/dynamodblocal/data"
      working_dir: /home/dynamodblocal
    app-node:
      depends_on:
        - dynamodb-local
      image: amazon/aws-cli
      container_name: app-node
      ports:
       - "8080:8080"
      environment:
        AWS_ACCESS_KEY_ID: 'DUMMYIDEXAMPLE'
        AWS_SECRET_ACCESS_KEY: 'DUMMYEXAMPLEKEY'
      command:
        dynamodb describe-limits --endpoint-url http://dynamodb-local:8000 --region us-west-2
   ```

    Ce script docker-compose.yml crée un conteneur `app-node` et un conteneur `dynamodb-local`. Le script exécute une commande dans le conteneur `app-node`, qui utilise l’ AWS CLI pour se connecter au conteneur `dynamodb-local`, et décrit les limites de compte et de table. 

    Pour l’utiliser avec votre propre image d’application, remplacez la valeur `image` dans l’exemple ci-dessous par celle de votre application. 

   ```
   version: '3.8'
   services:
    dynamodb-local:
      command: "-jar DynamoDBLocal.jar -sharedDb -dbPath ./data"
      image: "amazon/dynamodb-local:latest"
      container_name: dynamodb-local
      ports:
        - "8000:8000"
      volumes:
        - "./docker/dynamodb:/home/dynamodblocal/data"
      working_dir: /home/dynamodblocal
    app-node:
      image: location-of-your-dynamodb-demo-app:latest
      container_name: app-node
      ports:
        - "8080:8080"
      depends_on:
        - "dynamodb-local"
      links:
        - "dynamodb-local"
      environment:
        AWS_ACCESS_KEY_ID: 'DUMMYIDEXAMPLE'
        AWS_SECRET_ACCESS_KEY: 'DUMMYEXAMPLEKEY'
        REGION: 'eu-west-1'
   ```
**Note**  
 Les scripts YAML nécessitent que vous spécifiiez une clé d' AWS accès et une clé AWS secrète, mais il n'est pas nécessaire qu'il s'agisse de AWS clés valides pour accéder à DynamoDB local. 

1.  Exécutez la commande de ligne de commande suivante : 

   ```
   docker-compose up
   ```

## Exécution de DynamoDB local en tant que dépendance Apache Maven
<a name="DynamoDBLocal.DownloadingAndRunning.Maven.v2"></a>

**Note**  
Si vous migrez une application qui utilise le kit SDK pour Java v1.x vers le kit SDK pour Java 2.x, suivez les étapes du [ kit AWS SDK pour Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/migration.html).

 Suivez ces étapes pour utiliser Amazon DynamoDB dans votre application en tant que dépendance. 

**Pour déployer DynamoDB en tant que référentiel Apache Maven**

1.  Téléchargez et installez Apache Maven. Pour plus d’informations, consultez [Downloading Apache Maven](https://maven.apache.org/download.cgi) et [Installing Apache Maven](https://maven.apache.org/install.html). 

1.  Ajoutez le référentiel Maven DynamoDB au fichier POM (Project Object Model) de votre application. 

   ```
   <!--Dependency:-->
   <dependencies>
      <dependency>
         <groupId>software.amazon.dynamodb</groupId>
         <artifactId>DynamoDBLocal</artifactId>
         <version>3.3.0</version>
      </dependency>
   </dependencies>
   ```

    Exemple de modèle à utiliser avec Spring Boot 3 and/or Spring Framework 6 : 

   ```
   <?xml version="1.0" encoding="UTF-8"?>
   <project xmlns="http://maven.apache.org/POM/4.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   
   <groupId>org.example</groupId>
   <artifactId>SpringMavenDynamoDB</artifactId>
   <version>1.0-SNAPSHOT</version>
   
   <properties>
      <spring-boot.version>3.0.1</spring-boot.version>
      <maven.compiler.source>17</maven.compiler.source>
      <maven.compiler.target>17</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
      <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>3.1.0</version>
      </parent>
   
   <dependencies>
      <dependency>
          <groupId>software.amazon.dynamodb</groupId>
          <artifactId>DynamoDBLocal</artifactId>
          <version>3.3.0</version>
      </dependency>
      <!-- Spring Boot -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter</artifactId>
          <version>${spring-boot.version}</version>
      </dependency>
      <!-- Spring Web -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
          <version>${spring-boot.version}</version>
      </dependency>
      <!-- Spring Data JPA -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-jpa</artifactId>
          <version>${spring-boot.version}</version>
      </dependency>
      <!-- Other Spring dependencies -->
      <!-- Replace the version numbers with the desired version -->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>6.0.0</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>6.0.0</version>
      </dependency>
      <!-- Add other Spring dependencies as needed -->
      <!-- Add any other dependencies your project requires -->
   </dependencies>
   </project>
   ```
**Note**  
 Vous pouvez également utiliser l’URL du [référentiel central Maven](https://mvnrepository.com/artifact/com.amazonaws/DynamoDBLocal?repo=dynamodb-local-release). 

## Exécutez DynamoDB en local dans AWS CloudShell
<a name="DynamoDBLocal.DynamoDB.Local.CloudShell"></a>

AWS CloudShell est un shell pré-authentifié basé sur un navigateur que vous pouvez lancer directement depuis le. AWS Management Console Vous pouvez naviguer AWS CloudShell AWS Management Console de différentes manières. Pour plus d'informations, consultez la section [Mise en route avec AWS CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/getting-started.html).

Procédez comme suit pour exécuter DynamoDB en local n'importe où dans le AWS CloudShell . AWS Management Console

**Pour exécuter DynamoDB en local dans votre AWS CloudShell AWS Management Console**

1. Lancez AWS CloudShell depuis l'interface de la console Région AWS, choisissez un shell disponible et passez à votre shell préféré, tel que Bash ou Z. PowerShell

1. Pour en choisir une Région AWS, allez dans le menu **Sélectionnez une région** et sélectionnez une région [prise en charge Région AWS](https://docs.aws.amazon.com/cloudshell/latest/userguide/supported-aws-regions.html). (Les régions disponibles sont surlignées.)

1. À partir du AWS Management Console, lancez-le AWS CloudShell en choisissant l'une des options suivantes :

   1. Dans la barre de navigation, choisissez l’icône **AWS CloudShell**.

   1. Dans la zone **de recherche**, entrez le mot CloudShell, puis choisissez **CloudShell**.

   1. Dans le widget **Visites récentes**, sélectionnez **CloudShell**.

   1. Dans la barre d'outils de la console, choisissez **CloudShell**.

1. Pour exécuter DynamoDB en local, vous pouvez AWS CloudShell utiliser l'alias. `dynamodb-local` Vous pouvez spécifier des options de ligne de commande supplémentaires pour modifier les paramètres DynamoDB local. Consultez [Notes d’utilisation de DynamoDB Local](DynamoDBLocal.UsageNotes.md) pour connaître les options disponibles.
**Note**  
Pour exécuter DynamoDB local en arrière-plan, exécutez DynamoDB local en utilisant :. AWS CloudShell `dynamodb-local &`

1. Pour accéder à DynamoDB s'exécutant localement AWS CloudShell avec AWS CLI le, utilisez le paramètre. `--endpoint-url` Par exemple, utilisez la commande suivante pour afficher la liste des tables DynamoDB :

   `aws dynamodb list-tables --endpoint-url http://localhost:8000`

Pour un exemple de projet présentant plusieurs approches pour configurer et utiliser DynamoDB local, notamment le téléchargement de fichiers JAR, leur exécution sous forme d’image Docker et leur utilisation en tant que dépendance Maven, consultez [DynamoDB Local Sample Java Project](https://github.com/awslabs/amazon-dynamodb-local-samples/tree/main).

# Notes d’utilisation de DynamoDB Local
<a name="DynamoDBLocal.UsageNotes"></a>

 À l’exception du point de terminaison, les applications qui s’exécutent avec la version téléchargeable d’Amazon DynamoDB doivent également utiliser le service web DynamoDB. Cependant, lorsque vous utilisez DynamoDB localement, vous devez être conscient de ce qui suit : 
+  *Si vous utilisez `-sharedDb` cette option, DynamoDB crée un seul fichier de base de données nommé .db. shared-local-instance* Tous les programmes qui se connectent à DynamoDB accèdent à ce fichier. Si vous supprimez le fichier, vous perdez toutes les données que vous y avez stockées. 
+  Si vous omettez`-sharedDb`, le fichier de base de données s'appelle *myaccesskeyid\$1region.db*, avec l'ID de clé AWS d'accès et AWS la région tels qu'ils apparaissent dans la configuration de votre application. Si vous supprimez le fichier, vous perdez toutes les données que vous y avez stockées. 
+  Si vous utilisez l’option `-inMemory`, DynamoDB n’écrit aucun fichier de base de données. Au lieu de cela, toutes les données sont écrites en mémoire et ne sont pas enregistrées lorsque vous arrêtez DynamoDB. 
+  Si vous utilisez l’option `-inMemory`, l’option `-sharedDb` est également nécessaire. 
+  Si vous utilisez l’option `-optimizeDbBeforeStartup`, vous devez également spécifier le paramètre `-dbPath` de sorte que DynamoDB puisse trouver son fichier de base de données. 
+  AWS SDKs Pour DynamoDB, la configuration de votre application nécessite que la configuration de votre application spécifie une valeur de clé d'accès et AWS une valeur de région. DynamoDB utilise ces valeurs pour nommer le fichier de base de données local, sauf si vous utilisez l’option `-sharedDb` ou `-inMemory`. Il n'est pas nécessaire que ces AWS valeurs soient valides pour être exécutées localement. Vous pouvez trouver pratique de choisir des valeurs valides afin de pouvoir exécuter votre code dans le cloud en modifiant simplement le point de terminaison que vous utilisez. 
+  DynamoDB local renvoie toujours une valeur nulle pour `billingModeSummary.` 
+  La variable d’environnement `AWS_ACCESS_KEY_ID` de DynamoDB local ne peut contenir que des lettres (A à Z, a à z) et des chiffres (0 à 9). 
+ DynamoDB local ne prend pas en [Point-in-time charge la restauration](Point-in-time-recovery.md) (PITR).

**Topics**
+ [Options de ligne de commande](#DynamoDBLocal.CommandLineOptions)
+ [Définition du point de terminaison local](#DynamoDBLocal.Endpoint)
+ [Différences entre la version téléchargeable de DynamoDB et le service web DynamoDB](#DynamoDBLocal.Differences)

## Options de ligne de commande
<a name="DynamoDBLocal.CommandLineOptions"></a>

 Avec la version téléchargeable de DynamoDB, vous pouvez utiliser les options de ligne de commande suivantes : 
+  `-cors``value`— Permet la prise en charge du partage de ressources entre origines (CORS) pour. JavaScript Vous devez fournir une liste « allow » séparée par des virgules de domaines spécifiques. Le paramètre par défaut de `-cors` est un astérisque (\$1), qui autorise l’accès public. 
+  `-dbPath` `value` – Répertoire dans lequel DynamoDB écrit son fichier de base de données. Si vous ne spécifiez pas cette option, le fichier est écrit dans le répertoire actuel. Vous ne pouvez pas spécifier à la fois `-dbPath` et `-inMemory`. 
+  `-delayTransientStatuses` – Amène DynamoDB à introduire des retards pour certaines opérations. DynamoDB (version téléchargeable) peut effectuer certaines tâches presque instantanément, create/update/delete telles que les opérations sur les tables et les index. Cependant, le service DynamoDB nécessite plus de temps pour exécuter ces tâches. La définition de ce paramètre permet à DynamoDB s’exécutant sur votre ordinateur de simuler plus fidèlement le comportement du service web DynamoDB. (Actuellement, ce paramètre provoque des retards uniquement pour les index secondaires globaux dont l’état est *CREATING* ou *DELETING*.) 
+  `-help` – Affiche un récapitulatif de l’utilisation et des options. 
+  `-inMemory` – DynamoDB s’exécute en mémoire au lieu d’utiliser un fichier de base de données. Lorsque vous arrêtez DynamoDB, aucune des données n’est enregistrée. Vous ne pouvez pas spécifier à la fois `-dbPath` et `-inMemory`. 
+  `-optimizeDbBeforeStartup` – Optimise les tables de base de données sous-jacentes avant de démarrer DynamoDB sur votre ordinateur. Vous devez également spécifier `-dbPath` lorsque vous utilisez ce paramètre. 
+  `-port` `value` – Numéro de port que DynamoDB utilise pour communiquer avec votre application. Si vous ne spécifiez pas cette option, le port par défaut est `8000`. 
**Note**  
 DynamoDB utilise le port 8000 par défaut. Si le port 8000 n'est pas disponible, cette commande lève une exception. Vous pouvez utiliser l’option `-port` pour spécifier un autre numéro de port. Pour obtenir la liste complète des options d’exécution de DynamoDB, dont `-port`, entrez la commande suivante :   
 `java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -help` 
+  `-sharedDb` – Si vous spécifiez `-sharedDb`, DynamoDB utilise un fichier de base de données unique au lieu de fichiers distincts pour chaque identification et région. 
+  `-disableTelemetry` : lorsque cette option est spécifiée, DynamoDB Local n’envoie aucune donnée de télémétrie. 
+ `-version` : imprime la version de DynamoDB local.

## Définition du point de terminaison local
<a name="DynamoDBLocal.Endpoint"></a>

 Par défaut, les outils AWS SDKs et utilisent des points de terminaison pour le service Web Amazon DynamoDB. Pour utiliser les outils SDKs et avec la version téléchargeable de DynamoDB, vous devez spécifier le point de terminaison local : 

 `http://localhost:8000` 

### AWS Command Line Interface
<a name="DynamoDBLocal.Endpoint.CLI"></a>

 Vous pouvez utiliser le AWS Command Line Interface (AWS CLI) pour interagir avec DynamoDB téléchargeable. 

 Pour accéder à DynamoDB s’exécutant localement, utilisez le paramètre `--endpoint-url`. Voici un exemple d'utilisation du AWS CLI pour répertorier les tables de DynamoDB sur votre ordinateur. 

```
aws dynamodb list-tables --endpoint-url http://localhost:8000
```

**Note**  
 AWS CLI Impossible d'utiliser la version téléchargeable de DynamoDB comme point de terminaison par défaut. Par conséquent, vous devez le spécifier `--endpoint-url` à chaque AWS CLI commande. 

### AWS SDKs
<a name="DynamoDBLocal.Endpoint.SDK"></a>

 La façon dont vous spécifiez un point de terminaison dépend du langage de programmation et du kit SDK AWS que vous utilisez. Les sections suivantes décrivent comment le faire : 
+  [Java : définition de la AWS région et du point de terminaison](CodeSamples.Java.md#CodeSamples.Java.RegionAndEndpoint)(DynamoDB local prend en charge le SDK AWS pour Java V1 et V2) 
+ CodeSamples.Java. RegionAndEndpoint [.NET : définition de la AWS région et du point de terminaison](CodeSamples.DotNet.md#CodeSamples.DotNet.RegionAndEndpoint) 

## Différences entre la version téléchargeable de DynamoDB et le service web DynamoDB
<a name="DynamoDBLocal.Differences"></a>

 La version téléchargeable de DynamoDB est destinée uniquement à des fins de développement et de test. En comparaison, le service web DynamoDB est un service géré doté de fonctions de mise à l’échelle, de disponibilité et de durabilité, qui en font une solution idéale pour un usage en mode production. 

 Les différences entre la version téléchargeable de DynamoDB et le service web sont les suivantes : 
+ Régions AWS et distincts ne Comptes AWS sont pas pris en charge au niveau du client. 
+  Les paramètres de débit approvisionné sont ignorés dans la version téléchargeable de DynamoDB, même si l’opération `CreateTable` les requiert. Pour `CreateTable`, vous pouvez spécifier les nombres de votre choix pour le débit provisionné en lecture et en écriture, même si ces chiffres ne sont pas utilisés. Vous pouvez appeler `UpdateTable` autant de fois que vous le souhaitez par jour. Cependant, les modifications des valeurs du débit provisionné sont ignorées. 
+  Les opérations `Scan` sont exécutées de façon séquentielle. Les analyses parallèles ne sont pas prises en charge. Les paramètres `Segment` et `TotalSegments` de l’opération `Scan` sont ignorés. 
+  La vitesse des opérations de lecture et d’écriture sur les données de la table est limitée uniquement par la vitesse de votre ordinateur. Les opérations `CreateTable`, `UpdateTable` et `DeleteTable` se produisent immédiatement, et l’état de la table est toujours ACTIVE. Les opérations `UpdateTable` qui modifient uniquement les paramètres de débit provisionné sur les tables ou les index secondaires globaux se produisent immédiatement. Si une opération `UpdateTable` crée ou supprime des index secondaires globaux, ces index passent par les états normaux (tels que CREATING et DELETING, respectivement) avant d’acquérir l’état ACTIVE. La table demeure ACTIVE pendant ce temps. 
+  Les opérations de lecture sont éventuellement cohérentes. Cependant, en raison de la vitesse d’exécution de DynamoDB local sur votre ordinateur, la plupart des lectures apparaissent fortement cohérentes. 
+  Les métriques des collections d’élément ne sont pas suivies, ni leurs tailles. Dans les réponses des opérations, les valeurs null sont retournées à la place des métriques des collections d’élément. 
+  Dans DynamoDB, les données retournées sont limitées à 1 Mo par jeu de résultats. Tant le service web que la version téléchargeable de DynamoDB appliquent cette limite. Cependant, lorsque vous interrogez un index, le service DynamoDB calcule uniquement la taille de la clé et des attributs projetés. En revanche, la version téléchargeable de DynamoDB calcule la taille de l’élément entier. 
+  Si vous utilisez DynamoDB Streams, la vitesse de création des partitions peut varier. Dans le service web DynamoDB, le comportement de création de partition est partiellement influencé par l’activité de partition de table. Lorsque vous exécutez DynamoDB localement, il n’existe aucun partitionnement de table. Dans les deux cas, comme les partitions sont éphémères, votre application ne doit pas être dépendante du comportement des partitions. 
+  `TransactionConflictExceptions`ne sont pas lancés par DynamoDB téléchargeable pour les transactions. APIs Nous vous recommandons d’utiliser une infrastructure de simulation Java pour simuler des `TransactionConflictExceptions` dans le gestionnaire DynamoDB pour tester comment votre application répond dans le cas de transactions en conflit. 
+  Dans le service Web DynamoDB, qu'il soit accessible via la console ou le, les noms des tables distinguent AWS CLI les majuscules et minuscules. Une table nommée `Authors` et une table nommée `authors` peuvent toutes deux exister comme tables distinctes. Dans la version téléchargeable, les noms de table ne sont pas sensibles à la casse, et la tentative de créer ces deux tables se traduira par une erreur. 
+ L’ajout de balises n’est pas pris en charge dans la version téléchargeable de DynamoDB. 
+ [La version téléchargeable de DynamoDB ignore le paramètre Limit dans. [ExecuteStatement](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ExecuteStatement.html)](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ExecuteStatement.html#DDB-ExecuteStatement-request-Limit)

# Historique des versions de DynamoDB local
<a name="DynamoDBLocalHistory"></a>

Le tableau suivant décrit les modifications importantes apportées à chaque version de *DynamoDB local*.


****  

| Version | Modifier | Description | Date | 
| --- | --- | --- | --- | 
| 3.3.0 |  Ajout de la prise en charge des clés à attributs multiples pour les index secondaires globaux  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  19 janvier 2026  | 
| 3.2.0 |  Problèmes de compatibilité résolus avec plusieurs versions de Kotlin  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  09 janvier 2026  | 
| 3.1.0 |  Amélioration des performances pour les requêtes PartiQL, y compris la dépendance au temps de Joda  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  14 septembre 2025  | 
| 3.0.0 |  Migration du AWS SDK Java V1 vers le V2  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  17 juillet 2025  | 
| 2.6.0 |  Support de l'ARN de table en tant que nom de table dans DynamoDB APIs Correction des performances et mises à jour de sécurité  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  13 mars 2025  | 
| 2.5.4 |  Mise à niveau vers Jetty Dependencies  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  12 décembre 2024  | 
| 2.5.3 |  Mise à niveau de Jackson Dependencies vers la version 2.17.x dans Log4j Core (résout CVE-2022-1471)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  6 novembre 2024  | 
| 2.5.2 | Correctif de bogue pour le flux de travail de mise à jour des tables | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  | 20 juin 2024 | 
| 2.5.1 | Correctif pour les bogues introduits dans la fonctionnalité OndemandThroughPut  | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html) | 5 juin 2024 | 
| 2.5.0 |  Prise en charge d’un débit maximal configurable pour les tables à la demande, `ReturnValuesOnConditionCheckFailure``BatchExecuteStatement` et `ExecuteTransactionRequest`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  28 mai 2024  | 
| 2.4.0 |  Prise en charge pour `ReturnValuesOnConditionCheckFailure` - Mode intégré  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  17 avril 2024  | 
| 2.3.0 |  Mise à niveau de Jetty et de JDK  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  14 mars 2024  | 
| 2.2.0 |  Ajout de la prise en charge de la protection contre la suppression des tables et du paramètre `ReturnValuesOnConditionCheckFailure`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  14 décembre 2023  | 
| 2.1.0 |  Support des bibliothèques SQLLite natives pour les projets Maven et ajout de la télémétrie  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  23 octobre 2023  | 
| 2.0.0 |  Migration de Javax vers Jakarta Namespace et Support JDK11   |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  5 juillet 2023  | 
| 1.25.1 |  Mise à niveau de Jackson Dependencies vers la version 2.17.x dans Log4j Core (résout CVE-2022-1471)  |  Mise à niveau de Jackson Dependencies vers la version 2.17.x dans Log4j Core (résout CVE-2022-1471) pour corriger une vulnérabilité critique dans la bibliothèque SnakeYAML, qui est une dépendance transitive  |  6 novembre 2024  | 
| 1.25.0 |  Ajout de la prise en charge de la protection contre la suppression des tables et du paramètre `ReturnValuesOnConditionCheckFailure`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  18 décembre 2023  | 
| 1.24.0 |  Support des bibliothèques SQLLite natives pour les projets Maven et ajout de la télémétrie  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  23 octobre 2023  | 
| 1.23.0 |  Gestion de l’accès et de la clé secrète non valides lors du démarrage du serveur  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  28 juin 2023  | 
| 1.22.0 |  Prise en charge de l’opération Limit pour PartiQL  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  8 juin 2023  | 
| 1.21.0 |  Prise en charge de 100 actions par transaction  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  26 janvier 2023  | 
| 1.20.0 |  Ajout de la prise en charge de M1 Mac  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  12 septembre 2022  | 
| 1.19.0 |  Mise à niveau de l’analyseur PartiQL  |  Mise à niveau de l’analyseur PartiQL et d’autres bibliothèques associées  |  27 juillet 2022  | 
| 1.18.0 | Mise à niveau de log4j-core et Jackson-core | Mise à niveau de log4j-core vers la version 2.17.1 et de Jackson-core 2.10.x vers la version 2.12.0 | 10 janvier 2022 | 
| 1.17.2 | Mise à niveau de log4j-core | Mise à niveau de la dépendance log4j-core vers la version 2.16 | 16 janvier 2021 | 
| 1.17.1 | Mise à niveau de log4j-core | Mise à jour de la dépendance log4j-core pour corriger l’exploit « jour zéro » afin d’empêcher l’exécution du code à distance - Log4Shel | 10 janvier 2021 | 
| 1.17.0 | Obsolescence du shell Web Javascript |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  | 8 janvier 2021 | 

# Télémétrie dans DynamoDB Local
<a name="DynamoDBLocalTelemetry"></a>

 Chez AWS, nous développons et lançons des services en fonction de ce que nous apprenons des interactions avec les clients, et nous utilisons les commentaires des clients pour améliorer nos produits. La télémétrie est une information supplémentaire qui nous aide à mieux comprendre les besoins de nos clients, à diagnostiquer les problèmes et à fournir des fonctionnalités permettant d’améliorer l’expérience client. 

 DynamoDB Local collecte des données de télémétrie, telles que les métriques d’utilisation génériques, les informations relatives aux systèmes et à l’environnement et les erreurs. Pour plus de détails sur les types de télémétrie collectés, consultez [Type d’informations à collecter](#DynamoDBLocalTelemetry.TypesOfInformationCollected). 

 DynamoDB Local ne collecte pas les informations personnelles, telles que les noms d’utilisateur ou les adresses e-mail. Elle n’extrait pas non plus les informations sensibles au niveau du projet. 

 En tant que client, vous contrôlez si la télémétrie est activée et vous pouvez modifier vos paramètres à tout moment. Si la télémétrie reste activée, DynamoDB Local envoie des données de télémétrie en arrière-plan sans nécessiter d’interaction supplémentaire avec le client. 

## Désactivation de la télémétrie à l’aide des options de ligne de commande
<a name="DynamoDBLocalTelemetry.cli"></a>

 Vous pouvez désactiver la télémétrie à l’aide des options de ligne de commande au démarrage de DynamoDB Local à l’aide de l’option `-disableTelemetry`. Pour de plus amples informations, veuillez consulter [Options de ligne de commande](DynamoDBLocal.UsageNotes.md#DynamoDBLocal.CommandLineOptions).

## Désactivation de la télémétrie pour une session unique
<a name="DynamoDBLocalTelemetry.TurnOffTelemetrySingleSession"></a>

 Dans les systèmes d’exploitation macOS et Linux, vous pouvez désactiver la télémétrie pour une seule session. Pour désactiver la télémétrie de votre session en cours, exécutez la commande suivante pour définir la variable d’environnement `DDB_LOCAL_TELEMETRY` sur `false`. Répétez la commande pour chaque nouveau terminal ou chaque nouvelle session. 

```
export DDB_LOCAL_TELEMETRY=0
```

## Désactivation de la télémétrie pour votre profil dans toutes les sessions
<a name="DynamoDBLocalTelemetry.TurnOffTelemetryForAllSessions"></a>

 Exécutez les commandes suivantes pour désactiver la télémétrie pour toutes les sessions lorsque vous exécutez DynamoDB Local sur votre système d’exploitation. 

**Pour désactiver la télémétrie sous Linux**

1.  Exécuter : 

   ```
   echo "export DDB_LOCAL_TELEMETRY=0" >>~/.profile
   ```

1.  Exécuter : 

   ```
   source ~/.profile
   ```

**Pour désactiver la télémétrie sous macOS**

1.  Exécuter : 

   ```
   echo "export DDB_LOCAL_TELEMETRY=0" >>~/.profile
   ```

1.  Exécuter : 

   ```
   source ~/.profile
   ```

**Pour désactiver la télémétrie sous Windows**

1.  Exécuter : 

   ```
   setx DDB_LOCAL_TELEMETRY 0
   ```

1.  Exécuter : 

   ```
   refreshenv
   ```

## Désactivation de la télémétrie à l’aide de DynamoDB local intégré aux projets Maven
<a name="DynamoDBLocalTelemetry.maven"></a>

 Vous pouvez désactiver la télémétrie à l’aide de DynamoDB local intégré aux projets Maven. 

```
boolean disableTelemetry = true;
// AWS SDK v1
 AmazonDynamoDB amazonDynamoDB = DynamoDBEmbedded.create(disableTelemetry).amazonDynamoDB();

// AWS SDK v2
DynamoDbClient ddbClientSDKv2Local = DynamoDBEmbedded.create(disableTelemetry).dynamoDbClient();
```

## Type d’informations à collecter
<a name="DynamoDBLocalTelemetry.TypesOfInformationCollected"></a>
+  **Informations d'utilisation** — La télémétrie générique telle que le serveur start/stop et l'API ou l'opération appelée. 
+  **Informations sur le système et l’environnement** : la version de Java, le système d’exploitation (Windows, Linux ou macOS), l’environnement dans lequel DynamoDB Local s’exécute (par exemple, fichier JAR autonome, conteneur Docker ou dépendance Maven) et les valeurs de hachage des attributs d’utilisation. 

## En savoir plus
<a name="DynamoDBLocalTelemetry.LearnMore"></a>

 Les données de télémétrie collectées par DynamoDB local sont conformes aux politiques de confidentialité des données. AWS Pour plus d’informations, consultez les ressources suivantes : 
+  [AWS conditions de service](https://aws.amazon.com/service-terms/) 
+  [Questions fréquentes (FAQ) relatives à la confidentialité des données](https://aws.amazon.com/compliance/data-privacy-faq/) 

# Étape 1 : création d’une table dans DynamoDB
<a name="getting-started-step-1"></a>

Dans cette étape, vous allez créer une table `Music` dans Amazon DynamoDB. Cette table possède les informations suivantes :
+ Clé de partition : `Artist`
+ Clé de tri : `SongTitle`

Pour plus d’informations sur les opérations de table, consultez [Utilisation de tables et de données dans DynamoDB](WorkingWithTables.md). 

**Note**  
Avant de commencer, assurez-vous d’avoir suivi les étapes dans [Conditions préalables](GettingStartedDynamoDB.md#GettingStarted.SettingUp.DynamoWebService).

## AWS Management Console
<a name="getting-started-step-1-Console"></a>

Pour créer une table `Music` à l’aide de la console DynamoDB :

1. Connectez-vous à la console DynamoDB AWS Management Console et ouvrez-la à l'adresse. [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)

1. Dans le volet de navigation de gauche, choisissez **Tables**. 

1. Choisissez **Créer un tableau**.

1. Saisissez les **informations de la table ** comme suit :

   1. Sous **Nom du tableau**, saisissez **Music**.

   1. Pour **Clé de partition**, saisissez **Artist**.

   1. Pour **Clé de tri**, entrez **SongTitle**.

1. Pour **Paramètres de la table**, conservez la sélection par défaut de **Paramètres par défaut**.

1. Choisissez **Créer une table** pour créer la table.  
![\[Page Créer une table contenant les informations de la table.\]](http://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/images/GettingStarted/CreateTableMusic.png)

1. Une fois que la table a le statut `ACTIVE`, nous vous recommandons d’activer [Sauvegardes ponctuelles pour DynamoDB](Point-in-time-recovery.md) sur cette table en exécutant les étapes suivantes :

   1. Cliquez sur le nom de la table pour l’ouvrir.

   1. Choisissez **Sauvegarde**.

   1. Choisissez **Modifier** dans la section **Point-in-time de restauration (PITR)**.

   1. Sur la page **Modifier les paramètres de point-in-time restauration**, choisissez **Activer la point-in-time restauration**.

   1. Sélectionnez **Enregistrer les modifications**.

## AWS CLI
<a name="getting-started-step-1-CLI"></a>

L' AWS CLI exemple suivant crée une nouvelle `Music` table à l'aide de`create-table`.

**Linux**

```
aws dynamodb create-table \
    --table-name Music \
    --attribute-definitions \
        AttributeName=Artist,AttributeType=S \
        AttributeName=SongTitle,AttributeType=S \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --billing-mode PAY_PER_REQUEST \
    --table-class STANDARD
```

**Windows CMD**

```
aws dynamodb create-table ^
    --table-name Music ^
    --attribute-definitions ^
        AttributeName=Artist,AttributeType=S ^
        AttributeName=SongTitle,AttributeType=S ^
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE ^
    --billing-mode PAY_PER_REQUEST ^
    --table-class STANDARD
```

L’utilisation de `create-table` renvoie l’exemple de résultat suivant.

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "Music",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2023-03-29T12:11:43.379000-04:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 5,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-east-1:111122223333:table/Music",
        "TableId": "60abf404-1839-4917-a89b-a8b0ab2a1b87",
        "TableClassSummary": {
            "TableClass": "STANDARD"
        }
    }
}
}
```

Veuillez noter que la valeur du champ `TableStatus` est définie sur `CREATING`.

Pour vérifier que DynamoDB a fini de créer la table `Music`, utilisez la commande `describe-table`. 

**Linux**

```
 aws dynamodb describe-table --table-name Music | grep TableStatus
```

**Windows CMD**

```
 aws dynamodb describe-table --table-name Music | findstr TableStatus
```

Cette commande renvoie le résultat suivant. Lorsque DynamoDB finit de créer la table, la valeur du champ `TableStatus` est définie sur `ACTIVE`. 

```
"TableStatus": "ACTIVE",
```

Une fois que la table a le statut `ACTIVE`, il est considéré comme une bonne pratique d’activer [Sauvegardes ponctuelles pour DynamoDB](Point-in-time-recovery.md) sur cette table en exécutant les commandes suivantes.

**Linux**

```
aws dynamodb update-continuous-backups \ 
    --table-name Music \ 
    --point-in-time-recovery-specification \ 
        PointInTimeRecoveryEnabled=true
```

**Windows CMD**

```
aws dynamodb update-continuous-backups --table-name Music --point-in-time-recovery-specification PointInTimeRecoveryEnabled=true
```

Cette commande renvoie le résultat suivant.

```
{
    "ContinuousBackupsDescription": {
        "ContinuousBackupsStatus": "ENABLED",
        "PointInTimeRecoveryDescription": {
            "PointInTimeRecoveryStatus": "ENABLED",
            "EarliestRestorableDateTime": "2023-03-29T12:18:19-04:00",
            "LatestRestorableDateTime": "2023-03-29T12:18:19-04:00"
        }
    }
}
```

**Note**  
L'activation de sauvegardes continues avec point-in-time restauration entraîne des implications financières. Pour plus d’informations sur la tarification, veuillez consulter [Tarification Amazon DynamoDB](https://aws.amazon.com/dynamodb/pricing).

## AWS SDK
<a name="getting-started-step-1-SDK"></a>

Les exemples de code suivants montrent comment créer une table DynamoDB à l’aide d’un kit AWS SDK.

------
#### [ .NET ]

**SDK pour .NET (v4)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples). 

```
    /// <summary>
    /// Creates a new Amazon DynamoDB table and then waits for the new
    /// table to become active.
    /// </summary>
    /// <param name="tableName">The name of the table to create.</param>
    /// <returns>A Boolean value indicating the success of the operation.</returns>
    public async Task<bool> CreateMovieTableAsync(string tableName)
    {
        try
        {
            var response = await _amazonDynamoDB.CreateTableAsync(new CreateTableRequest
            {
                TableName = tableName,
                AttributeDefinitions = new List<AttributeDefinition>()
                {
                    new AttributeDefinition
                    {
                        AttributeName = "title",
                        AttributeType = ScalarAttributeType.S,
                    },
                    new AttributeDefinition
                    {
                        AttributeName = "year",
                        AttributeType = ScalarAttributeType.N,
                    },
                },
                KeySchema = new List<KeySchemaElement>()
                {
                    new KeySchemaElement
                    {
                        AttributeName = "year",
                        KeyType = KeyType.HASH,
                    },
                    new KeySchemaElement
                    {
                        AttributeName = "title",
                        KeyType = KeyType.RANGE,
                    },
                },
                BillingMode = BillingMode.PAY_PER_REQUEST,
            });

            // Wait until the table is ACTIVE and then report success.
            Console.Write("Waiting for table to become active...");

            var request = new DescribeTableRequest
            {
                TableName = response.TableDescription.TableName,
            };

            TableStatus status;

            int sleepDuration = 2000;

            do
            {
                Thread.Sleep(sleepDuration);

                var describeTableResponse = await _amazonDynamoDB.DescribeTableAsync(request);
                status = describeTableResponse.Table.TableStatus;

                Console.Write(".");
            }
            while (status != "ACTIVE");

            return status == TableStatus.ACTIVE;
        }
        catch (ResourceInUseException ex)
        {
            Console.WriteLine($"Table {tableName} already exists. {ex.Message}");
            throw;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while creating table {tableName}. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating table {tableName}. {ex.Message}");
            throw;
        }
    }
```
+  Pour plus de détails sur l'API, reportez-vous [CreateTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/CreateTable)à la section *Référence des AWS SDK pour .NET API*. 

------
#### [ Bash ]

**AWS CLI avec le script Bash**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples). 

```
###############################################################################
# function dynamodb_create_table
#
# This function creates an Amazon DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table to create.
#       -a attribute_definitions -- JSON file path of a list of attributes and their types.
#       -k key_schema -- JSON file path of a list of attributes and their key types.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function dynamodb_create_table() {
  local table_name attribute_definitions key_schema response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_create_table"
    echo "Creates an Amazon DynamoDB table with on-demand billing."
    echo " -n table_name  -- The name of the table to create."
    echo " -a attribute_definitions -- JSON file path of a list of attributes and their types."
    echo " -k key_schema -- JSON file path of a list of attributes and their key types."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:a:k:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      a) attribute_definitions="${OPTARG}" ;;
      k) key_schema="${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 "$attribute_definitions" ]]; then
    errecho "ERROR: You must provide an attribute definitions json file path the -a parameter."
    usage
    return 1
  fi

  if [[ -z "$key_schema" ]]; then
    errecho "ERROR: You must provide a key schema json file path the -k parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    attribute_definitions:   $attribute_definitions"
  iecho "    key_schema:   $key_schema"
  iecho ""

  response=$(aws dynamodb create-table \
    --table-name "$table_name" \
    --attribute-definitions file://"$attribute_definitions" \
    --billing-mode PAY_PER_REQUEST \
    --key-schema file://"$key_schema" )

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-table operation failed.$response"
    return 1
  fi

  return 0
}
```
Fonctions utilitaires utilisées dans cet exemple.  

```
###############################################################################
# function iecho
#
# This function enables the script to display the specified text only if
# the global variable $VERBOSE is set to true.
###############################################################################
function iecho() {
  if [[ $VERBOSE == true ]]; then
    echo "$@"
  fi
}

###############################################################################
# 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 plus de détails sur l'API, voir [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)la section *Référence des AWS CLI commandes*. 

------
#### [ C\$1\$1 ]

**SDK pour C\$1\$1**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples). 

```
//! Create an Amazon DynamoDB table.
/*!
  \sa createTable()
  \param tableName: Name for the DynamoDB table.
  \param primaryKey: Primary key for the DynamoDB table.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::createTable(const Aws::String &tableName,
                                   const Aws::String &primaryKey,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::cout << "Creating table " << tableName <<
              " with a simple primary key: \"" << primaryKey << "\"." << std::endl;

    Aws::DynamoDB::Model::CreateTableRequest request;

    Aws::DynamoDB::Model::AttributeDefinition hashKey;
    hashKey.SetAttributeName(primaryKey);
    hashKey.SetAttributeType(Aws::DynamoDB::Model::ScalarAttributeType::S);
    request.AddAttributeDefinitions(hashKey);

    Aws::DynamoDB::Model::KeySchemaElement keySchemaElement;
    keySchemaElement.WithAttributeName(primaryKey).WithKeyType(
            Aws::DynamoDB::Model::KeyType::HASH);
    request.AddKeySchema(keySchemaElement);

    Aws::DynamoDB::Model::ProvisionedThroughput throughput;
    throughput.WithReadCapacityUnits(5).WithWriteCapacityUnits(5);
    request.SetProvisionedThroughput(throughput);
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::CreateTableOutcome &outcome = dynamoClient.CreateTable(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Table \""
                  << outcome.GetResult().GetTableDescription().GetTableName() <<
                  " created!" << std::endl;
    }
    else {
        std::cerr << "Failed to create table: " << outcome.GetError().GetMessage()
                  << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```
Code qui attend que la table soit active.  

```
//! Query a newly created DynamoDB table until it is active.
/*!
  \sa waitTableActive()
  \param waitTableActive: The DynamoDB table's name.
  \param dynamoClient: A DynamoDB client.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::waitTableActive(const Aws::String &tableName,
                                       const Aws::DynamoDB::DynamoDBClient &dynamoClient) {

    // Repeatedly call DescribeTable until table is ACTIVE.
    const int MAX_QUERIES = 20;
    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    int count = 0;
    while (count < MAX_QUERIES) {
        const Aws::DynamoDB::Model::DescribeTableOutcome &result = dynamoClient.DescribeTable(
                request);
        if (result.IsSuccess()) {
            Aws::DynamoDB::Model::TableStatus status = result.GetResult().GetTable().GetTableStatus();

            if (Aws::DynamoDB::Model::TableStatus::ACTIVE != status) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                return true;
            }
        }
        else {
            std::cerr << "Error DynamoDB::waitTableActive "
                      << result.GetError().GetMessage() << std::endl;
            return false;
        }
        count++;
    }
    return false;
}
```
+  Pour plus de détails sur l'API, reportez-vous [CreateTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/CreateTable)à la section *Référence des AWS SDK pour C\$1\$1 API*. 

------
#### [ CLI ]

**AWS CLI**  
**Exemple 1 : pour créer une table avec des balises**  
L’exemple `create-table` suivant utilise les attributs et le schéma de clés spécifiés pour créer une table nommée `MusicCollection`. Cette table utilise le débit provisionné et est chiffrée au repos à l'aide de la clé CMK AWS détenue par défaut. La commande applique également une balise à la table, avec une clé `Owner` et une valeur `blueTeam`.  

```
aws dynamodb create-table \
    --table-name MusicCollection \
    --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
    --tags Key=Owner,Value=blueTeam
```
Sortie :  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "WriteCapacityUnits": 5,
            "ReadCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "TableName": "MusicCollection",
        "TableStatus": "CREATING",
        "KeySchema": [
            {
                "KeyType": "HASH",
                "AttributeName": "Artist"
            },
            {
                "KeyType": "RANGE",
                "AttributeName": "SongTitle"
            }
        ],
        "ItemCount": 0,
        "CreationDateTime": "2020-05-26T16:04:41.627000-07:00",
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    }
}
```
Pour plus d’informations, consultez [Opérations de base pour les tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 2 : pour créer une table en mode à la demande**  
L’exemple suivant crée une table appelée `MusicCollection` en mode à la demande, plutôt qu’en mode débit provisionné. Cela est utile pour les tables dont les charges de travail sont imprévisibles.  

```
aws dynamodb create-table \
    --table-name MusicCollection \
    --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --billing-mode PAY_PER_REQUEST
```
Sortie :  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollection",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-05-27T11:44:10.807000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 0,
            "WriteCapacityUnits": 0
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "BillingModeSummary": {
            "BillingMode": "PAY_PER_REQUEST"
        }
    }
}
```
Pour plus d’informations, consultez [Opérations de base pour les tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 3 : pour créer une table et la chiffrer à l’aide d’une clé CMK gérée par le client**  
L’exemple suivant crée une table nommée `MusicCollection` et la chiffre à l’aide d’une clé CMK gérée par le client.  

```
aws dynamodb create-table \
    --table-name MusicCollection \
    --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
    --sse-specification Enabled=true,SSEType=KMS,KMSMasterKeyId=abcd1234-abcd-1234-a123-ab1234a1b234
```
Sortie :  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollection",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-05-27T11:12:16.431000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 5,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "SSEDescription": {
            "Status": "ENABLED",
            "SSEType": "KMS",
            "KMSMasterKeyArn": "arn:aws:kms:us-west-2:123456789012:key/abcd1234-abcd-1234-a123-ab1234a1b234"
        }
    }
}
```
Pour plus d’informations, consultez [Opérations de base pour les tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 4 : pour créer une table avec un index secondaire local**  
L’exemple suivant utilise les attributs et le schéma de clés spécifiés pour créer une table nommée `MusicCollection` avec un index local secondaire nommé `AlbumTitleIndex`.  

```
aws dynamodb create-table \
    --table-name MusicCollection \
    --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S AttributeName=AlbumTitle,AttributeType=S \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --local-secondary-indexes \
        "[
            {
                \"IndexName\": \"AlbumTitleIndex\",
                \"KeySchema\": [
                    {\"AttributeName\": \"Artist\",\"KeyType\":\"HASH\"},
                    {\"AttributeName\": \"AlbumTitle\",\"KeyType\":\"RANGE\"}
                ],
                \"Projection\": {
                    \"ProjectionType\": \"INCLUDE\",
                    \"NonKeyAttributes\": [\"Genre\", \"Year\"]
                }
            }
        ]"
```
Sortie :  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "AlbumTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollection",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-05-26T15:59:49.473000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "LocalSecondaryIndexes": [
            {
                "IndexName": "AlbumTitleIndex",
                "KeySchema": [
                    {
                        "AttributeName": "Artist",
                        "KeyType": "HASH"
                    },
                    {
                        "AttributeName": "AlbumTitle",
                        "KeyType": "RANGE"
                    }
                ],
                "Projection": {
                    "ProjectionType": "INCLUDE",
                    "NonKeyAttributes": [
                        "Genre",
                        "Year"
                    ]
                },
                "IndexSizeBytes": 0,
                "ItemCount": 0,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/index/AlbumTitleIndex"
            }
        ]
    }
}
```
Pour plus d’informations, consultez [Opérations de base pour les tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 5 : pour créer une table avec un index secondaire global**  
L’exemple suivant crée une table nommée `GameScores` avec un index secondaire global nommé `GameTitleIndex`. La table de base a une clé de partition `UserId` et une clé de tri `GameTitle`, vous permettant de trouver efficacement le meilleur score d’un utilisateur pour un jeu spécifique, tandis que l’index secondaire global (GSI) a une clé de partition `GameTitle` et une clé de tri `TopScore`, vous permettant de trouver rapidement le score le plus élevé pour un jeu particulier.  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S AttributeName=TopScore,AttributeType=N \
    --key-schema AttributeName=UserId,KeyType=HASH \
                AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --global-secondary-indexes \
        "[
            {
                \"IndexName\": \"GameTitleIndex\",
                \"KeySchema\": [
                    {\"AttributeName\":\"GameTitle\",\"KeyType\":\"HASH\"},
                    {\"AttributeName\":\"TopScore\",\"KeyType\":\"RANGE\"}
                ],
                \"Projection\": {
                    \"ProjectionType\":\"INCLUDE\",
                    \"NonKeyAttributes\":[\"UserId\"]
                },
                \"ProvisionedThroughput\": {
                    \"ReadCapacityUnits\": 10,
                    \"WriteCapacityUnits\": 5
                }
            }
        ]"
```
Sortie :  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "TopScore",
                "AttributeType": "N"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-05-26T17:28:15.602000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "GlobalSecondaryIndexes": [
            {
                "IndexName": "GameTitleIndex",
                "KeySchema": [
                    {
                        "AttributeName": "GameTitle",
                        "KeyType": "HASH"
                    },
                    {
                        "AttributeName": "TopScore",
                        "KeyType": "RANGE"
                    }
                ],
                "Projection": {
                    "ProjectionType": "INCLUDE",
                    "NonKeyAttributes": [
                        "UserId"
                    ]
                },
                "IndexStatus": "CREATING",
                "ProvisionedThroughput": {
                    "NumberOfDecreasesToday": 0,
                    "ReadCapacityUnits": 10,
                    "WriteCapacityUnits": 5
                },
                "IndexSizeBytes": 0,
                "ItemCount": 0,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/index/GameTitleIndex"
            }
        ]
    }
}
```
Pour plus d’informations, consultez [Opérations de base pour les tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 6 : pour créer une table avec plusieurs index secondaires globaux à la fois**  
L’exemple suivant crée une table nommée `GameScores` avec deux index secondaires globaux. Les schémas GSI sont transmis via un fichier plutôt que sur la ligne de commande.  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S AttributeName=TopScore,AttributeType=N AttributeName=Date,AttributeType=S \
    --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --global-secondary-indexes file://gsi.json
```
Contenu de `gsi.json` :  

```
[
    {
        "IndexName": "GameTitleIndex",
        "KeySchema": [
            {
                "AttributeName": "GameTitle",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "TopScore",
                "KeyType": "RANGE"
            }
        ],
        "Projection": {
            "ProjectionType": "ALL"
        },
        "ProvisionedThroughput": {
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        }
    },
    {
        "IndexName": "GameDateIndex",
        "KeySchema": [
            {
                "AttributeName": "GameTitle",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "Date",
                "KeyType": "RANGE"
            }
        ],
        "Projection": {
            "ProjectionType": "ALL"
        },
        "ProvisionedThroughput": {
            "ReadCapacityUnits": 5,
            "WriteCapacityUnits": 5
        }
    }
]
```
Sortie :  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Date",
                "AttributeType": "S"
            },
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "TopScore",
                "AttributeType": "N"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-08-04T16:40:55.524000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "GlobalSecondaryIndexes": [
            {
                "IndexName": "GameTitleIndex",
                "KeySchema": [
                    {
                        "AttributeName": "GameTitle",
                        "KeyType": "HASH"
                    },
                    {
                        "AttributeName": "TopScore",
                        "KeyType": "RANGE"
                    }
                ],
                "Projection": {
                    "ProjectionType": "ALL"
                },
                "IndexStatus": "CREATING",
                "ProvisionedThroughput": {
                    "NumberOfDecreasesToday": 0,
                    "ReadCapacityUnits": 10,
                    "WriteCapacityUnits": 5
                },
                "IndexSizeBytes": 0,
                "ItemCount": 0,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/index/GameTitleIndex"
            },
            {
                "IndexName": "GameDateIndex",
                "KeySchema": [
                    {
                        "AttributeName": "GameTitle",
                        "KeyType": "HASH"
                    },
                    {
                        "AttributeName": "Date",
                        "KeyType": "RANGE"
                    }
                ],
                "Projection": {
                    "ProjectionType": "ALL"
                },
                "IndexStatus": "CREATING",
                "ProvisionedThroughput": {
                    "NumberOfDecreasesToday": 0,
                    "ReadCapacityUnits": 5,
                    "WriteCapacityUnits": 5
                },
                "IndexSizeBytes": 0,
                "ItemCount": 0,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/index/GameDateIndex"
            }
        ]
    }
}
```
Pour plus d’informations, consultez [Opérations de base pour les tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 7 : pour créer une table avec Streams activé**  
L’exemple suivant crée une table appelée `GameScores` avec DynamoDB Streams activé. Les nouvelles et les anciennes images de chaque élément seront écrites dans le flux.  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S \
    --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --stream-specification StreamEnabled=TRUE,StreamViewType=NEW_AND_OLD_IMAGES
```
Sortie :  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-05-27T10:49:34.056000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "StreamSpecification": {
            "StreamEnabled": true,
            "StreamViewType": "NEW_AND_OLD_IMAGES"
        },
        "LatestStreamLabel": "2020-05-27T17:49:34.056",
        "LatestStreamArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/stream/2020-05-27T17:49:34.056"
    }
}
```
Pour plus d’informations, consultez [Opérations de base pour les tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 8 : pour créer une table avec Keys-Only Stream activé**  
L’exemple suivant crée une table appelée `GameScores` avec DynamoDB Streams activé. Seuls les attributs clés des éléments modifiés sont écrits dans le flux.  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S \
    --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --stream-specification StreamEnabled=TRUE,StreamViewType=KEYS_ONLY
```
Sortie :  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2023-05-25T18:45:34.140000+00:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "StreamSpecification": {
            "StreamEnabled": true,
            "StreamViewType": "KEYS_ONLY"
        },
        "LatestStreamLabel": "2023-05-25T18:45:34.140",
        "LatestStreamArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/stream/2023-05-25T18:45:34.140",
        "DeletionProtectionEnabled": false
    }
}
```
Pour plus d’informations, consultez [Modifier la récupération de données pour DynamoDB Streams](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 9 : pour créer une table à l’aide de la classe Standard Infrequent Access**  
L’exemple suivant crée une table appelée `GameScores` et attribue la classe de table Standard-Infrequent Access (DynamoDB Standard-IA). Cette classe de table est optimisée pour le stockage, qui constitue le principal coût.  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S \
    --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --table-class STANDARD_INFREQUENT_ACCESS
```
Sortie :  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2023-05-25T18:33:07.581000+00:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "TableClassSummary": {
            "TableClass": "STANDARD_INFREQUENT_ACCESS"
        },
        "DeletionProtectionEnabled": false
    }
}
```
Pour plus d’informations, consultez [Classes de tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.TableClasses.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 10 : pour créer une table avec la protection contre la suppression activée**  
L’exemple suivant crée une table appelée `GameScores` et active la protection contre la suppression.  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S \
    --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --deletion-protection-enabled
```
Sortie :  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2023-05-25T23:02:17.093000+00:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "DeletionProtectionEnabled": true
    }
}
```
Pour plus d’informations, consultez [Utilisation de la protection contre la suppression](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeletionProtection) dans le *Guide du développeur Amazon DynamoDB*.  
+  Pour plus de détails sur l'API, voir [CreateTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/create-table.html)la section *Référence des AWS CLI commandes*. 

------
#### [ Go ]

**Kit SDK pour Go V2**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples). 

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

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



// CreateMovieTable creates a DynamoDB table with a composite primary key defined as
// a string sort key named `title`, and a numeric partition key named `year`.
// This function uses NewTableExistsWaiter to wait for the table to be created by
// DynamoDB before it returns.
func (basics TableBasics) CreateMovieTable(ctx context.Context) (*types.TableDescription, error) {
	var tableDesc *types.TableDescription
	table, err := basics.DynamoDbClient.CreateTable(ctx, &dynamodb.CreateTableInput{
		AttributeDefinitions: []types.AttributeDefinition{{
			AttributeName: aws.String("year"),
			AttributeType: types.ScalarAttributeTypeN,
		}, {
			AttributeName: aws.String("title"),
			AttributeType: types.ScalarAttributeTypeS,
		}},
		KeySchema: []types.KeySchemaElement{{
			AttributeName: aws.String("year"),
			KeyType:       types.KeyTypeHash,
		}, {
			AttributeName: aws.String("title"),
			KeyType:       types.KeyTypeRange,
		}},
		TableName:   aws.String(basics.TableName),
		BillingMode: types.BillingModePayPerRequest,
	})
	if err != nil {
		log.Printf("Couldn't create table %v. Here's why: %v\n", basics.TableName, err)
	} else {
		waiter := dynamodb.NewTableExistsWaiter(basics.DynamoDbClient)
		err = waiter.Wait(ctx, &dynamodb.DescribeTableInput{
			TableName: aws.String(basics.TableName)}, 5*time.Minute)
		if err != nil {
			log.Printf("Wait for table exists failed. Here's why: %v\n", err)
		}
		tableDesc = table.TableDescription
		log.Printf("Ccreating table test")
	}
	return tableDesc, err
}
```
+  Pour plus de détails sur l'API, reportez-vous [CreateTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.CreateTable)à la section *Référence des AWS SDK pour Go API*. 

------
#### [ Java ]

**SDK pour Java 2.x**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 

```
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.BillingMode;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.OnDemandThroughput;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class CreateTable {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <tableName> <key>

            Where:
                tableName - The Amazon DynamoDB table to create (for example, Music3).
                key - The key for the Amazon DynamoDB table (for example, Artist).
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String key = args[1];
        System.out.println("Creating an Amazon DynamoDB table " + tableName + " with a simple primary key: " + key);
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
            .region(region)
            .build();

        String result = createTable(ddb, tableName, key);
        System.out.println("New table is " + result);
        ddb.close();
    }

    public static String createTable(DynamoDbClient ddb, String tableName, String key) {
        DynamoDbWaiter dbWaiter = ddb.waiter();
        CreateTableRequest request = CreateTableRequest.builder()
            .attributeDefinitions(AttributeDefinition.builder()
                .attributeName(key)
                .attributeType(ScalarAttributeType.S)
                .build())
            .keySchema(KeySchemaElement.builder()
                .attributeName(key)
                .keyType(KeyType.HASH)
                .build())
            .billingMode(BillingMode.PAY_PER_REQUEST) //  DynamoDB automatically scales based on traffic.
            .tableName(tableName)
            .build();

        String newTable;
        try {
            CreateTableResponse response = ddb.createTable(request);
            DescribeTableRequest tableRequest = DescribeTableRequest.builder()
                .tableName(tableName)
                .build();

            // Wait until the Amazon DynamoDB table is created.
            WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            newTable = response.tableDescription().tableName();
            return newTable;

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  Pour plus de détails sur l'API, reportez-vous [CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/CreateTable)à la section *Référence des AWS SDK for Java 2.x API*. 

------
#### [ JavaScript ]

**SDK pour JavaScript (v3)**  
 Il y en a plus sur GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le [ référentiel d'exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 

```
import { CreateTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb";

const client = new DynamoDBClient({});

export const main = async () => {
  const command = new CreateTableCommand({
    TableName: "EspressoDrinks",
    // For more information about data types,
    // see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes and
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors
    AttributeDefinitions: [
      {
        AttributeName: "DrinkName",
        AttributeType: "S",
      },
    ],
    KeySchema: [
      {
        AttributeName: "DrinkName",
        KeyType: "HASH",
      },
    ],
    BillingMode: "PAY_PER_REQUEST",
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  Pour plus d’informations, consultez le [Guide du développeur AWS SDK pour JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table). 
+  Pour plus de détails sur l'API, reportez-vous [CreateTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/CreateTableCommand)à la section *Référence des AWS SDK pour JavaScript API*. 

**SDK pour JavaScript (v2)**  
 Il y en a plus sur GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le [ référentiel d'exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples). 

```
// 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 = {
  AttributeDefinitions: [
    {
      AttributeName: "CUSTOMER_ID",
      AttributeType: "N",
    },
    {
      AttributeName: "CUSTOMER_NAME",
      AttributeType: "S",
    },
  ],
  KeySchema: [
    {
      AttributeName: "CUSTOMER_ID",
      KeyType: "HASH",
    },
    {
      AttributeName: "CUSTOMER_NAME",
      KeyType: "RANGE",
    },
  ],
  ProvisionedThroughput: {
    ReadCapacityUnits: 1,
    WriteCapacityUnits: 1,
  },
  TableName: "CUSTOMER_LIST",
  StreamSpecification: {
    StreamEnabled: false,
  },
};

// Call DynamoDB to create the table
ddb.createTable(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Table Created", data);
  }
});
```
+  Pour plus d’informations, consultez le [Guide du développeur AWS SDK pour JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table). 
+  Pour plus de détails sur l'API, reportez-vous [CreateTable](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/CreateTable)à la section *Référence des AWS SDK pour JavaScript API*. 

------
#### [ Kotlin ]

**SDK pour Kotlin**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples). 

```
suspend fun createNewTable(
    tableNameVal: String,
    key: String,
): String? {
    val attDef =
        AttributeDefinition {
            attributeName = key
            attributeType = ScalarAttributeType.S
        }

    val keySchemaVal =
        KeySchemaElement {
            attributeName = key
            keyType = KeyType.Hash
        }

    val request =
        CreateTableRequest {
            attributeDefinitions = listOf(attDef)
            keySchema = listOf(keySchemaVal)
            billingMode = BillingMode.PayPerRequest
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        var tableArn: String
        val response = ddb.createTable(request)
        ddb.waitUntilTableExists {
            // suspend call
            tableName = tableNameVal
        }
        tableArn = response.tableDescription!!.tableArn.toString()
        println("Table $tableArn is ready")
        return tableArn
    }
}
```
+  Pour plus de détails sur l'API, consultez [CreateTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)la section *AWS SDK pour la référence de l'API Kotlin*. 

------
#### [ PHP ]

**Kit SDK pour PHP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples). 
Créer une table.  

```
        $tableName = "ddb_demo_table_$uuid";
        $service->createTable(
            $tableName,
            [
                new DynamoDBAttribute('year', 'N', 'HASH'),
                new DynamoDBAttribute('title', 'S', 'RANGE')
            ]
        );

    public function createTable(string $tableName, array $attributes)
    {
        $keySchema = [];
        $attributeDefinitions = [];
        foreach ($attributes as $attribute) {
            if (is_a($attribute, DynamoDBAttribute::class)) {
                $keySchema[] = ['AttributeName' => $attribute->AttributeName, 'KeyType' => $attribute->KeyType];
                $attributeDefinitions[] =
                    ['AttributeName' => $attribute->AttributeName, 'AttributeType' => $attribute->AttributeType];
            }
        }

        $this->dynamoDbClient->createTable([
            'TableName' => $tableName,
            'KeySchema' => $keySchema,
            'AttributeDefinitions' => $attributeDefinitions,
            'ProvisionedThroughput' => ['ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 10],
        ]);
    }
```
+  Pour plus de détails sur l'API, reportez-vous [CreateTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/CreateTable)à la section *Référence des AWS SDK pour PHP API*. 

------
#### [ PowerShell ]

**Outils pour PowerShell V4**  
**Exemple 1 : Cet exemple crée une table nommée Thread dont la clé primaire est composée de « ForumName » (hachage de type de clé) et de « Subject » (plage de types de clés). Le schéma utilisé pour construire la table peut être redirigé vers chaque applet de commande comme indiqué ou spécifié à l’aide du paramètre -Schema.**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
$schema | Add-DDBKeySchema -KeyName "Subject" -KeyType RANGE -KeyDataType "S"
$schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**Sortie** :  

```
AttributeDefinitions   : {ForumName, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {}
```
**Exemple 2 : Cet exemple crée une table nommée Thread dont la clé primaire est composée de « ForumName » (hachage de type de clé) et de « Subject » (plage de types de clés). Un index secondaire local est également défini. La clé de l'index secondaire local sera définie automatiquement à partir de la clé de hachage principale de la table (ForumName). Le schéma utilisé pour construire la table peut être redirigé vers chaque applet de commande comme indiqué ou spécifié à l’aide du paramètre -Schema.**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
$schema | Add-DDBKeySchema -KeyName "Subject" -KeyDataType "S"
$schema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only"
$schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**Sortie** :  

```
AttributeDefinitions   : {ForumName, LastPostDateTime, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {LastPostIndex}
```
**Exemple 3 : Cet exemple montre comment utiliser un pipeline unique pour créer une table nommée Thread qui possède une clé primaire composée de « ForumName » (hachage de type de clé) et de « Subject » (plage de types de clés) et un index secondaire local. Les options Add- DDBKey Schema et Add- DDBIndex Schema créent un nouvel TableSchema objet pour vous si aucun objet n'est fourni par le pipeline ou le paramètre -Schema.**  

```
New-DDBTableSchema |
  Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S" |
  Add-DDBKeySchema -KeyName "Subject" -KeyDataType "S" |
  Add-DDBIndexSchema -IndexName "LastPostIndex" `
                     -RangeKeyName "LastPostDateTime" `
                     -RangeKeyDataType "S" `
                     -ProjectionType "keys_only" |
  New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**Sortie** :  

```
AttributeDefinitions   : {ForumName, LastPostDateTime, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {LastPostIndex}
```
+  Pour plus de détails sur l'API, reportez-vous [CreateTable](https://docs.aws.amazon.com/powershell/v4/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V4)*. 

**Outils pour PowerShell V5**  
**Exemple 1 : Cet exemple crée une table nommée Thread dont la clé primaire est composée de « ForumName » (hachage de type de clé) et de « Subject » (plage de types de clés). Le schéma utilisé pour construire la table peut être redirigé vers chaque applet de commande comme indiqué ou spécifié à l’aide du paramètre -Schema.**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
$schema | Add-DDBKeySchema -KeyName "Subject" -KeyType RANGE -KeyDataType "S"
$schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**Sortie** :  

```
AttributeDefinitions   : {ForumName, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {}
```
**Exemple 2 : Cet exemple crée une table nommée Thread dont la clé primaire est composée de « ForumName » (hachage de type de clé) et de « Subject » (plage de types de clés). Un index secondaire local est également défini. La clé de l'index secondaire local sera définie automatiquement à partir de la clé de hachage principale de la table (ForumName). Le schéma utilisé pour construire la table peut être redirigé vers chaque applet de commande comme indiqué ou spécifié à l’aide du paramètre -Schema.**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
$schema | Add-DDBKeySchema -KeyName "Subject" -KeyDataType "S"
$schema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only"
$schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**Sortie** :  

```
AttributeDefinitions   : {ForumName, LastPostDateTime, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {LastPostIndex}
```
**Exemple 3 : Cet exemple montre comment utiliser un pipeline unique pour créer une table nommée Thread qui possède une clé primaire composée de « ForumName » (hachage de type de clé) et de « Subject » (plage de types de clés) et un index secondaire local. Les options Add- DDBKey Schema et Add- DDBIndex Schema créent un nouvel TableSchema objet pour vous si aucun objet n'est fourni par le pipeline ou le paramètre -Schema.**  

```
New-DDBTableSchema |
  Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S" |
  Add-DDBKeySchema -KeyName "Subject" -KeyDataType "S" |
  Add-DDBIndexSchema -IndexName "LastPostIndex" `
                     -RangeKeyName "LastPostDateTime" `
                     -RangeKeyDataType "S" `
                     -ProjectionType "keys_only" |
  New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**Sortie** :  

```
AttributeDefinitions   : {ForumName, LastPostDateTime, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {LastPostIndex}
```
+  Pour plus de détails sur l'API, reportez-vous [CreateTable](https://docs.aws.amazon.com/powershell/v5/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V5)*. 

------
#### [ Python ]

**Kit SDK for Python (Boto3)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 
Créez une table pour stocker des données vidéo.  

```
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 create_table(self, table_name):
        """
        Creates an Amazon DynamoDB table that can be used to store movie data.
        The table uses the release year of the movie as the partition key and the
        title as the sort key.

        :param table_name: The name of the table to create.
        :return: The newly created table.
        """
        try:
            self.table = self.dyn_resource.create_table(
                TableName=table_name,
                KeySchema=[
                    {"AttributeName": "year", "KeyType": "HASH"},  # Partition key
                    {"AttributeName": "title", "KeyType": "RANGE"},  # Sort key
                ],
                AttributeDefinitions=[
                    {"AttributeName": "year", "AttributeType": "N"},
                    {"AttributeName": "title", "AttributeType": "S"},
                ],
                BillingMode='PAY_PER_REQUEST',
            )
            self.table.wait_until_exists()
        except ClientError as err:
            logger.error(
                "Couldn't create table %s. Here's why: %s: %s",
                table_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return self.table
```
+  Pour plus de détails sur l'API, consultez [CreateTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/CreateTable)le *AWS manuel de référence de l'API SDK for Python (Boto3*). 

------
#### [ Ruby ]

**Kit SDK pour Ruby**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples). 

```
# Encapsulates an Amazon DynamoDB table of movie data.
class Scaffold
  attr_reader :dynamo_resource, :table_name, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table_name = table_name
    @table = nil
    @logger = Logger.new($stdout)
    @logger.level = Logger::DEBUG
  end

  # Creates an Amazon DynamoDB table that can be used to store movie data.
  # The table uses the release year of the movie as the partition key and the
  # title as the sort key.
  #
  # @param table_name [String] The name of the table to create.
  # @return [Aws::DynamoDB::Table] The newly created table.
  def create_table(table_name)
    @table = @dynamo_resource.create_table(
      table_name: table_name,
      key_schema: [
        { attribute_name: 'year', key_type: 'HASH' }, # Partition key
        { attribute_name: 'title', key_type: 'RANGE' } # Sort key
      ],
      attribute_definitions: [
        { attribute_name: 'year', attribute_type: 'N' },
        { attribute_name: 'title', attribute_type: 'S' }
      ],
      billing_mode: 'PAY_PER_REQUEST'
    )
    @dynamo_resource.client.wait_until(:table_exists, table_name: table_name)
    @table
  rescue Aws::DynamoDB::Errors::ServiceError => e
    @logger.error("Failed create table #{table_name}:\n#{e.code}: #{e.message}")
    raise
  end
```
+  Pour plus de détails sur l'API, reportez-vous [CreateTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/CreateTable)à la section *Référence des AWS SDK pour Ruby API*. 

------
#### [ Rust ]

**SDK pour Rust**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples). 

```
pub async fn create_table(
    client: &Client,
    table: &str,
    key: &str,
) -> Result<CreateTableOutput, Error> {
    let a_name: String = key.into();
    let table_name: String = table.into();

    let ad = AttributeDefinition::builder()
        .attribute_name(&a_name)
        .attribute_type(ScalarAttributeType::S)
        .build()
        .map_err(Error::BuildError)?;

    let ks = KeySchemaElement::builder()
        .attribute_name(&a_name)
        .key_type(KeyType::Hash)
        .build()
        .map_err(Error::BuildError)?;

    let create_table_response = client
        .create_table()
        .table_name(table_name)
        .key_schema(ks)
        .attribute_definitions(ad)
        .billing_mode(BillingMode::PayPerRequest)
        .send()
        .await;

    match create_table_response {
        Ok(out) => {
            println!("Added table {} with key {}", table, key);
            Ok(out)
        }
        Err(e) => {
            eprintln!("Got an error creating table:");
            eprintln!("{}", e);
            Err(Error::unhandled(e))
        }
    }
}
```
+  Pour plus de détails sur l'API, voir [CreateTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.create_table)la section de *référence de l'API AWS SDK for Rust*. 

------
#### [ SAP ABAP ]

**Kit SDK pour SAP ABAP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples). 

```
    TRY.
        DATA(lt_keyschema) = VALUE /aws1/cl_dynkeyschemaelement=>tt_keyschema(
          ( NEW /aws1/cl_dynkeyschemaelement( iv_attributename = 'year'
                                              iv_keytype = 'HASH' ) )
          ( NEW /aws1/cl_dynkeyschemaelement( iv_attributename = 'title'
                                              iv_keytype = 'RANGE' ) ) ).
        DATA(lt_attributedefinitions) = VALUE /aws1/cl_dynattributedefn=>tt_attributedefinitions(
          ( NEW /aws1/cl_dynattributedefn( iv_attributename = 'year'
                                           iv_attributetype = 'N' ) )
          ( NEW /aws1/cl_dynattributedefn( iv_attributename = 'title'
                                           iv_attributetype = 'S' ) ) ).

        " Adjust read/write capacities as desired.
        DATA(lo_dynprovthroughput)  = NEW /aws1/cl_dynprovthroughput(
          iv_readcapacityunits = 5
          iv_writecapacityunits = 5 ).
        oo_result = lo_dyn->createtable(
          it_keyschema = lt_keyschema
          iv_tablename = iv_table_name
          it_attributedefinitions = lt_attributedefinitions
          io_provisionedthroughput = lo_dynprovthroughput ).
        " Table creation can take some time. Wait till table exists before returning.
        lo_dyn->get_waiter( )->tableexists(
          iv_max_wait_time = 200
          iv_tablename     = iv_table_name ).
        MESSAGE 'DynamoDB Table' && iv_table_name && 'created.' TYPE 'I'.
        " This exception can happen if the table already exists.
      CATCH /aws1/cx_dynresourceinuseex INTO DATA(lo_resourceinuseex).
        DATA(lv_error) = |"{ lo_resourceinuseex->av_err_code }" - { lo_resourceinuseex->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  Pour plus de détails sur l'API, consultez [CreateTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)la section de référence du *AWS SDK pour l'API SAP ABAP*. 

------
#### [ Swift ]

**Kit SDK pour Swift**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples). 

```
import AWSDynamoDB


    ///
    /// Create a movie table in the Amazon DynamoDB data store.
    ///
    private func createTable() async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = CreateTableInput(
                attributeDefinitions: [
                    DynamoDBClientTypes.AttributeDefinition(attributeName: "year", attributeType: .n),
                    DynamoDBClientTypes.AttributeDefinition(attributeName: "title", attributeType: .s)
                ],
                billingMode: DynamoDBClientTypes.BillingMode.payPerRequest,
                keySchema: [
                    DynamoDBClientTypes.KeySchemaElement(attributeName: "year", keyType: .hash),
                    DynamoDBClientTypes.KeySchemaElement(attributeName: "title", keyType: .range)
                ],
                tableName: self.tableName
            )
            let output = try await client.createTable(input: input)
            if output.tableDescription == nil {
                throw MoviesError.TableNotFound
            }
        } catch {
            print("ERROR: createTable:", dump(error))
            throw error
        }
    }
```
+  Pour plus de détails sur l'API, reportez-vous [CreateTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/createtable(input:))à la section *AWS SDK pour la référence de l'API Swift*. 

------

Pour obtenir plus d’exemples avec DynamoDB, consultez [Exemples de code pour DynamoDB utilisant AWS SDKs](service_code_examples.md).

Une fois la nouvelle table créée, passez à l’ [Étape 2 : écrire des données dans une table DynamoDB](getting-started-step-2.md).

# Étape 2 : écrire des données dans une table DynamoDB
<a name="getting-started-step-2"></a>

Dans cette étape, vous insérez plusieurs éléments dans la table `Music` que vous avez créée dans [Étape 1 : création d’une table dans DynamoDB](getting-started-step-1.md). 

Pour plus d’informations sur les opérations d’écriture, consultez [Écriture d’un élément](WorkingWithItems.md#WorkingWithItems.WritingData).

## AWS Management Console
<a name="getting-started-step-2-Console"></a>

Suivez ces étapes pour écrire des données sur la table `Music` à l’aide de la console DynamoDB.

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

1. Dans le volet de navigation de gauche, choisissez **Tables**. 

1. Sur la page **Tables**, sélectionnez la table **Musique**.

1. Sélectionnez **Explorer les éléments de table**.

1. Dans la section **Éléments retournés**, choisissez **Créer un article**.

1. Sur la page **Créer un article**, procédez comme suit pour ajouter des éléments à la table :

   1. Choisissez **Ajouter un nouvel attribut**, puis choisissez **Numéro**.

   1. Dans Nom de l’attribut, entrez **Awards**.

   1. Répétez cette procédure pour créer un **AlbumTitle** de type **Chaîne**.

   1. Saisissez les valeurs suivantes pour votre élément :

      1. Pour **Artist (Artiste)**, saisissez **No One You Know**.

      1. Pour **SongTitle**, saisissez **Call Me Today**.

      1. Pour **AlbumTitle**, saisissez **Somewhat Famous**.

      1. Pour **Awards (Récompenses)**, saisissez **1**.

1. Choisissez **Créer un élément**.

1. Répétez cette procédure et créez un autre élément avec les valeurs suivantes :

   1. Pour **Artist (Artiste)**, saisissez **Acme Band**.

   1. Pour **SongTitle**entrer**Happy Day**.

   1. Pour **AlbumTitle**, saisissez **Songs About Life**.

   1. Pour **Awards (Récompenses)**, saisissez **10**.

1. Effectuez cette opération de nouveau pour créer un autre élément avec le même **Artist** (Artiste) qu’à l’étape précédente, mais avec des valeurs différentes pour les autres attributs :

   1. Pour **Artist (Artiste)**, saisissez **Acme Band**.

   1. Pour **SongTitle**entrer**PartiQL Rocks**.

   1. Pour **AlbumTitle**, saisissez **Another Album Title**.

   1. Pour **Awards (Récompenses)**, saisissez **8**.

## AWS CLI
<a name="getting-started-step-2-CLI"></a>

L' AWS CLI exemple suivant crée plusieurs nouveaux éléments dans le `Music` tableau. Vous pouvez procéder via l’API DynamoDB ou [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), un langage de requête compatible SQL pour DynamoDB.

------
#### [ DynamoDB API ]

**Linux**

```
aws dynamodb put-item \
    --table-name Music  \
    --item \
        '{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}, "AlbumTitle": {"S": "Somewhat Famous"}, "Awards": {"N": "1"}}'

aws dynamodb put-item \
    --table-name Music  \
    --item \
        '{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Howdy"}, "AlbumTitle": {"S": "Somewhat Famous"}, "Awards": {"N": "2"}}'

aws dynamodb put-item \
    --table-name Music \
    --item \
        '{"Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}, "AlbumTitle": {"S": "Songs About Life"}, "Awards": {"N": "10"}}'
                            
aws dynamodb put-item \
    --table-name Music \
    --item \
        '{"Artist": {"S": "Acme Band"}, "SongTitle": {"S": "PartiQL Rocks"}, "AlbumTitle": {"S": "Another Album Title"}, "Awards": {"N": "8"}}'
```

**Windows CMD**

```
aws dynamodb put-item ^
    --table-name Music  ^
    --item ^
        "{\"Artist\": {\"S\": \"No One You Know\"}, \"SongTitle\": {\"S\": \"Call Me Today\"}, \"AlbumTitle\": {\"S\": \"Somewhat Famous\"}, \"Awards\": {\"N\": \"1\"}}"

aws dynamodb put-item ^
    --table-name Music  ^
    --item ^
        "{\"Artist\": {\"S\": \"No One You Know\"}, \"SongTitle\": {\"S\": \"Howdy\"}, \"AlbumTitle\": {\"S\": \"Somewhat Famous\"}, \"Awards\": {\"N\": \"2\"}}"

aws dynamodb put-item ^
    --table-name Music ^
    --item ^
        "{\"Artist\": {\"S\": \"Acme Band\"}, \"SongTitle\": {\"S\": \"Happy Day\"}, \"AlbumTitle\": {\"S\": \"Songs About Life\"}, \"Awards\": {\"N\": \"10\"}}"
                            
aws dynamodb put-item ^
    --table-name Music ^
    --item ^
        "{\"Artist\": {\"S\": \"Acme Band\"}, \"SongTitle\": {\"S\": \"PartiQL Rocks\"}, \"AlbumTitle\": {\"S\": \"Another Album Title\"}, \"Awards\": {\"N\": \"8\"}}"
```

------
#### [ PartiQL for DynamoDB ]

**Linux**

```
aws dynamodb execute-statement --statement "INSERT INTO Music  \
                VALUE  \
                {'Artist':'No One You Know','SongTitle':'Call Me Today', 'AlbumTitle':'Somewhat Famous', 'Awards':'1'}"

aws dynamodb execute-statement --statement "INSERT INTO Music  \
                VALUE  \
                {'Artist':'No One You Know','SongTitle':'Howdy', 'AlbumTitle':'Somewhat Famous', 'Awards':'2'}"

aws dynamodb execute-statement --statement "INSERT INTO Music  \
                VALUE  \
                {'Artist':'Acme Band','SongTitle':'Happy Day', 'AlbumTitle':'Songs About Life', 'Awards':'10'}"
                            
aws dynamodb execute-statement --statement "INSERT INTO Music  \
                VALUE  \
                {'Artist':'Acme Band','SongTitle':'PartiQL Rocks', 'AlbumTitle':'Another Album Title', 'Awards':'8'}"
```

**Windows CMD**

```
aws dynamodb execute-statement --statement "INSERT INTO Music VALUE {'Artist':'No One You Know','SongTitle':'Call Me Today', 'AlbumTitle':'Somewhat Famous', 'Awards':'1'}"

aws dynamodb execute-statement --statement "INSERT INTO Music VALUE {'Artist':'No One You Know','SongTitle':'Howdy', 'AlbumTitle':'Somewhat Famous', 'Awards':'2'}"

aws dynamodb execute-statement --statement "INSERT INTO Music VALUE {'Artist':'Acme Band','SongTitle':'Happy Day', 'AlbumTitle':'Songs About Life', 'Awards':'10'}"
                            
aws dynamodb execute-statement --statement "INSERT INTO Music VALUE {'Artist':'Acme Band','SongTitle':'PartiQL Rocks', 'AlbumTitle':'Another Album Title', 'Awards':'8'}"
```

Pour plus d’informations sur l’écriture de données avec PartiQL, veuillez consulter [Instructions d’insertion de PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.insert.html).

------

Pour plus d’informations sur les types de données pris en charge dans DynamoDB, consultez [Types de données](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes). 

Pour plus d’informations sur la façon de représenter les types de données DynamoDB dans JSON, consultez [Valeurs d’attributs](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html). 

## AWS SDK
<a name="getting-started-step-2-SDK"></a>

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

------
#### [ .NET ]

**SDK pour .NET (v4)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples). 

```
    /// <summary>
    /// Adds a new item to the table.
    /// </summary>
    /// <param name="newMovie">A Movie object containing informtation for
    /// the movie to add to the table.</param>
    /// <param name="tableName">The name of the table where the item will be added.</param>
    /// <returns>A Boolean value that indicates the results of adding the item.</returns>
    public async Task<bool> PutItemAsync(Movie newMovie, string tableName)
    {
        try
        {
            var item = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = newMovie.Title },
                ["year"] = new AttributeValue { N = newMovie.Year.ToString() },
            };

            var request = new PutItemRequest
            {
                TableName = tableName,
                Item = item,
            };

            await _amazonDynamoDB.PutItemAsync(request);
            return true;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while putting item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while putting item. {ex.Message}");
            throw;
        }
    }
```
+  Pour plus de détails sur l'API, reportez-vous [PutItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/PutItem)à la section *Référence des AWS SDK pour .NET API*. 

------
#### [ Bash ]

**AWS CLI avec le script Bash**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples). 

```
##############################################################################
# function dynamodb_put_item
#
# This function puts an item into a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -i item  -- Path to json file containing the item values.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
##############################################################################
function dynamodb_put_item() {
  local table_name item response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_put_item"
    echo "Put an item into a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -i item  -- Path to json file containing the item values."
    echo ""
  }

  while getopts "n:i:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      i) item="${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 "$item" ]]; then
    errecho "ERROR: You must provide an item with the -i parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    item:   $item"
  iecho ""
  iecho ""

  response=$(aws dynamodb put-item \
    --table-name "$table_name" \
    --item file://"$item")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports put-item operation failed.$response"
    return 1
  fi

  return 0

}
```
Fonctions utilitaires utilisées dans cet exemple.  

```
###############################################################################
# function iecho
#
# This function enables the script to display the specified text only if
# the global variable $VERBOSE is set to true.
###############################################################################
function iecho() {
  if [[ $VERBOSE == true ]]; then
    echo "$@"
  fi
}

###############################################################################
# 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 plus de détails sur l'API, voir [PutItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem)la section *Référence des AWS CLI commandes*. 

------
#### [ C\$1\$1 ]

**SDK pour C\$1\$1**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples). 

```
//! Put an item in an Amazon DynamoDB table.
/*!
  \sa putItem()
  \param tableName: The table name.
  \param artistKey: The artist key. This is the partition key for the table.
  \param artistValue: The artist value.
  \param albumTitleKey: The album title key.
  \param albumTitleValue: The album title value.
  \param awardsKey: The awards key.
  \param awardsValue: The awards value.
  \param songTitleKey: The song title key.
  \param songTitleValue: The song title value.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::putItem(const Aws::String &tableName,
                               const Aws::String &artistKey,
                               const Aws::String &artistValue,
                               const Aws::String &albumTitleKey,
                               const Aws::String &albumTitleValue,
                               const Aws::String &awardsKey,
                               const Aws::String &awardsValue,
                               const Aws::String &songTitleKey,
                               const Aws::String &songTitleValue,
                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::PutItemRequest putItemRequest;
    putItemRequest.SetTableName(tableName);

    putItemRequest.AddItem(artistKey, Aws::DynamoDB::Model::AttributeValue().SetS(
            artistValue)); // This is the hash key.
    putItemRequest.AddItem(albumTitleKey, Aws::DynamoDB::Model::AttributeValue().SetS(
            albumTitleValue));
    putItemRequest.AddItem(awardsKey,
                           Aws::DynamoDB::Model::AttributeValue().SetS(awardsValue));
    putItemRequest.AddItem(songTitleKey,
                           Aws::DynamoDB::Model::AttributeValue().SetS(songTitleValue));

    const Aws::DynamoDB::Model::PutItemOutcome outcome = dynamoClient.PutItem(
            putItemRequest);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully added Item!" << std::endl;
    }
    else {
        std::cerr << outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```
Code qui attend que la table soit active.  

```
//! Query a newly created DynamoDB table until it is active.
/*!
  \sa waitTableActive()
  \param waitTableActive: The DynamoDB table's name.
  \param dynamoClient: A DynamoDB client.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::waitTableActive(const Aws::String &tableName,
                                       const Aws::DynamoDB::DynamoDBClient &dynamoClient) {

    // Repeatedly call DescribeTable until table is ACTIVE.
    const int MAX_QUERIES = 20;
    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    int count = 0;
    while (count < MAX_QUERIES) {
        const Aws::DynamoDB::Model::DescribeTableOutcome &result = dynamoClient.DescribeTable(
                request);
        if (result.IsSuccess()) {
            Aws::DynamoDB::Model::TableStatus status = result.GetResult().GetTable().GetTableStatus();

            if (Aws::DynamoDB::Model::TableStatus::ACTIVE != status) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                return true;
            }
        }
        else {
            std::cerr << "Error DynamoDB::waitTableActive "
                      << result.GetError().GetMessage() << std::endl;
            return false;
        }
        count++;
    }
    return false;
}
```
+  Pour plus de détails sur l'API, reportez-vous [PutItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/PutItem)à la section *Référence des AWS SDK pour C\$1\$1 API*. 

------
#### [ CLI ]

**AWS CLI**  
**Exemple 1 : pour ajouter un élément à une table**  
L'`put-item`exemple suivant ajoute un nouvel élément au *MusicCollection*tableau.  

```
aws dynamodb put-item \
    --table-name MusicCollection \
    --item file://item.json \
    --return-consumed-capacity TOTAL \
    --return-item-collection-metrics SIZE
```
Contenu de `item.json` :  

```
{
    "Artist": {"S": "No One You Know"},
    "SongTitle": {"S": "Call Me Today"},
    "AlbumTitle": {"S": "Greatest Hits"}
}
```
Sortie :  

```
{
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    },
    "ItemCollectionMetrics": {
        "ItemCollectionKey": {
            "Artist": {
                "S": "No One You Know"
            }
        },
        "SizeEstimateRangeGB": [
            0.0,
            1.0
        ]
    }
}
```
Pour plus d’informations, consultez [Écriture d’un élément](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 2 : pour remplacer un élément d’une table sous certaines conditions**  
L’exemple `put-item` suivant remplace un élément existant dans la table `MusicCollection` uniquement si celui-ci possède un attribut `AlbumTitle` dont la valeur est `Greatest Hits`. La commande renvoie la valeur précédente de l’élément.  

```
aws dynamodb put-item \
    --table-name MusicCollection \
    --item file://item.json \
    --condition-expression "#A = :A" \
    --expression-attribute-names file://names.json \
    --expression-attribute-values file://values.json \
    --return-values ALL_OLD
```
Contenu de `item.json` :  

```
{
    "Artist": {"S": "No One You Know"},
    "SongTitle": {"S": "Call Me Today"},
    "AlbumTitle": {"S": "Somewhat Famous"}
}
```
Contenu de `names.json` :  

```
{
    "#A": "AlbumTitle"
}
```
Contenu de `values.json` :  

```
{
    ":A": {"S": "Greatest Hits"}
}
```
Sortie :  

```
{
    "Attributes": {
        "AlbumTitle": {
            "S": "Greatest Hits"
        },
        "Artist": {
            "S": "No One You Know"
        },
        "SongTitle": {
            "S": "Call Me Today"
        }
    }
}
```
Si la clé existe déjà, vous devriez voir la sortie suivante :  

```
A client error (ConditionalCheckFailedException) occurred when calling the PutItem operation: The conditional request failed.
```
Pour plus d’informations, consultez [Écriture d’un élément](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) dans le *Guide du développeur Amazon DynamoDB*.  
+  Pour plus de détails sur l'API, voir [PutItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/put-item.html)la section *Référence des AWS CLI commandes*. 

------
#### [ Go ]

**Kit SDK pour Go V2**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples). 

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

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



// AddMovie adds a movie the DynamoDB table.
func (basics TableBasics) AddMovie(ctx context.Context, movie Movie) error {
	item, err := attributevalue.MarshalMap(movie)
	if err != nil {
		panic(err)
	}
	_, err = basics.DynamoDbClient.PutItem(ctx, &dynamodb.PutItemInput{
		TableName: aws.String(basics.TableName), Item: item,
	})
	if err != nil {
		log.Printf("Couldn't add item to table. Here's why: %v\n", err)
	}
	return err
}
```
Définissez une structure Movie utilisée dans cet exemple.  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// 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 plus de détails sur l'API, reportez-vous [PutItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.PutItem)à la section *Référence des AWS SDK pour Go API*. 

------
#### [ Java ]

**SDK pour Java 2.x**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
Met un élément dans un tableau en utilisant [DynamoDbClient](https://docs.aws.amazon.com/sdk-for-java/latest/reference/software/amazon/awssdk/services/dynamodb/DynamoDbClient.html).  

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

/**
 * 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 place items into an Amazon DynamoDB table using the AWS SDK for Java V2,
 * its better practice to use the
 * Enhanced Client. See the EnhancedPutItem example.
 */
public class PutItem {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <key> <keyVal> <albumtitle> <albumtitleval> <awards> <awardsval> <Songtitle> <songtitleval>

                Where:
                    tableName - The Amazon DynamoDB table in which an item is placed (for example, Music3).
                    key - The key used in the Amazon DynamoDB table (for example, Artist).
                    keyval - The key value that represents the item to get (for example, Famous Band).
                    albumTitle - The Album title (for example, AlbumTitle).
                    AlbumTitleValue - The name of the album (for example, Songs About Life ).
                    Awards - The awards column (for example, Awards).
                    AwardVal - The value of the awards (for example, 10).
                    SongTitle - The song title (for example, SongTitle).
                    SongTitleVal - The value of the song title (for example, Happy Day).
                **Warning** This program will  place an item that you specify into a table!
                """;

        if (args.length != 9) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String key = args[1];
        String keyVal = args[2];
        String albumTitle = args[3];
        String albumTitleValue = args[4];
        String awards = args[5];
        String awardVal = args[6];
        String songTitle = args[7];
        String songTitleVal = args[8];

        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        putItemInTable(ddb, tableName, key, keyVal, albumTitle, albumTitleValue, awards, awardVal, songTitle,
                songTitleVal);
        System.out.println("Done!");
        ddb.close();
    }

    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<>();
        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 {
            PutItemResponse response = ddb.putItem(request);
            System.out.println(tableName + " was successfully updated. The request id is "
                    + response.responseMetadata().requestId());

        } 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);
        }
    }
}
```
+  Pour plus de détails sur l'API, reportez-vous [PutItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem)à la section *Référence des AWS SDK for Java 2.x API*. 

------
#### [ JavaScript ]

**SDK pour JavaScript (v3)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Cet exemple utilise le client de document pour simplifier l’utilisation d’éléments dans DynamoDB. Pour plus de détails sur l'API, voir [PutCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/PutCommand/).  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { PutCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new PutCommand({
    TableName: "HappyAnimals",
    Item: {
      CommonName: "Shiba Inu",
    },
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  Pour plus de détails sur l'API, reportez-vous [PutItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/PutItemCommand)à la section *Référence des AWS SDK pour JavaScript API*. 

**SDK pour JavaScript (v2)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples). 
Insérez un élément dans la 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: "CUSTOMER_LIST",
  Item: {
    CUSTOMER_ID: { N: "001" },
    CUSTOMER_NAME: { S: "Richard Roe" },
  },
};

// Call DynamoDB to add the item to the table
ddb.putItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
Insérez un élément dans 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: "TABLE",
  Item: {
    HASHKEY: VALUE,
    ATTRIBUTE_1: "STRING_VALUE",
    ATTRIBUTE_2: VALUE_2,
  },
};

docClient.put(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  Pour plus d’informations, consultez le [Guide du développeur AWS SDK pour JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write.html#dynamodb-example-table-read-write-writing-an-item). 
+  Pour plus de détails sur l'API, reportez-vous [PutItem](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/PutItem)à la section *Référence des AWS SDK pour JavaScript API*. 

------
#### [ Kotlin ]

**SDK pour Kotlin**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples). 

```
suspend fun putItemInTable(
    tableNameVal: String,
    key: String,
    keyVal: String,
    albumTitle: String,
    albumTitleValue: String,
    awards: String,
    awardVal: String,
    songTitle: String,
    songTitleVal: String,
) {
    val itemValues = mutableMapOf<String, AttributeValue>()

    // Add all content to the table.
    itemValues[key] = AttributeValue.S(keyVal)
    itemValues[songTitle] = AttributeValue.S(songTitleVal)
    itemValues[albumTitle] = AttributeValue.S(albumTitleValue)
    itemValues[awards] = AttributeValue.S(awardVal)

    val request =
        PutItemRequest {
            tableName = tableNameVal
            item = itemValues
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.putItem(request)
        println(" A new item was placed into $tableNameVal.")
    }
}
```
+  Pour plus de détails sur l'API, consultez [PutItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)la section *AWS SDK pour la référence de l'API Kotlin*. 

------
#### [ PHP ]

**Kit SDK pour PHP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples). 

```
        echo "What's the name of the last movie you watched?\n";
        while (empty($movieName)) {
            $movieName = testable_readline("Movie name: ");
        }
        echo "And what year was it released?\n";
        $movieYear = "year";
        while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) {
            $movieYear = testable_readline("Year released: ");
        }

        $service->putItem([
            'Item' => [
                'year' => [
                    'N' => "$movieYear",
                ],
                'title' => [
                    'S' => $movieName,
                ],
            ],
            'TableName' => $tableName,
        ]);

    public function putItem(array $array)
    {
        $this->dynamoDbClient->putItem($array);
    }
```
+  Pour plus de détails sur l'API, reportez-vous [PutItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/PutItem)à la section *Référence des AWS SDK pour PHP API*. 

------
#### [ PowerShell ]

**Outils pour PowerShell V4**  
**Exemple 1 : création d’un nouvel élément ou remplacement d’un élément existant par un nouvel élément.**  

```
$item = @{
  SongTitle = 'Somewhere Down The Road'
  Artist = 'No One You Know'
        AlbumTitle = 'Somewhat Famous'
        Price = 1.94
        Genre = 'Country'
        CriticRating = 9.0
} | ConvertTo-DDBItem
Set-DDBItem -TableName 'Music' -Item $item
```
+  Pour plus de détails sur l'API, reportez-vous [PutItem](https://docs.aws.amazon.com/powershell/v4/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V4)*. 

**Outils pour PowerShell V5**  
**Exemple 1 : création d’un nouvel élément ou remplacement d’un élément existant par un nouvel élément.**  

```
$item = @{
  SongTitle = 'Somewhere Down The Road'
  Artist = 'No One You Know'
        AlbumTitle = 'Somewhat Famous'
        Price = 1.94
        Genre = 'Country'
        CriticRating = 9.0
} | ConvertTo-DDBItem
Set-DDBItem -TableName 'Music' -Item $item
```
+  Pour plus de détails sur l'API, reportez-vous [PutItem](https://docs.aws.amazon.com/powershell/v5/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V5)*. 

------
#### [ Python ]

**Kit SDK for Python (Boto3)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 

```
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 add_movie(self, title, year, plot, rating):
        """
        Adds a movie to the table.

        :param title: The title of the movie.
        :param year: The release year of the movie.
        :param plot: The plot summary of the movie.
        :param rating: The quality rating of the movie.
        """
        try:
            self.table.put_item(
                Item={
                    "year": year,
                    "title": title,
                    "info": {"plot": plot, "rating": Decimal(str(rating))},
                }
            )
        except ClientError as err:
            logger.error(
                "Couldn't add movie %s to table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  Pour plus de détails sur l'API, consultez [PutItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem)le *AWS manuel de référence de l'API SDK for Python (Boto3*). 

------
#### [ Ruby ]

**Kit SDK pour Ruby**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples). 

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :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

  # Adds a movie to the table.
  #
  # @param movie [Hash] The title, year, plot, and rating of the movie.
  def add_item(movie)
    @table.put_item(
      item: {
        'year' => movie[:year],
        'title' => movie[:title],
        'info' => { 'plot' => movie[:plot], 'rating' => movie[:rating] }
      }
    )
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't add movie #{title} to table #{@table.name}. Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  Pour plus de détails sur l'API, reportez-vous [PutItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/PutItem)à la section *Référence des AWS SDK pour Ruby API*. 

------
#### [ Rust ]

**SDK pour Rust**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples). 

```
pub async fn add_item(client: &Client, item: Item, table: &String) -> Result<ItemOut, Error> {
    let user_av = AttributeValue::S(item.username);
    let type_av = AttributeValue::S(item.p_type);
    let age_av = AttributeValue::S(item.age);
    let first_av = AttributeValue::S(item.first);
    let last_av = AttributeValue::S(item.last);

    let request = client
        .put_item()
        .table_name(table)
        .item("username", user_av)
        .item("account_type", type_av)
        .item("age", age_av)
        .item("first_name", first_av)
        .item("last_name", last_av);

    println!("Executing request [{request:?}] to add item...");

    let resp = request.send().await?;

    let attributes = resp.attributes().unwrap();

    let username = attributes.get("username").cloned();
    let first_name = attributes.get("first_name").cloned();
    let last_name = attributes.get("last_name").cloned();
    let age = attributes.get("age").cloned();
    let p_type = attributes.get("p_type").cloned();

    println!(
        "Added user {:?}, {:?} {:?}, age {:?} as {:?} user",
        username, first_name, last_name, age, p_type
    );

    Ok(ItemOut {
        p_type,
        age,
        username,
        first_name,
        last_name,
    })
}
```
+  Pour plus de détails sur l'API, voir [PutItem](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.put_item)la section de *référence de l'API AWS SDK for Rust*. 

------
#### [ SAP ABAP ]

**Kit SDK pour SAP ABAP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples). 

```
    TRY.
        DATA(lo_resp) = lo_dyn->putitem(
          iv_tablename = iv_table_name
          it_item      = it_item ).
        MESSAGE '1 row inserted into DynamoDB Table' && iv_table_name TYPE 'I'.
      CATCH /aws1/cx_dyncondalcheckfaile00.
        MESSAGE 'A condition specified in the operation could not be evaluated.' TYPE 'E'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
      CATCH /aws1/cx_dyntransactconflictex.
        MESSAGE 'Another transaction is using the item' TYPE 'E'.
    ENDTRY.
```
+  Pour plus de détails sur l'API, consultez [PutItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)la section de référence du *AWS SDK pour l'API SAP ABAP*. 

------
#### [ Swift ]

**Kit SDK pour Swift**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples). 

```
import AWSDynamoDB


    /// Add a movie specified as a `Movie` structure to the Amazon DynamoDB
    /// table.
    ///
    /// - Parameter movie: The `Movie` to add to the table.
    ///
    func add(movie: Movie) async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            // Get a DynamoDB item containing the movie data.
            let item = try await movie.getAsItem()

            // Send the `PutItem` request to Amazon DynamoDB.

            let input = PutItemInput(
                item: item,
                tableName: self.tableName
            )
            _ = try await client.putItem(input: input)
        } catch {
            print("ERROR: add movie:", dump(error))
            throw error
        }
    }


    ///
    /// Return an array mapping attribute names to Amazon DynamoDB attribute
    /// values, representing the contents of the `Movie` record as a DynamoDB
    /// item.
    ///
    /// - Returns: The movie item as an array of type
    ///   `[Swift.String:DynamoDBClientTypes.AttributeValue]`.
    ///
    func getAsItem() async throws -> [Swift.String:DynamoDBClientTypes.AttributeValue]  {
        // Build the item record, starting with the year and title, which are
        // always present.

        var item: [Swift.String:DynamoDBClientTypes.AttributeValue] = [
            "year": .n(String(self.year)),
            "title": .s(self.title)
        ]

        // Add the `info` field with the rating and/or plot if they're
        // available.

        var details: [Swift.String:DynamoDBClientTypes.AttributeValue] = [:]
        if (self.info.rating != nil || self.info.plot != nil) {
            if self.info.rating != nil {
                details["rating"] = .n(String(self.info.rating!))
            }
            if self.info.plot != nil {
                details["plot"] = .s(self.info.plot!)
            }
        }
        item["info"] = .m(details)

        return item
    }
```
+  Pour plus de détails sur l'API, reportez-vous [PutItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/putitem(input:))à la section *AWS SDK pour la référence de l'API Swift*. 

------

Pour obtenir plus d’exemples avec DynamoDB, consultez [Exemples de code pour DynamoDB utilisant AWS SDKs](service_code_examples.md).

Après avoir écrit des données dans votre table, passez à l’ [Étape 3 : lire des données à partir d’une table DynamoDB](getting-started-step-3.md).

# Étape 3 : lire des données à partir d’une table DynamoDB
<a name="getting-started-step-3"></a>

Dans cette étape, vous relirez l’un des éléments que vous avez créé dans [Étape 2 : écrire des données dans une table DynamoDB](getting-started-step-2.md). Vous pouvez utiliser la console DynamoDB ou AWS CLI le pour lire un élément du `Music` tableau en spécifiant et. `Artist` `SongTitle` 

Pour plus d’informations sur les opérations de lecture dans DynamoDB, consultez [Lecture d’un élément](WorkingWithItems.md#WorkingWithItems.ReadingData). 

## AWS Management Console
<a name="getting-started-step-3-Console"></a>

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/](https://console.aws.amazon.com/dynamodb/)

1. Dans le volet de navigation de gauche, choisissez **Tables**.

1. Sur la page **Tables**, sélectionnez la table **Musique**.

1. Sélectionnez **Explorer les éléments de table**.

1. Dans la section **Éléments retournés**, affichez la liste d’éléments stockés dans la table, triés par `Artist` et `SongTitle`. Le premier élément de la liste est celui avec l'**artiste** **Acme Band** et les **SongTitle****PartiQL Rocks**.

## AWS CLI
<a name="getting-started-step-3-CLI"></a>

L' AWS CLI exemple suivant lit un élément à partir du`Music`. Vous pouvez procéder via l’API DynamoDB ou [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), un langage de requête compatible SQL 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"}}'
```

**Windows 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'"
```

**Windows 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](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.SELECT.html).

------

## AWS SDK
<a name="getting-started-step-3-SDK"></a>

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

------
#### [ .NET ]

**SDK pour .NET (v4)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples). 

```
    /// <summary>
    /// Gets information about an existing movie from the table.
    /// </summary>
    /// <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 async Task<Dictionary<string, AttributeValue>> GetItemAsync(Movie newMovie, string tableName)
    {
        try
        {
            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 _amazonDynamoDB.GetItemAsync(request);
            return response.Item;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return new Dictionary<string, AttributeValue>();
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while getting item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while getting item. {ex.Message}");
            throw;
        }
    }
```
+  Pour plus de détails sur l'API, reportez-vous [GetItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/GetItem)à la section *Référence des AWS SDK pour .NET API*. 

------
#### [ Bash ]

**AWS CLI avec le script Bash**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples). 

```
#############################################################################
# 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 plus de détails sur l'API, voir [GetItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/GetItem)la section *Référence des AWS CLI commandes*. 

------
#### [ C\$1\$1 ]

**SDK pour C\$1\$1**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples). 

```
//! 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 plus de détails sur l'API, reportez-vous [GetItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/GetItem)à la section *Référence des AWS SDK pour C\$1\$1 API*. 

------
#### [ CLI ]

**AWS CLI**  
**Exemple 1 : pour lire un élément dans une table**  
L’exemple `get-item` suivant récupère un élément de la table `MusicCollection`. La table possède une clé hash-and-range primaire (`Artist`et`SongTitle`), 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 [Lecture d’un élément](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 2 : pour lire un élément en utilisant une lecture cohérente**  
L’exemple suivant récupère un élément à partir de la table `MusicCollection` à l’aide de la lecture fortement cohérente.  

```
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 [Lecture d’un élément](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 3 : pour extraire des attributs spécifiques d’un élément**  
L’exemple suivant utilise une expression de projection pour extraire 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 [Lecture d’un élément](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData) dans le *Guide du développeur Amazon DynamoDB*.  
+  Pour plus de détails sur l'API, voir [GetItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/get-item.html)la section *Référence des AWS CLI commandes*. 

------
#### [ Go ]

**Kit SDK pour Go V2**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples). 

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// 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(ctx context.Context, title string, year int) (Movie, error) {
	movie := Movie{Title: title, Year: year}
	response, err := basics.DynamoDbClient.GetItem(ctx, &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
}
```
Définissez une structure Movie utilisée dans cet exemple.  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// 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 plus de détails sur l'API, reportez-vous [GetItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.GetItem)à la section *Référence des AWS SDK pour Go API*. 

------
#### [ Java ]

**SDK pour Java 2.x**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
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 plus de détails sur l'API, reportez-vous [GetItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/GetItem)à la section *Référence des AWS SDK for Java 2.x API*. 

------
#### [ JavaScript ]

**SDK pour JavaScript (v3)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Cet exemple utilise le client de document pour simplifier l’utilisation d’éléments dans DynamoDB. Pour plus de détails sur l'API, voir [GetCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/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 plus de détails sur l'API, reportez-vous [GetItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/GetItemCommand)à la section *Référence des AWS SDK pour JavaScript API*. 

**SDK pour JavaScript (v2)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples). 
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);
  }
});
```
+  Pour plus d’informations, consultez le [Guide du développeur AWS SDK pour JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-dynamodb-utilities.html#dynamodb-example-document-client-get). 
+  Pour plus de détails sur l'API, reportez-vous [GetItem](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/GetItem)à la section *Référence des AWS SDK pour JavaScript API*. 

------
#### [ Kotlin ]

**SDK pour Kotlin**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples). 

```
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.fromEnvironment { 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 plus de détails sur l'API, consultez [GetItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)la section *AWS SDK pour la référence de l'API Kotlin*. 

------
#### [ PHP ]

**Kit SDK pour PHP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples). 

```
        $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 plus de détails sur l'API, reportez-vous [GetItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/GetItem)à la section *Référence des AWS SDK pour PHP API*. 

------
#### [ PowerShell ]

**Outils pour PowerShell V4**  
**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 plus de détails sur l'API, reportez-vous [GetItem](https://docs.aws.amazon.com/powershell/v4/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V4)*. 

**Outils pour PowerShell V5**  
**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 plus de détails sur l'API, reportez-vous [GetItem](https://docs.aws.amazon.com/powershell/v5/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V5)*. 

------
#### [ Python ]

**Kit SDK for Python (Boto3)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 

```
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 plus de détails sur l'API, consultez [GetItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/GetItem)le *AWS manuel de référence de l'API SDK for Python (Boto3*). 

------
#### [ Ruby ]

**Kit SDK pour Ruby**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples). 

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :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 plus de détails sur l'API, reportez-vous [GetItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/GetItem)à la section *Référence des AWS SDK pour Ruby API*. 

------
#### [ SAP ABAP ]

**Kit SDK pour SAP ABAP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples). 

```
    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 plus de détails sur l'API, consultez [GetItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)la section de référence du *AWS SDK pour l'API SAP ABAP*. 

------
#### [ Swift ]

**Kit SDK pour Swift**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples). 

```
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 {
        do {
            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
        } catch {
            print("ERROR: get:", dump(error))
            throw error
        }
    }
```
+  Pour plus de détails sur l'API, reportez-vous [GetItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/getitem(input:))à la section *AWS SDK pour la référence de l'API Swift*. 

------

Pour obtenir plus d’exemples avec DynamoDB, consultez [Exemples de code pour DynamoDB utilisant AWS SDKs](service_code_examples.md).

Pour mettre à jour les données dans votre table, passez à l’ [Étape 4 : mettre à jour des données dans une table DynamoDB](getting-started-step-4.md).

# Étape 4 : mettre à jour des données dans une table DynamoDB
<a name="getting-started-step-4"></a>

Dans cette étape, vous mettez à jour un élément que vous avez créé dans [Étape 2 : écrire des données dans une table DynamoDB](getting-started-step-2.md). Vous pouvez utiliser la console DynamoDB ou AWS CLI le pour mettre à jour un élément `AlbumTitle` du tableau en `Music` `Artist` spécifiant`SongTitle`, et en mettant à jour. `AlbumTitle` 

Pour plus d’informations sur les opérations d’écriture, consultez [Écriture d’un élément](WorkingWithItems.md#WorkingWithItems.WritingData).

## AWS Management Console
<a name="getting-started-step-4-Console"></a>

Vous pouvez utiliser la console DynamoDB pour mettre à jour des données dans la table `Music`.

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

1. Dans le volet de navigation de gauche, choisissez **Tables**.

1. Dans la liste de tables, choisissez la table **Music (Musique)**.

1. Sélectionnez **Explorer les éléments de table**.

1. Dans **Articles retournés**, pour la ligne d'articles avec **Acme Band** **Artist** et **Happy Day **SongTitle****, procédez comme suit :

   1. Placez votre curseur sur le **AlbumTitle**titre **Songs About Life**.

   1. Choisissez l’icône Modifier.

   1. Dans la fenêtre contextuelle **Modifier la chaîne**, entrez **Songs of Twilight**.

   1. Choisissez **Enregistrer**.
**Astuce**  
Pour pouvez aussi, pour mettre à jour un élément, procéder comme suit dans la section **Articles retournés** :  
Choisissez la rangée d'articles avec **l'artiste** **Acme Band** et **SongTitle****Happy Day.**
Dans la liste déroulante **Actions**, choisissez **Modifier l’élément**.
Pour entrer **AlbumTitle**, entrez**Songs of Twilight**.
Choisissez **Enregistrer et fermer**.

## AWS CLI
<a name="getting-started-step-4-CLI"></a>

L' AWS CLI exemple suivant met à jour un élément du `Music` tableau. Vous pouvez procéder via l’API DynamoDB ou [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), un langage de requête compatible SQL pour DynamoDB.

------
#### [ DynamoDB API ]

**Linux**

```
aws dynamodb update-item \
    --table-name Music \
    --key '{ "Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}}' \
    --update-expression "SET AlbumTitle = :newval" \
    --expression-attribute-values '{":newval":{"S":"Updated Album Title"}}' \
    --return-values ALL_NEW
```

**Windows CMD**

```
aws dynamodb update-item ^
    --table-name Music ^
    --key "{\"Artist\": {\"S\": \"Acme Band\"}, \"SongTitle\": {\"S\": \"Happy Day\"}}" ^
    --update-expression "SET AlbumTitle = :newval" ^
    --expression-attribute-values "{\":newval\":{\"S\":\"Updated Album Title\"}}" ^
    --return-values ALL_NEW
```

L’utilisation de `update-item` renvoie l’exemple de résultat suivant car `return-values ALL_NEW` a été spécifié.

```
{
    "Attributes": {
        "AlbumTitle": {
            "S": "Updated Album Title"
        },
        "Awards": {
            "S": "10"
        },
        "Artist": {
            "S": "Acme Band"
        },
        "SongTitle": {
            "S": "Happy Day"
        }
    }
}
```

------
#### [ PartiQL for DynamoDB ]

**Linux**

```
aws dynamodb execute-statement --statement "UPDATE Music  \
    SET AlbumTitle='Updated Album Title'  \
    WHERE Artist='Acme Band' AND SongTitle='Happy Day' \
    RETURNING ALL NEW *"
```

**Windows CMD**

```
aws dynamodb execute-statement --statement "UPDATE Music SET AlbumTitle='Updated Album Title' WHERE Artist='Acme Band' AND SongTitle='Happy Day' RETURNING ALL NEW *"
```

L’utilisation de l’instruction `Update` renvoie l’exemple de résultat suivant car `RETURNING ALL NEW *` a été spécifié.

```
{
    "Items": [
        {
            "AlbumTitle": {
                "S": "Updated Album Title"
            },
            "Awards": {
                "S": "10"
            },
            "Artist": {
                "S": "Acme Band"
            },
            "SongTitle": {
                "S": "Happy Day"
            }
        }
    ]
}
```

Pour plus d’informations sur la mise à jour des données avec PartiQL, consultez [Instructions de mise à jour de PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.update.html).

------

## AWS SDK
<a name="getting-started-step-4-SDK"></a>

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

------
#### [ .NET ]

**SDK pour .NET (v4)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples). 

```
    /// <summary>
    /// Updates an existing item in the movies table.
    /// </summary>
    /// <param name="newMovie">A Movie object containing information for
    /// the movie to update.</param>
    /// <param name="newInfo">A MovieInfo object that contains the
    /// information that will be changed.</param>
    /// <param name="tableName">The name of the table that contains the movie.</param>
    /// <returns>A Boolean value that indicates the success of the operation.</returns>
    public async Task<bool> UpdateItemAsync(
        Movie newMovie,
        MovieInfo newInfo,
        string tableName)
    {
        try
        {
            var key = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = newMovie.Title },
                ["year"] = new AttributeValue { N = newMovie.Year.ToString() },
            };
            var updates = new Dictionary<string, AttributeValueUpdate>
            {
                ["info.plot"] = new AttributeValueUpdate
                {
                    Action = AttributeAction.PUT,
                    Value = new AttributeValue { S = newInfo.Plot },
                },

                ["info.rating"] = new AttributeValueUpdate
                {
                    Action = AttributeAction.PUT,
                    Value = new AttributeValue { N = newInfo.Rank.ToString() },
                },
            };

            var request = new UpdateItemRequest
            {
                AttributeUpdates = updates,
                Key = key,
                TableName = tableName,
            };

            await _amazonDynamoDB.UpdateItemAsync(request);
            return true;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} or item was not found. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while updating item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while updating item. {ex.Message}");
            throw;
        }
    }
```
+  Pour plus de détails sur l'API, reportez-vous [UpdateItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/UpdateItem)à la section *Référence des AWS SDK pour .NET API*. 

------
#### [ Bash ]

**AWS CLI avec le script Bash**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples). 

```
##############################################################################
# function dynamodb_update_item
#
# This function updates an item in 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 update.
#       -e update expression  -- An expression that defines one or more attributes to be updated.
#       -v values  -- Path to json file containing the update values.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
#############################################################################
function dynamodb_update_item() {
  local table_name keys update_expression values response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_update_item"
    echo "Update an item in 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 update."
    echo " -e update expression  -- An expression that defines one or more attributes to be updated."
    echo " -v values  -- Path to json file containing the update values."
    echo ""
  }

  while getopts "n:k:e:v:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) keys="${OPTARG}" ;;
      e) update_expression="${OPTARG}" ;;
      v) values="${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 [[ -z "$update_expression" ]]; then
    errecho "ERROR: You must provide an update expression with the -e parameter."
    usage
    return 1
  fi

  if [[ -z "$values" ]]; then
    errecho "ERROR: You must provide a values json file path the -v parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    keys:   $keys"
  iecho "    update_expression:   $update_expression"
  iecho "    values:   $values"

  response=$(aws dynamodb update-item \
    --table-name "$table_name" \
    --key file://"$keys" \
    --update-expression "$update_expression" \
    --expression-attribute-values file://"$values")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports update-item operation failed.$response"
    return 1
  fi

  return 0

}
```
Fonctions utilitaires utilisées dans cet exemple.  

```
###############################################################################
# function iecho
#
# This function enables the script to display the specified text only if
# the global variable $VERBOSE is set to true.
###############################################################################
function iecho() {
  if [[ $VERBOSE == true ]]; then
    echo "$@"
  fi
}

###############################################################################
# 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 plus de détails sur l'API, voir [UpdateItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateItem)la section *Référence des AWS CLI commandes*. 

------
#### [ C\$1\$1 ]

**SDK pour C\$1\$1**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples). 

```
//! Update an Amazon DynamoDB table item.
/*!
  \sa updateItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param attributeKey: The key for the attribute to be updated.
  \param attributeValue: The value for the attribute to be updated.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
  */

/*
 *  The example code only sets/updates an attribute value. It processes
 *  the attribute value as a string, even if the value could be interpreted
 *  as a number. Also, the example code does not remove an existing attribute
 *  from the key value.
 */

bool AwsDoc::DynamoDB::updateItem(const Aws::String &tableName,
                                  const Aws::String &partitionKey,
                                  const Aws::String &partitionValue,
                                  const Aws::String &attributeKey,
                                  const Aws::String &attributeValue,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    // *** Define UpdateItem request arguments.
    // Define TableName argument.
    Aws::DynamoDB::Model::UpdateItemRequest request;
    request.SetTableName(tableName);

    // Define KeyName argument.
    Aws::DynamoDB::Model::AttributeValue attribValue;
    attribValue.SetS(partitionValue);
    request.AddKey(partitionKey, attribValue);

    // Construct the SET update expression argument.
    Aws::String update_expression("SET #a = :valueA");
    request.SetUpdateExpression(update_expression);

    // Construct attribute name argument.
    Aws::Map<Aws::String, Aws::String> expressionAttributeNames;
    expressionAttributeNames["#a"] = attributeKey;
    request.SetExpressionAttributeNames(expressionAttributeNames);

    // Construct attribute value argument.
    Aws::DynamoDB::Model::AttributeValue attributeUpdatedValue;
    attributeUpdatedValue.SetS(attributeValue);
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> expressionAttributeValues;
    expressionAttributeValues[":valueA"] = attributeUpdatedValue;
    request.SetExpressionAttributeValues(expressionAttributeValues);

    // Update the item.
    const Aws::DynamoDB::Model::UpdateItemOutcome &outcome = dynamoClient.UpdateItem(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Item was updated" << std::endl;
    } else {
        std::cerr << outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```
Code qui attend que la table soit active.  

```
//! Query a newly created DynamoDB table until it is active.
/*!
  \sa waitTableActive()
  \param waitTableActive: The DynamoDB table's name.
  \param dynamoClient: A DynamoDB client.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::waitTableActive(const Aws::String &tableName,
                                       const Aws::DynamoDB::DynamoDBClient &dynamoClient) {

    // Repeatedly call DescribeTable until table is ACTIVE.
    const int MAX_QUERIES = 20;
    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    int count = 0;
    while (count < MAX_QUERIES) {
        const Aws::DynamoDB::Model::DescribeTableOutcome &result = dynamoClient.DescribeTable(
                request);
        if (result.IsSuccess()) {
            Aws::DynamoDB::Model::TableStatus status = result.GetResult().GetTable().GetTableStatus();

            if (Aws::DynamoDB::Model::TableStatus::ACTIVE != status) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                return true;
            }
        }
        else {
            std::cerr << "Error DynamoDB::waitTableActive "
                      << result.GetError().GetMessage() << std::endl;
            return false;
        }
        count++;
    }
    return false;
}
```
+  Pour plus de détails sur l'API, reportez-vous [UpdateItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/UpdateItem)à la section *Référence des AWS SDK pour C\$1\$1 API*. 

------
#### [ CLI ]

**AWS CLI**  
**Exemple 1 : pour mettre à jour un élément dans une table**  
L’exemple `update-item` suivant met à jour un élément dans la table `MusicCollection`. Il ajoute un nouvel attribut (`Year`) et modifie l’attribut `AlbumTitle`. Tous les attributs de l’élément, tels qu’ils apparaissent après la mise à jour, sont renvoyés dans la réponse.  

```
aws dynamodb update-item \
    --table-name MusicCollection \
    --key file://key.json \
    --update-expression "SET #Y = :y, #AT = :t" \
    --expression-attribute-names file://expression-attribute-names.json \
    --expression-attribute-values file://expression-attribute-values.json  \
    --return-values ALL_NEW \
    --return-consumed-capacity TOTAL \
    --return-item-collection-metrics SIZE
```
Contenu de `key.json` :  

```
{
    "Artist": {"S": "Acme Band"},
    "SongTitle": {"S": "Happy Day"}
}
```
Contenu de `expression-attribute-names.json` :  

```
{
    "#Y":"Year", "#AT":"AlbumTitle"
}
```
Contenu de `expression-attribute-values.json` :  

```
{
    ":y":{"N": "2015"},
    ":t":{"S": "Louder Than Ever"}
}
```
Sortie :  

```
{
    "Attributes": {
        "AlbumTitle": {
            "S": "Louder Than Ever"
        },
        "Awards": {
            "N": "10"
        },
        "Artist": {
            "S": "Acme Band"
        },
        "Year": {
            "N": "2015"
        },
        "SongTitle": {
            "S": "Happy Day"
        }
    },
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 3.0
    },
    "ItemCollectionMetrics": {
        "ItemCollectionKey": {
            "Artist": {
                "S": "Acme Band"
            }
        },
        "SizeEstimateRangeGB": [
            0.0,
            1.0
        ]
    }
}
```
Pour plus d’informations, consultez [Écriture d’un élément](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 2 : pour mettre à jour un élément sous certaines conditions**  
L’exemple suivant met à jour un élément de la table `MusicCollection`, mais uniquement si l’élément existant ne possède pas encore d’attribut `Year`.  

```
aws dynamodb update-item \
    --table-name MusicCollection \
    --key file://key.json \
    --update-expression "SET #Y = :y, #AT = :t" \
    --expression-attribute-names file://expression-attribute-names.json \
    --expression-attribute-values file://expression-attribute-values.json  \
    --condition-expression "attribute_not_exists(#Y)"
```
Contenu de `key.json` :  

```
{
    "Artist": {"S": "Acme Band"},
    "SongTitle": {"S": "Happy Day"}
}
```
Contenu de `expression-attribute-names.json` :  

```
{
    "#Y":"Year",
    "#AT":"AlbumTitle"
}
```
Contenu de `expression-attribute-values.json` :  

```
{
    ":y":{"N": "2015"},
    ":t":{"S": "Louder Than Ever"}
}
```
Si l’élément possède déjà un attribut `Year`, DynamoDB renvoie le résultat suivant.  

```
An error occurred (ConditionalCheckFailedException) when calling the UpdateItem operation: The conditional request failed
```
Pour plus d’informations, consultez [Écriture d’un élément](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) dans le *Guide du développeur Amazon DynamoDB*.  
+  Pour plus de détails sur l'API, voir [UpdateItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-item.html)la section *Référence des AWS CLI commandes*. 

------
#### [ Go ]

**Kit SDK pour Go V2**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples). 

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

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



// UpdateMovie updates the rating and plot of a movie that already exists in the
// DynamoDB table. This function uses the `expression` package to build the update
// expression.
func (basics TableBasics) UpdateMovie(ctx context.Context, movie Movie) (map[string]map[string]interface{}, error) {
	var err error
	var response *dynamodb.UpdateItemOutput
	var attributeMap map[string]map[string]interface{}
	update := expression.Set(expression.Name("info.rating"), expression.Value(movie.Info["rating"]))
	update.Set(expression.Name("info.plot"), expression.Value(movie.Info["plot"]))
	expr, err := expression.NewBuilder().WithUpdate(update).Build()
	if err != nil {
		log.Printf("Couldn't build expression for update. Here's why: %v\n", err)
	} else {
		response, err = basics.DynamoDbClient.UpdateItem(ctx, &dynamodb.UpdateItemInput{
			TableName:                 aws.String(basics.TableName),
			Key:                       movie.GetKey(),
			ExpressionAttributeNames:  expr.Names(),
			ExpressionAttributeValues: expr.Values(),
			UpdateExpression:          expr.Update(),
			ReturnValues:              types.ReturnValueUpdatedNew,
		})
		if err != nil {
			log.Printf("Couldn't update movie %v. Here's why: %v\n", movie.Title, err)
		} else {
			err = attributevalue.UnmarshalMap(response.Attributes, &attributeMap)
			if err != nil {
				log.Printf("Couldn't unmarshall update response. Here's why: %v\n", err)
			}
		}
	}
	return attributeMap, err
}
```
Définissez une structure Movie utilisée dans cet exemple.  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// 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 plus de détails sur l'API, reportez-vous [UpdateItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.UpdateItem)à la section *Référence des AWS SDK pour Go API*. 

------
#### [ Java ]

**SDK pour Java 2.x**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
Met à jour un élément d'un tableau à l'aide de [DynamoDbClient](https://docs.aws.amazon.com/sdk-for-java/latest/reference/software/amazon/awssdk/services/dynamodb/DynamoDbClient.html).  

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

/**
 * 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 update an Amazon DynamoDB table using the AWS SDK for Java V2, its better
 * practice to use the
 * Enhanced Client, See the EnhancedModifyItem example.
 */
public class UpdateItem {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <key> <keyVal> <name> <updateVal>

                Where:
                    tableName - The Amazon DynamoDB table (for example, Music3).
                    key - The name of the key in the table (for example, Artist).
                    keyVal - The value of the key (for example, Famous Band).
                    name - The name of the column where the value is updated (for example, Awards).
                    updateVal - The value used to update an item (for example, 14).
                 Example:
                    UpdateItem Music3 Artist Famous Band Awards 14
                """;

        if (args.length != 5) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String key = args[1];
        String keyVal = args[2];
        String name = args[3];
        String updateVal = args[4];

        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();
        updateTableItem(ddb, tableName, key, keyVal, name, updateVal);
        ddb.close();
    }

    public static void updateTableItem(DynamoDbClient ddb,
            String tableName,
            String key,
            String keyVal,
            String name,
            String updateVal) {

        HashMap<String, AttributeValue> itemKey = new HashMap<>();
        itemKey.put(key, AttributeValue.builder()
                .s(keyVal)
                .build());

        HashMap<String, AttributeValueUpdate> updatedValues = new HashMap<>();
        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 (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("The Amazon DynamoDB table was updated!");
    }
}
```
+  Pour plus de détails sur l'API, reportez-vous [UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)à la section *Référence des AWS SDK for Java 2.x API*. 

------
#### [ JavaScript ]

**SDK pour JavaScript (v3)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Cet exemple utilise le client de document pour simplifier l’utilisation d’éléments dans DynamoDB. Pour plus de détails sur l'API, voir [UpdateCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/UpdateCommand/).  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, UpdateCommand } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new UpdateCommand({
    TableName: "Dogs",
    Key: {
      Breed: "Labrador",
    },
    UpdateExpression: "set Color = :color",
    ExpressionAttributeValues: {
      ":color": "black",
    },
    ReturnValues: "ALL_NEW",
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  Pour plus de détails sur l'API, reportez-vous [UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)à la section *Référence des AWS SDK pour JavaScript API*. 

------
#### [ Kotlin ]

**SDK pour Kotlin**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples). 

```
suspend fun updateTableItem(
    tableNameVal: String,
    keyName: String,
    keyVal: String,
    name: String,
    updateVal: String,
) {
    val itemKey = mutableMapOf<String, AttributeValue>()
    itemKey[keyName] = AttributeValue.S(keyVal)

    val updatedValues = mutableMapOf<String, AttributeValueUpdate>()
    updatedValues[name] =
        AttributeValueUpdate {
            value = AttributeValue.S(updateVal)
            action = AttributeAction.Put
        }

    val request =
        UpdateItemRequest {
            tableName = tableNameVal
            key = itemKey
            attributeUpdates = updatedValues
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.updateItem(request)
        println("Item in $tableNameVal was updated")
    }
}
```
+  Pour plus de détails sur l'API, consultez [UpdateItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)la section *AWS SDK pour la référence de l'API Kotlin*. 

------
#### [ PHP ]

**Kit SDK pour PHP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples). 

```
        echo "What rating would you like to give {$movie['Item']['title']['S']}?\n";
        $rating = 0;
        while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) {
            $rating = testable_readline("Rating (1-10): ");
        }
        $service->updateItemAttributeByKey($tableName, $key, 'rating', 'N', $rating);

    public function updateItemAttributeByKey(
        string $tableName,
        array $key,
        string $attributeName,
        string $attributeType,
        string $newValue
    ) {
        $this->dynamoDbClient->updateItem([
            'Key' => $key['Item'],
            'TableName' => $tableName,
            'UpdateExpression' => "set #NV=:NV",
            'ExpressionAttributeNames' => [
                '#NV' => $attributeName,
            ],
            'ExpressionAttributeValues' => [
                ':NV' => [
                    $attributeType => $newValue
                ]
            ],
        ]);
    }
```
+  Pour plus de détails sur l'API, reportez-vous [UpdateItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/UpdateItem)à la section *Référence des AWS SDK pour PHP API*. 

------
#### [ PowerShell ]

**Outils pour PowerShell V4**  
**Exemple 1 : définit l'attribut genre sur « Rap » sur 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

$updateDdbItem = @{
    TableName = 'Music'
    Key = $key
    UpdateExpression = 'set Genre = :val1'
    ExpressionAttributeValue = (@{
        ':val1' = ([Amazon.DynamoDBv2.Model.AttributeValue]'Rap')
    })
}
Update-DDBItem @updateDdbItem
```
**Sortie** :  

```
Name                           Value
----                           -----
Genre                          Rap
```
+  Pour plus de détails sur l'API, reportez-vous [UpdateItem](https://docs.aws.amazon.com/powershell/v4/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V4)*. 

**Outils pour PowerShell V5**  
**Exemple 1 : définit l'attribut genre sur « Rap » sur 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

$updateDdbItem = @{
    TableName = 'Music'
    Key = $key
    UpdateExpression = 'set Genre = :val1'
    ExpressionAttributeValue = (@{
        ':val1' = ([Amazon.DynamoDBv2.Model.AttributeValue]'Rap')
    })
}
Update-DDBItem @updateDdbItem
```
**Sortie** :  

```
Name                           Value
----                           -----
Genre                          Rap
```
+  Pour plus de détails sur l'API, reportez-vous [UpdateItem](https://docs.aws.amazon.com/powershell/v5/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V5)*. 

------
#### [ Python ]

**Kit SDK for Python (Boto3)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 
Mettez à jour un élément à l’aide d’une expression de mise à jour.  

```
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 update_movie(self, title, year, rating, plot):
        """
        Updates rating and plot data for a movie in the table.

        :param title: The title of the movie to update.
        :param year: The release year of the movie to update.
        :param rating: The updated rating to the give the movie.
        :param plot: The updated plot summary to give the movie.
        :return: The fields that were updated, with their new values.
        """
        try:
            response = self.table.update_item(
                Key={"year": year, "title": title},
                UpdateExpression="set info.rating=:r, info.plot=:p",
                ExpressionAttributeValues={":r": Decimal(str(rating)), ":p": plot},
                ReturnValues="UPDATED_NEW",
            )
        except ClientError as err:
            logger.error(
                "Couldn't update movie %s in table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Attributes"]
```
Mettez à jour un élément à l’aide d’une expression de mise à jour qui inclut une opération arithmétique.  

```
class UpdateQueryWrapper:
    def __init__(self, table):
        self.table = table


    def update_rating(self, title, year, rating_change):
        """
        Updates the quality rating of a movie in the table by using an arithmetic
        operation in the update expression. By specifying an arithmetic operation,
        you can adjust a value in a single request, rather than first getting its
        value and then setting its new value.

        :param title: The title of the movie to update.
        :param year: The release year of the movie to update.
        :param rating_change: The amount to add to the current rating for the movie.
        :return: The updated rating.
        """
        try:
            response = self.table.update_item(
                Key={"year": year, "title": title},
                UpdateExpression="set info.rating = info.rating + :val",
                ExpressionAttributeValues={":val": Decimal(str(rating_change))},
                ReturnValues="UPDATED_NEW",
            )
        except ClientError as err:
            logger.error(
                "Couldn't update movie %s in table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Attributes"]
```
Mettre à jour un élément uniquement lorsqu’il remplit certaines conditions.  

```
class UpdateQueryWrapper:
    def __init__(self, table):
        self.table = table


    def remove_actors(self, title, year, actor_threshold):
        """
        Removes an actor from a movie, but only when the number of actors is greater
        than a specified threshold. If the movie does not list more than the threshold,
        no actors are removed.

        :param title: The title of the movie to update.
        :param year: The release year of the movie to update.
        :param actor_threshold: The threshold of actors to check.
        :return: The movie data after the update.
        """
        try:
            response = self.table.update_item(
                Key={"year": year, "title": title},
                UpdateExpression="remove info.actors[0]",
                ConditionExpression="size(info.actors) > :num",
                ExpressionAttributeValues={":num": actor_threshold},
                ReturnValues="ALL_NEW",
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
                logger.warning(
                    "Didn't update %s because it has fewer than %s actors.",
                    title,
                    actor_threshold + 1,
                )
            else:
                logger.error(
                    "Couldn't update movie %s. Here's why: %s: %s",
                    title,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return response["Attributes"]
```
+  Pour plus de détails sur l'API, consultez [UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)le *AWS manuel de référence de l'API SDK for Python (Boto3*). 

------
#### [ Ruby ]

**Kit SDK pour Ruby**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples). 

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :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

  # Updates rating and plot data for a movie in the table.
  #
  # @param movie [Hash] The title, year, plot, rating of the movie.
  def update_item(movie)
    response = @table.update_item(
      key: { 'year' => movie[:year], 'title' => movie[:title] },
      update_expression: 'set info.rating=:r',
      expression_attribute_values: { ':r' => movie[:rating] },
      return_values: 'UPDATED_NEW'
    )
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't update movie #{movie[:title]} (#{movie[:year]}) in table #{@table.name}\n")
    puts("\t#{e.code}: #{e.message}")
    raise
  else
    response.attributes
  end
```
+  Pour plus de détails sur l'API, reportez-vous [UpdateItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/UpdateItem)à la section *Référence des AWS SDK pour Ruby API*. 

------
#### [ SAP ABAP ]

**Kit SDK pour SAP ABAP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples). 

```
    TRY.
        oo_output = lo_dyn->updateitem(
          iv_tablename        = iv_table_name
          it_key              = it_item_key
          it_attributeupdates = it_attribute_updates ).
        MESSAGE '1 item updated in DynamoDB Table' && iv_table_name TYPE 'I'.
      CATCH /aws1/cx_dyncondalcheckfaile00.
        MESSAGE 'A condition specified in the operation could not be evaluated.' TYPE 'E'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
      CATCH /aws1/cx_dyntransactconflictex.
        MESSAGE 'Another transaction is using the item' TYPE 'E'.
    ENDTRY.
```
+  Pour plus de détails sur l'API, consultez [UpdateItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)la section de référence du *AWS SDK pour l'API SAP ABAP*. 

------
#### [ Swift ]

**Kit SDK pour Swift**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples). 

```
import AWSDynamoDB


    /// Update the specified movie with new `rating` and `plot` information.
    ///
    /// - Parameters:
    ///   - title: The title of the movie to update.
    ///   - year: The release year of the movie to update.
    ///   - rating: The new rating for the movie.
    ///   - plot: The new plot summary string for the movie.
    ///
    /// - Returns: An array of mappings of attribute names to their new
    ///   listing each item actually changed. Items that didn't need to change
    ///   aren't included in this list. `nil` if no changes were made.
    ///
    func update(title: String, year: Int, rating: Double? = nil, plot: String? = nil) async throws
        -> [Swift.String: DynamoDBClientTypes.AttributeValue]?
    {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            // Build the update expression and the list of expression attribute
            // values. Include only the information that's changed.

            var expressionParts: [String] = []
            var attrValues: [Swift.String: DynamoDBClientTypes.AttributeValue] = [:]

            if rating != nil {
                expressionParts.append("info.rating=:r")
                attrValues[":r"] = .n(String(rating!))
            }
            if plot != nil {
                expressionParts.append("info.plot=:p")
                attrValues[":p"] = .s(plot!)
            }
            let expression = "set \(expressionParts.joined(separator: ", "))"

            let input = UpdateItemInput(
                // Create substitution tokens for the attribute values, to ensure
                // no conflicts in expression syntax.
                expressionAttributeValues: attrValues,
                // The key identifying the movie to update consists of the release
                // year and title.
                key: [
                    "year": .n(String(year)),
                    "title": .s(title)
                ],
                returnValues: .updatedNew,
                tableName: self.tableName,
                updateExpression: expression
            )
            let output = try await client.updateItem(input: input)

            guard let attributes: [Swift.String: DynamoDBClientTypes.AttributeValue] = output.attributes else {
                throw MoviesError.InvalidAttributes
            }
            return attributes
        } catch {
            print("ERROR: update:", dump(error))
            throw error
        }
    }
```
+  Pour plus de détails sur l'API, reportez-vous [UpdateItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/updateitem(input:))à la section *AWS SDK pour la référence de l'API Swift*. 

------

Pour obtenir plus d’exemples avec DynamoDB, consultez [Exemples de code pour DynamoDB utilisant AWS SDKs](service_code_examples.md).

Pour interroger les données dans la table `Music`, passez à l’[Étape 5 : interroger des données dans une table DynamoDB](getting-started-step-5.md).

# Étape 5 : interroger des données dans une table DynamoDB
<a name="getting-started-step-5"></a>

Dans cette étape, vous interrogez les données que vous avez écrites dans la table `Music` dans [Étape 2 : écrire des données dans une table DynamoDB](getting-started-step-2.md) en spécifiant l’`Artist`. Cela affichera tous les morceaux associés à la clé de partition : `Artist`.

Pour plus d’informations sur les opérations d’interrogation, consultez [Interrogation de tables dans DynamoDB](Query.md). 

## AWS Management Console
<a name="getting-started-step-5-Console"></a>

Suivez ces étapes pour utiliser la console DynamoDB afin d’interroger les données de la table `Music`.

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

1. Dans le volet de navigation de gauche, choisissez **Tables**.

1. Dans la liste de tables, choisissez la table **Music (Musique)**.

1. Sélectionnez **Explorer les éléments de table**.

1. Dans **Analyser ou interroger des éléments**, assurez-vous que l’option **Requête** est sélectionnée.

1. Pour **Clé de partition**, entrez **Acme Band**, puis choisissez **Exécuter**.

## AWS CLI
<a name="getting-started-step-5-CLI"></a>

L' AWS CLI exemple suivant interroge un élément de la `Music` table. Vous pouvez procéder via l’API DynamoDB ou [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), un langage de requête compatible SQL pour DynamoDB.

------
#### [ DynamoDB API ]

Vous interrogez un élément via l’API DynamoDB en utilisant `query` et en fournissant la clé de partition.

**Linux**

```
aws dynamodb query \
    --table-name Music \
    --key-condition-expression "Artist = :name" \
    --expression-attribute-values  '{":name":{"S":"Acme Band"}}'
```

**Windows CMD**

```
aws dynamodb query ^
    --table-name Music ^
    --key-condition-expression "Artist = :name" ^
    --expression-attribute-values  "{\":name\":{\"S\":\"Acme Band\"}}"
```

Une telle utilisation de `query` renvoie tous les morceaux associés à cet `Artist` spécifique.

```
{
    "Items": [
        {
            "AlbumTitle": {
                "S": "Updated Album Title"
            },
            "Awards": {
                "N": "10"
            },
            "Artist": {
                "S": "Acme Band"
            },
            "SongTitle": {
                "S": "Happy Day"
            }
        },
        {
            "AlbumTitle": {
                "S": "Another Album Title"
            },
            "Awards": {
                "N": "8"
            },
            "Artist": {
                "S": "Acme Band"
            },
            "SongTitle": {
                "S": "PartiQL Rocks"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": null
}
```

------
#### [ PartiQL for DynamoDB ]

Vous interrogez un élément via PartiQL en utilisant l’instruction `Select` et en fournissant la clé de partition.

**Linux**

```
aws dynamodb execute-statement --statement "SELECT * FROM Music   \
                                            WHERE Artist='Acme Band'"
```

**Windows CMD**

```
aws dynamodb execute-statement --statement "SELECT * FROM Music WHERE Artist='Acme Band'"
```

Une telle utilisation de l’instruction `Select` renvoie tous les morceaux associés à cet `Artist` spécifique.

```
{
    "Items": [
        {
            "AlbumTitle": {
                "S": "Updated Album Title"
            },
            "Awards": {
                "S": "10"
            },
            "Artist": {
                "S": "Acme Band"
            },
            "SongTitle": {
                "S": "Happy Day"
            }
        },
        {
            "AlbumTitle": {
                "S": "Another Album Title"
            },
            "Awards": {
                "S": "8"
            },
            "Artist": {
                "S": "Acme Band"
            },
            "SongTitle": {
                "S": "PartiQL Rocks"
            }
        }
    ]
}
```

Pour plus d’informations sur l’interrogation de données avec PartiQL, consultez [Instructions de sélection de PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.select.html).

------

## AWS SDK
<a name="getting-started-step-5-SDK"></a>

Les exemples de code suivants expliquent comment interroger une table DynamoDB à l’aide d’un kit AWS SDK.

------
#### [ .NET ]

**SDK pour .NET (v4)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples). 

```
    /// <summary>
    /// Queries the table for movies released in a particular year and
    /// then displays the information for the movies returned.
    /// </summary>
    /// <param name="tableName">The name of the table to query.</param>
    /// <param name="year">The release year for which we want to
    /// view movies.</param>
    /// <returns>The number of movies that match the query.</returns>
    public async Task<int> QueryMoviesAsync(string tableName, int year)
    {
        try
        {
            var movieTable = new TableBuilder(_amazonDynamoDB, tableName)
                .AddHashKey("year", DynamoDBEntryType.Numeric)
                .AddRangeKey("title", DynamoDBEntryType.String)
                .Build();

            var filter = new QueryFilter("year", QueryOperator.Equal, year);

            Console.WriteLine("\nFind movies released in: {year}:");

            var config = new QueryOperationConfig()
            {
                Limit = 10, // 10 items per page.
                Select = SelectValues.SpecificAttributes,
                AttributesToGet = new List<string>
                {
                    "title",
                    "year",
                },
                ConsistentRead = true,
                Filter = filter,
            };

            // Value used to track how many movies match the
            // supplied criteria.
            var moviesFound = 0;

            var search = movieTable.Query(config);
            do
            {
                var movieList = await search.GetNextSetAsync();
                moviesFound += movieList.Count;

                foreach (var movie in movieList)
                {
                    DisplayDocument(movie);
                }
            }
            while (!search.IsDone);

            return moviesFound;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return 0;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while querying movies. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while querying movies. {ex.Message}");
            throw;
        }
    }
```
+  Pour plus de détails sur l’API, consultez [Query](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/Query) dans la *Référence des API du kit AWS SDK pour .NET *. 

------
#### [ Bash ]

**AWS CLI avec le script Bash**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples). 

```
#############################################################################
# function dynamodb_query
#
# This function queries a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k key_condition_expression -- The key condition expression.
#       -a attribute_names -- Path to JSON file containing the attribute names.
#       -v attribute_values -- Path to JSON file containing the attribute values.
#       [-p projection_expression]  -- Optional projection expression.
#
#  Returns:
#       The items as json output.
#  And:
#       0 - If successful.
#       1 - If it fails.
###########################################################################
function dynamodb_query() {
  local table_name key_condition_expression attribute_names attribute_values projection_expression response
  local option OPTARG # Required to use getopts command in a function.

  # ######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_query"
    echo "Query a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k key_condition_expression -- The key condition expression."
    echo " -a attribute_names -- Path to JSON file containing the attribute names."
    echo " -v attribute_values -- Path to JSON file containing the attribute values."
    echo " [-p projection_expression]  -- Optional projection expression."
    echo ""
  }

  while getopts "n:k:a:v:p:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) key_condition_expression="${OPTARG}" ;;
      a) attribute_names="${OPTARG}" ;;
      v) attribute_values="${OPTARG}" ;;
      p) projection_expression="${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 "$key_condition_expression" ]]; then
    errecho "ERROR: You must provide a key condition expression with the -k parameter."
    usage
    return 1
  fi

  if [[ -z "$attribute_names" ]]; then
    errecho "ERROR: You must provide a attribute names with the -a parameter."
    usage
    return 1
  fi

  if [[ -z "$attribute_values" ]]; then
    errecho "ERROR: You must provide a attribute values with the -v parameter."
    usage
    return 1
  fi

  if [[ -z "$projection_expression" ]]; then
    response=$(aws dynamodb query \
      --table-name "$table_name" \
      --key-condition-expression "$key_condition_expression" \
      --expression-attribute-names file://"$attribute_names" \
      --expression-attribute-values file://"$attribute_values")
  else
    response=$(aws dynamodb query \
      --table-name "$table_name" \
      --key-condition-expression "$key_condition_expression" \
      --expression-attribute-names file://"$attribute_names" \
      --expression-attribute-values file://"$attribute_values" \
      --projection-expression "$projection_expression")
  fi

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports query operation failed.$response"
    return 1
  fi

  echo "$response"

  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 plus d’informations sur l’API, consultez [Query](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/Query) dans la *Référence des commandes AWS CLI *. 

------
#### [ C\$1\$1 ]

**SDK pour C\$1\$1**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples). 

```
//! Perform a query on an Amazon DynamoDB Table and retrieve items.
/*!
  \sa queryItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param projectionExpression: The projections expression, which is ignored if empty.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
  */

/*
 * The partition key attribute is searched with the specified value. By default, all fields and values
 * contained in the item are returned. If an optional projection expression is
 * specified on the command line, only the specified fields and values are
 * returned.
 */

bool AwsDoc::DynamoDB::queryItems(const Aws::String &tableName,
                                  const Aws::String &partitionKey,
                                  const Aws::String &partitionValue,
                                  const Aws::String &projectionExpression,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);
    Aws::DynamoDB::Model::QueryRequest request;

    request.SetTableName(tableName);

    if (!projectionExpression.empty()) {
        request.SetProjectionExpression(projectionExpression);
    }

    // Set query key condition expression.
    request.SetKeyConditionExpression(partitionKey + "= :valueToMatch");

    // Set Expression AttributeValues.
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> attributeValues;
    attributeValues.emplace(":valueToMatch", partitionValue);

    request.SetExpressionAttributeValues(attributeValues);

    bool result = true;

    // "exclusiveStartKey" is used for pagination.
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> exclusiveStartKey;
    do {
        if (!exclusiveStartKey.empty()) {
            request.SetExclusiveStartKey(exclusiveStartKey);
            exclusiveStartKey.clear();
        }
        // Perform Query operation.
        const Aws::DynamoDB::Model::QueryOutcome &outcome = dynamoClient.Query(request);
        if (outcome.IsSuccess()) {
            // Reference the retrieved items.
            const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>> &items = outcome.GetResult().GetItems();
            if (!items.empty()) {
                std::cout << "Number of items retrieved from Query: " << items.size()
                          << std::endl;
                // Iterate each item and print.
                for (const auto &item: items) {
                    std::cout
                            << "******************************************************"
                            << std::endl;
                    // Output each retrieved field and its value.
                    for (const auto &i: item)
                        std::cout << i.first << ": " << i.second.GetS() << std::endl;
                }
            }
            else {
                std::cout << "No item found in table: " << tableName << std::endl;
            }

            exclusiveStartKey = outcome.GetResult().GetLastEvaluatedKey();
        }
        else {
            std::cerr << "Failed to Query items: " << outcome.GetError().GetMessage();
            result = false;
            break;
        }
    } while (!exclusiveStartKey.empty());

    return result;
}
```
+  Pour plus d’informations sur l’API, consultez [Requête](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/Query) dans la *référence d’API AWS SDK pour C\$1\$1 *. 

------
#### [ CLI ]

**AWS CLI**  
**Exemple 1 : pour interroger une table**  
L’exemple `query` suivant interroge des éléments dans la table `MusicCollection`. La table possède une clé hash-and-range primaire (`Artist`et`SongTitle`), mais cette requête indique uniquement la valeur de la clé de hachage. Elle renvoie les titres des chansons de l’artiste « No One You Know ».  

```
aws dynamodb query \
    --table-name MusicCollection \
    --projection-expression "SongTitle" \
    --key-condition-expression "Artist = :v1" \
    --expression-attribute-values file://expression-attributes.json \
    --return-consumed-capacity TOTAL
```
Contenu de `expression-attributes.json` :  

```
{
    ":v1": {"S": "No One You Know"}
}
```
Sortie :  

```
{
    "Items": [
        {
            "SongTitle": {
                "S": "Call Me Today"
            },
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5
    }
}
```
Pour plus d’informations, consultez [Utilisation de requêtes dans DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 2 : pour interroger une table à l’aide de lectures fortement cohérentes et parcourir l’index par ordre décroissant**  
L’exemple suivant exécute la même requête que le premier exemple, mais renvoie les résultats dans l’ordre inverse et utilise des lectures fortement cohérentes.  

```
aws dynamodb query \
    --table-name MusicCollection \
    --projection-expression "SongTitle" \
    --key-condition-expression "Artist = :v1" \
    --expression-attribute-values file://expression-attributes.json \
    --consistent-read \
    --no-scan-index-forward \
    --return-consumed-capacity TOTAL
```
Contenu de `expression-attributes.json` :  

```
{
    ":v1": {"S": "No One You Know"}
}
```
Sortie :  

```
{
    "Items": [
        {
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        },
        {
            "SongTitle": {
                "S": "Call Me Today"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    }
}
```
Pour plus d’informations, consultez [Utilisation des requêtes dans DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 3 : pour filtrer des résultats spécifiques**  
L’exemple suivant interroge `MusicCollection`, mais exclut les résultats contenant des valeurs spécifiques dans l’attribut `AlbumTitle`. Notez que cela n’affecte pas `ScannedCount` ni `ConsumedCapacity`, car le filtre est appliqué après la lecture des éléments.  

```
aws dynamodb query \
    --table-name MusicCollection \
    --key-condition-expression "#n1 = :v1" \
    --filter-expression "NOT (#n2 IN (:v2, :v3))" \
    --expression-attribute-names file://names.json \
    --expression-attribute-values file://values.json \
    --return-consumed-capacity TOTAL
```
Contenu de `values.json` :  

```
{
    ":v1": {"S": "No One You Know"},
    ":v2": {"S": "Blue Sky Blues"},
    ":v3": {"S": "Greatest Hits"}
}
```
Contenu de `names.json` :  

```
{
    "#n1": "Artist",
    "#n2": "AlbumTitle"
}
```
Sortie :  

```
{
    "Items": [
        {
            "AlbumTitle": {
                "S": "Somewhat Famous"
            },
            "Artist": {
                "S": "No One You Know"
            },
            "SongTitle": {
                "S": "Call Me Today"
            }
        }
    ],
    "Count": 1,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5
    }
}
```
Pour plus d’informations, consultez [Utilisation des requêtes dans DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 4 : pour extraire uniquement le nombre d’éléments**  
L’exemple suivant extrait le nombre d’éléments correspondant à la requête, mais n’extrait aucun des éléments eux-mêmes.  

```
aws dynamodb query \
    --table-name MusicCollection \
    --select COUNT \
    --key-condition-expression "Artist = :v1" \
    --expression-attribute-values file://expression-attributes.json
```
Contenu de `expression-attributes.json` :  

```
{
    ":v1": {"S": "No One You Know"}
}
```
Sortie :  

```
{
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": null
}
```
Pour plus d’informations, consultez [Utilisation des requêtes dans DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) dans le *Guide du développeur Amazon DynamoDB*.  
**Exemple 5 : pour interroger un index**  
L’exemple suivant interroge l’index secondaire global `AlbumTitleIndex`. La requête renvoie tous les attributs de la table de base qui ont été projetés dans l’index secondaire local. Notez que lorsque vous interrogez un index secondaire local ou un index secondaire global, vous devez également fournir le nom de la table de base à l’aide du paramètre `table-name`.  

```
aws dynamodb query \
    --table-name MusicCollection \
    --index-name AlbumTitleIndex \
    --key-condition-expression "Artist = :v1" \
    --expression-attribute-values file://expression-attributes.json \
    --select ALL_PROJECTED_ATTRIBUTES \
    --return-consumed-capacity INDEXES
```
Contenu de `expression-attributes.json` :  

```
{
    ":v1": {"S": "No One You Know"}
}
```
Sortie :  

```
{
    "Items": [
        {
            "AlbumTitle": {
                "S": "Blue Sky Blues"
            },
            "Artist": {
                "S": "No One You Know"
            },
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        },
        {
            "AlbumTitle": {
                "S": "Somewhat Famous"
            },
            "Artist": {
                "S": "No One You Know"
            },
            "SongTitle": {
                "S": "Call Me Today"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5,
        "Table": {
            "CapacityUnits": 0.0
        },
        "LocalSecondaryIndexes": {
            "AlbumTitleIndex": {
                "CapacityUnits": 0.5
            }
        }
    }
}
```
Pour plus d’informations, consultez [Utilisation des requêtes dans DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) dans le *Guide du développeur Amazon DynamoDB*.  
+  Pour plus d’informations sur l’API, consultez [Query](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/query.html) dans la *Référence des commandes AWS CLI *. 

------
#### [ Go ]

**Kit SDK pour Go V2**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples). 

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

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



// Query gets all movies in the DynamoDB table that were released in the specified year.
// The function uses the `expression` package to build the key condition expression
// that is used in the query.
func (basics TableBasics) Query(ctx context.Context, releaseYear int) ([]Movie, error) {
	var err error
	var response *dynamodb.QueryOutput
	var movies []Movie
	keyEx := expression.Key("year").Equal(expression.Value(releaseYear))
	expr, err := expression.NewBuilder().WithKeyCondition(keyEx).Build()
	if err != nil {
		log.Printf("Couldn't build expression for query. Here's why: %v\n", err)
	} else {
		queryPaginator := dynamodb.NewQueryPaginator(basics.DynamoDbClient, &dynamodb.QueryInput{
			TableName:                 aws.String(basics.TableName),
			ExpressionAttributeNames:  expr.Names(),
			ExpressionAttributeValues: expr.Values(),
			KeyConditionExpression:    expr.KeyCondition(),
		})
		for queryPaginator.HasMorePages() {
			response, err = queryPaginator.NextPage(ctx)
			if err != nil {
				log.Printf("Couldn't query for movies released in %v. Here's why: %v\n", releaseYear, err)
				break
			} else {
				var moviePage []Movie
				err = attributevalue.UnmarshalListOfMaps(response.Items, &moviePage)
				if err != nil {
					log.Printf("Couldn't unmarshal query response. Here's why: %v\n", err)
					break
				} else {
					movies = append(movies, moviePage...)
				}
			}
		}
	}
	return movies, err
}
```
Définissez une structure Movie utilisée dans cet exemple.  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// 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 plus d’informations sur l’API, consultez [Requête](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.Query) dans la *référence d’API AWS SDK pour Go *. 

------
#### [ Java ]

**SDK pour Java 2.x**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
Interroge une table à l'aide de [DynamoDbClient](https://docs.aws.amazon.com/sdk-for-java/latest/reference/software/amazon/awssdk/services/dynamodb/DynamoDbClient.html).  

```
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.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import java.util.HashMap;

/**
 * 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 query items from an Amazon DynamoDB table using the AWS SDK for Java V2,
 * its better practice to use the
 * Enhanced Client. See the EnhancedQueryRecords example.
 */
public class Query {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <partitionKeyName> <partitionKeyVal>

                Where:
                    tableName - The Amazon DynamoDB table to put the item in (for example, Music3).
                    partitionKeyName - The partition key name of the Amazon DynamoDB table (for example, Artist).
                    partitionKeyVal - The value of the partition key that should match (for example, Famous Band).
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String partitionKeyName = args[1];
        String partitionKeyVal = args[2];

        // For more information about an alias, see:
        // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html
        String partitionAlias = "#a";

        System.out.format("Querying %s", tableName);
        System.out.println("");
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        int count = queryTable(ddb, tableName, partitionKeyName, partitionKeyVal, partitionAlias);
        System.out.println("There were " + count + "  record(s) returned");
        ddb.close();
    }

    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;
    }
}
```
Interroge une table à l’aide de `DynamoDbClient` et d’un index secondaire.  

```
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.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 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
 *
 * Create the Movies table by running the Scenario example and loading the Movie
 * data from the JSON file. Next create a secondary
 * index for the Movies table that uses only the year column. Name the index
 * **year-index**. For more information, see:
 *
 * https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html
 */
public class QueryItemsUsingIndex {
    public static void main(String[] args) {
        String tableName = "Movies";
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        queryIndex(ddb, tableName);
        ddb.close();
    }

    public static void queryIndex(DynamoDbClient ddb, String tableName) {
        try {
            Map<String, String> expressionAttributesNames = new HashMap<>();
            expressionAttributesNames.put("#year", "year");
            Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
            expressionAttributeValues.put(":yearValue", AttributeValue.builder().n("2013").build());

            QueryRequest request = QueryRequest.builder()
                    .tableName(tableName)
                    .indexName("year-index")
                    .keyConditionExpression("#year = :yearValue")
                    .expressionAttributeNames(expressionAttributesNames)
                    .expressionAttributeValues(expressionAttributeValues)
                    .build();

            System.out.println("=== Movie Titles ===");
            QueryResponse response = ddb.query(request);
            response.items()
                    .forEach(movie -> System.out.println(movie.get("title").s()));

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  Pour plus d’informations sur l’API, consultez [Requête](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query) dans la *référence d’API AWS SDK for Java 2.x *. 

------
#### [ JavaScript ]

**SDK pour JavaScript (v3)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Cet exemple utilise le client de document pour simplifier l’utilisation d’éléments dans DynamoDB. Pour plus de détails sur l'API, voir [QueryCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/QueryCommand/).  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { QueryCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new QueryCommand({
    TableName: "CoffeeCrop",
    KeyConditionExpression:
      "OriginCountry = :originCountry AND RoastDate > :roastDate",
    ExpressionAttributeValues: {
      ":originCountry": "Ethiopia",
      ":roastDate": "2023-05-01",
    },
    ConsistentRead: true,
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  Pour plus d’informations, consultez le [Guide du développeur AWS SDK pour JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying). 
+  Pour plus d’informations sur l’API, consultez [Requête](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand) dans la *référence d’API AWS SDK pour JavaScript *. 

**SDK pour JavaScript (v2)**  
 Il y en a plus sur GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le [ référentiel d'exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples). 

```
// 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 = {
  ExpressionAttributeValues: {
    ":s": 2,
    ":e": 9,
    ":topic": "PHRASE",
  },
  KeyConditionExpression: "Season = :s and Episode > :e",
  FilterExpression: "contains (Subtitle, :topic)",
  TableName: "EPISODES_TABLE",
};

docClient.query(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Items);
  }
});
```
+  Pour plus d’informations, consultez le [Guide du développeur AWS SDK pour JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying). 
+  Pour plus d’informations sur l’API, consultez [Requête](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/Query) dans la *référence d’API AWS SDK pour JavaScript *. 

------
#### [ Kotlin ]

**SDK pour Kotlin**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples). 

```
suspend fun queryDynTable(
    tableNameVal: String,
    partitionKeyName: String,
    partitionKeyVal: String,
    partitionAlias: String,
): Int {
    val attrNameAlias = mutableMapOf<String, String>()
    attrNameAlias[partitionAlias] = partitionKeyName

    // Set up mapping of the partition name with the value.
    val attrValues = mutableMapOf<String, AttributeValue>()
    attrValues[":$partitionKeyName"] = AttributeValue.S(partitionKeyVal)

    val request =
        QueryRequest {
            tableName = tableNameVal
            keyConditionExpression = "$partitionAlias = :$partitionKeyName"
            expressionAttributeNames = attrNameAlias
            this.expressionAttributeValues = attrValues
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val response = ddb.query(request)
        return response.count
    }
}
```
+  Pour plus de détails sur l’API, consultez [Query](https://sdk.amazonaws.com/kotlin/api/latest/index.html) dans la *Référence des API du kit AWS SDK pour Kotlin*. 

------
#### [ PHP ]

**Kit SDK pour PHP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples). 

```
        $birthKey = [
            'Key' => [
                'year' => [
                    'N' => "$birthYear",
                ],
            ],
        ];
        $result = $service->query($tableName, $birthKey);

    public function query(string $tableName, $key)
    {
        $expressionAttributeValues = [];
        $expressionAttributeNames = [];
        $keyConditionExpression = "";
        $index = 1;
        foreach ($key as $name => $value) {
            $keyConditionExpression .= "#" . array_key_first($value) . " = :v$index,";
            $expressionAttributeNames["#" . array_key_first($value)] = array_key_first($value);
            $hold = array_pop($value);
            $expressionAttributeValues[":v$index"] = [
                array_key_first($hold) => array_pop($hold),
            ];
        }
        $keyConditionExpression = substr($keyConditionExpression, 0, -1);
        $query = [
            'ExpressionAttributeValues' => $expressionAttributeValues,
            'ExpressionAttributeNames' => $expressionAttributeNames,
            'KeyConditionExpression' => $keyConditionExpression,
            'TableName' => $tableName,
        ];
        return $this->dynamoDbClient->query($query);
    }
```
+  Pour plus de détails sur l’API, consultez [Query](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/Query) dans la *Référence des API du kit AWS SDK pour PHP *. 

------
#### [ PowerShell ]

**Outils pour PowerShell V4**  
**Exemple 1 : invoque une requête qui renvoie des éléments DynamoDB avec les valeurs spécifiées et Artist. SongTitle **  

```
$invokeDDBQuery = @{
    TableName = 'Music'
    KeyConditionExpression = ' SongTitle = :SongTitle and Artist = :Artist'
    ExpressionAttributeValues = @{
        ':SongTitle' = 'Somewhere Down The Road'
        ':Artist' = 'No One You Know'
    } | ConvertTo-DDBItem
}
Invoke-DDBQuery @invokeDDBQuery | ConvertFrom-DDBItem
```
**Sortie** :  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  Pour plus de détails sur l’API, consultez [Query](https://docs.aws.amazon.com/powershell/v4/reference) dans la *Référence des applets de commande pour les Outils AWS pour PowerShell  (V4)*. 

**Outils pour PowerShell V5**  
**Exemple 1 : invoque une requête qui renvoie des éléments DynamoDB avec les valeurs spécifiées et Artist. SongTitle **  

```
$invokeDDBQuery = @{
    TableName = 'Music'
    KeyConditionExpression = ' SongTitle = :SongTitle and Artist = :Artist'
    ExpressionAttributeValues = @{
        ':SongTitle' = 'Somewhere Down The Road'
        ':Artist' = 'No One You Know'
    } | ConvertTo-DDBItem
}
Invoke-DDBQuery @invokeDDBQuery | ConvertFrom-DDBItem
```
**Sortie** :  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  Pour plus de détails sur l’API, consultez [Query](https://docs.aws.amazon.com/powershell/v5/reference) dans la *Référence des applets de commande pour les Outils AWS pour PowerShell  (V5)*. 

------
#### [ Python ]

**Kit SDK for Python (Boto3)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 
Interrogez des éléments à l’aide d’une expression de condition clé.  

```
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 query_movies(self, year):
        """
        Queries for movies that were released in the specified year.

        :param year: The year to query.
        :return: The list of movies that were released in the specified year.
        """
        try:
            response = self.table.query(KeyConditionExpression=Key("year").eq(year))
        except ClientError as err:
            logger.error(
                "Couldn't query for movies released in %s. Here's why: %s: %s",
                year,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Items"]
```
Interrogez des éléments et projetez-les pour renvoyer un sous-ensemble de données.  

```
class UpdateQueryWrapper:
    def __init__(self, table):
        self.table = table


    def query_and_project_movies(self, year, title_bounds):
        """
        Query for movies that were released in a specified year and that have titles
        that start within a range of letters. A projection expression is used
        to return a subset of data for each movie.

        :param year: The release year to query.
        :param title_bounds: The range of starting letters to query.
        :return: The list of movies.
        """
        try:
            response = self.table.query(
                ProjectionExpression="#yr, title, info.genres, info.actors[0]",
                ExpressionAttributeNames={"#yr": "year"},
                KeyConditionExpression=(
                    Key("year").eq(year)
                    & Key("title").between(
                        title_bounds["first"], title_bounds["second"]
                    )
                ),
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ValidationException":
                logger.warning(
                    "There's a validation error. Here's the message: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            else:
                logger.error(
                    "Couldn't query for movies. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return response["Items"]
```
+  Pour plus de détails sur l’API, consultez [Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query) dans la *Référence des API du kit AWS SDK for Python (Boto3)*. 

------
#### [ Ruby ]

**Kit SDK pour Ruby**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples). 

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :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

  # Queries for movies that were released in the specified year.
  #
  # @param year [Integer] The year to query.
  # @return [Array] The list of movies that were released in the specified year.
  def query_items(year)
    response = @table.query(
      key_condition_expression: '#yr = :year',
      expression_attribute_names: { '#yr' => 'year' },
      expression_attribute_values: { ':year' => year }
    )
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't query for movies released in #{year}. Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  else
    response.items
  end
```
+  Pour plus d’informations sur l’API, consultez [Requête](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/Query) dans la *référence d’API AWS SDK pour Ruby *. 

------
#### [ Rust ]

**SDK pour Rust**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples). 
Trouvez les films réalisés au cours de l’année spécifiée.  

```
pub async fn movies_in_year(
    client: &Client,
    table_name: &str,
    year: u16,
) -> Result<Vec<Movie>, MovieError> {
    let results = client
        .query()
        .table_name(table_name)
        .key_condition_expression("#yr = :yyyy")
        .expression_attribute_names("#yr", "year")
        .expression_attribute_values(":yyyy", AttributeValue::N(year.to_string()))
        .send()
        .await?;

    if let Some(items) = results.items {
        let movies = items.iter().map(|v| v.into()).collect();
        Ok(movies)
    } else {
        Ok(vec![])
    }
}
```
+  Pour plus de détails sur l’API, consultez [Query](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.query) dans la *Référence des API du kit AWS SDK pour Rust*. 

------
#### [ SAP ABAP ]

**Kit SDK pour SAP ABAP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples). 

```
    TRY.
        " Query movies for a given year .
        DATA(lt_attributelist) = VALUE /aws1/cl_dynattributevalue=>tt_attributevaluelist(
            ( NEW /aws1/cl_dynattributevalue( iv_n = |{ iv_year }| ) ) ).
        DATA(lt_key_conditions) = VALUE /aws1/cl_dyncondition=>tt_keyconditions(
          ( VALUE /aws1/cl_dyncondition=>ts_keyconditions_maprow(
          key = 'year'
          value = NEW /aws1/cl_dyncondition(
          it_attributevaluelist = lt_attributelist
          iv_comparisonoperator = |EQ|
          ) ) ) ).
        oo_result = lo_dyn->query(
          iv_tablename = iv_table_name
          it_keyconditions = lt_key_conditions ).
        DATA(lt_items) = oo_result->get_items( ).
        "You can loop over the results to get item attributes.
        LOOP AT lt_items INTO DATA(lt_item).
          DATA(lo_title) = lt_item[ key = 'title' ]-value.
          DATA(lo_year) = lt_item[ key = 'year' ]-value.
        ENDLOOP.
        DATA(lv_count) = oo_result->get_count( ).
        MESSAGE 'Item count is: ' && lv_count TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
    ENDTRY.
```
+  Pour plus d’informations sur l’API, consultez [Query](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html) dans le *guide de référence d’API du kit SDK AWS pour SAP ABAP*. 

------
#### [ Swift ]

**Kit SDK pour Swift**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples). 

```
import AWSDynamoDB


    /// Get all the movies released in the specified year.
    ///
    /// - Parameter year: The release year of the movies to return.
    ///
    /// - Returns: An array of `Movie` objects describing each matching movie.
    ///
    func getMovies(fromYear year: Int) async throws -> [Movie] {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = QueryInput(
                expressionAttributeNames: [
                    "#y": "year"
                ],
                expressionAttributeValues: [
                    ":y": .n(String(year))
                ],
                keyConditionExpression: "#y = :y",
                tableName: self.tableName
            )
            // Use "Paginated" to get all the movies.
            // This lets the SDK handle the 'lastEvaluatedKey' property in "QueryOutput".

            let pages = client.queryPaginated(input: input)

            var movieList: [Movie] = []
            for try await page in pages {
                guard let items = page.items else {
                    print("Error: no items returned.")
                    continue
                }

                // Convert the found movies into `Movie` objects and return an array
                // of them.

                for item in items {
                    let movie = try Movie(withItem: item)
                    movieList.append(movie)
                }
            }
            return movieList
        } catch {
            print("ERROR: getMovies:", dump(error))
            throw error
        }
    }
```
+  Pour plus d’informations sur l’API, consultez [Requête](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/query(input:)) dans la *référence de l’API du kit SDK AWS for Swift*. 

------

Pour obtenir plus d’exemples avec DynamoDB, consultez [Exemples de code pour DynamoDB utilisant AWS SDKs](service_code_examples.md).

Pour créer un index secondaire global pour votre table, passez à l’ [Étape 6 : (Facultatif) supprimer votre table DynamoDB pour nettoyer les ressources](getting-started-step-6.md).

# Étape 6 : (Facultatif) supprimer votre table DynamoDB pour nettoyer les ressources
<a name="getting-started-step-6"></a>

Si vous n’avez plus besoin de la table Amazon DynamoDB que vous avez créée pour le didacticiel, vous pouvez la supprimer. Cette étape permet de vous assurer de ne pas être facturé pour des ressources que vous n’utilisez pas. Vous pouvez utiliser la console DynamoDB ou AWS CLI le pour supprimer la table que vous avez `Music` créée dans. [Étape 1 : création d’une table dans DynamoDB](getting-started-step-1.md)

Pour plus d’informations sur les opérations de table dans DynamoDB, consultez [Utilisation de tables et de données dans DynamoDB](WorkingWithTables.md). 

## AWS Management Console
<a name="getting-started-step-8-Console"></a>

Pour supprimer la table `Music` à l’aide de la console :

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

1. Dans le volet de navigation de gauche, choisissez **Tables**.

1. Choisissez la case à cocher en regard de la table **Musique** dans la liste de tables.

1. Sélectionnez **Delete (Supprimer)**.

## AWS CLI
<a name="getting-started-step-8-CLI"></a>

L' AWS CLI exemple suivant supprime le `Music` tableau à l'aide `delete-table` de.

```
aws dynamodb delete-table --table-name Music
```

## AWS SDK
<a name="getting-started-step-8-SDK"></a>

Les exemples de code suivants montrent comment supprimer une table DynamoDB à l’aide d’un kit SDK AWS .

------
#### [ .NET ]

**SDK pour .NET (v4)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples). 

```
    /// <summary>
    /// Deletes a DynamoDB table.
    /// </summary>
    /// <param name="tableName">The name of the table to delete.</param>
    /// <returns>A Boolean value indicating the success of the operation.</returns>
    public async Task<bool> DeleteTableAsync(string tableName)
    {
        try
        {
            var request = new DeleteTableRequest
            {
                TableName = tableName,
            };

            var response = await _amazonDynamoDB.DeleteTableAsync(request);

            Console.WriteLine($"Table {response.TableDescription.TableName} successfully deleted.");
            return true;

        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found and cannot be deleted. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while deleting table {tableName}. {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting table {tableName}. {ex.Message}");
            return false;
        }
    }
```
+  Pour plus de détails sur l'API, reportez-vous [DeleteTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/DeleteTable)à la section *Référence des AWS SDK pour .NET API*. 

------
#### [ Bash ]

**AWS CLI avec le script Bash**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples). 

```
###############################################################################
# function dynamodb_delete_table
#
# This function deletes a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table to delete.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function dynamodb_delete_table() {
  local table_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function dynamodb_delete_table"
    echo "Deletes an Amazon DynamoDB table."
    echo " -n table_name  -- The name of the table to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) table_name="${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

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho ""

  response=$(aws dynamodb delete-table \
    --table-name "$table_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-table operation failed.$response"
    return 1
  fi

  return 0
}
```
Fonctions utilitaires utilisées dans cet exemple.  

```
###############################################################################
# function iecho
#
# This function enables the script to display the specified text only if
# the global variable $VERBOSE is set to true.
###############################################################################
function iecho() {
  if [[ $VERBOSE == true ]]; then
    echo "$@"
  fi
}

###############################################################################
# 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 plus de détails sur l'API, voir [DeleteTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteTable)la section *Référence des AWS CLI commandes*. 

------
#### [ C\$1\$1 ]

**SDK pour C\$1\$1**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples). 

```
//! Delete an Amazon DynamoDB table.
/*!
  \sa deleteTable()
  \param tableName: The DynamoDB table name.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::deleteTable(const Aws::String &tableName,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DeleteTableRequest request;
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::DeleteTableOutcome &result = dynamoClient.DeleteTable(
            request);
    if (result.IsSuccess()) {
        std::cout << "Your table \""
                  << result.GetResult().GetTableDescription().GetTableName()
                  << " was deleted.\n";
    }
    else {
        std::cerr << "Failed to delete table: " << result.GetError().GetMessage()
                  << std::endl;
    }

    return result.IsSuccess();
}
```
+  Pour plus de détails sur l'API, reportez-vous [DeleteTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/DeleteTable)à la section *Référence des AWS SDK pour C\$1\$1 API*. 

------
#### [ CLI ]

**AWS CLI**  
**Pour supprimer une table**  
L’exemple `delete-table` suivant supprime la table `MusicCollection`.  

```
aws dynamodb delete-table \
    --table-name MusicCollection
```
Sortie :  

```
{
    "TableDescription": {
        "TableStatus": "DELETING",
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableName": "MusicCollection",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "WriteCapacityUnits": 5,
            "ReadCapacityUnits": 5
        }
    }
}
```
Pour plus d’informations, consultez [Suppression d’une table](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeleteTable) dans le *Guide du développeur Amazon DynamoDB*.  
+  Pour plus de détails sur l'API, voir [DeleteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/delete-table.html)la section *Référence des AWS CLI commandes*. 

------
#### [ Go ]

**Kit SDK pour Go V2**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples). 

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

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



// DeleteTable deletes the DynamoDB table and all of its data.
func (basics TableBasics) DeleteTable(ctx context.Context) error {
	_, err := basics.DynamoDbClient.DeleteTable(ctx, &dynamodb.DeleteTableInput{
		TableName: aws.String(basics.TableName)})
	if err != nil {
		log.Printf("Couldn't delete table %v. Here's why: %v\n", basics.TableName, err)
	}
	return err
}
```
+  Pour plus de détails sur l'API, reportez-vous [DeleteTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.DeleteTable)à la section *Référence des AWS SDK pour Go API*. 

------
#### [ Java ]

**SDK pour Java 2.x**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 

```
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.DeleteTableRequest;

/**
 * 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
 */

public class DeleteTable {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName>

                Where:
                    tableName - The Amazon DynamoDB table to delete (for example, Music3).

                **Warning** This program will delete the table that you specify!
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        System.out.format("Deleting the Amazon DynamoDB table %s...\n", tableName);
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        deleteDynamoDBTable(ddb, tableName);
        ddb.close();
    }

    public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {
        DeleteTableRequest request = DeleteTableRequest.builder()
                .tableName(tableName)
                .build();

        try {
            ddb.deleteTable(request);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println(tableName + " was successfully deleted!");
    }
}
```
+  Pour plus de détails sur l'API, reportez-vous [DeleteTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DeleteTable)à la section *Référence des AWS SDK for Java 2.x API*. 

------
#### [ JavaScript ]

**SDK pour JavaScript (v3)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 

```
import { DeleteTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb";

const client = new DynamoDBClient({});

export const main = async () => {
  const command = new DeleteTableCommand({
    TableName: "DecafCoffees",
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  Pour plus de détails sur l'API, reportez-vous [DeleteTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DeleteTableCommand)à la section *Référence des AWS SDK pour JavaScript API*. 

**SDK pour JavaScript (v2)**  
 Il y en a plus sur GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le [ référentiel d'exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples). 

```
// 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: process.argv[2],
};

// Call DynamoDB to delete the specified table
ddb.deleteTable(params, function (err, data) {
  if (err && err.code === "ResourceNotFoundException") {
    console.log("Error: Table not found");
  } else if (err && err.code === "ResourceInUseException") {
    console.log("Error: Table in use");
  } else {
    console.log("Success", data);
  }
});
```
+  Pour plus d’informations, consultez le [Guide du développeur AWS SDK pour JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-deleting-a-table). 
+  Pour plus de détails sur l'API, reportez-vous [DeleteTable](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/DeleteTable)à la section *Référence des AWS SDK pour JavaScript API*. 

------
#### [ Kotlin ]

**SDK pour Kotlin**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples). 

```
suspend fun deleteDynamoDBTable(tableNameVal: String) {
    val request =
        DeleteTableRequest {
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.deleteTable(request)
        println("$tableNameVal was deleted")
    }
}
```
+  Pour plus de détails sur l'API, consultez [DeleteTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)la section *AWS SDK pour la référence de l'API Kotlin*. 

------
#### [ PHP ]

**Kit SDK pour PHP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples). 

```
    public function deleteTable(string $TableName)
    {
        $this->customWaiter(function () use ($TableName) {
            return $this->dynamoDbClient->deleteTable([
                'TableName' => $TableName,
            ]);
        });
    }
```
+  Pour plus de détails sur l'API, voir [DeleteTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/DeleteTable)la section *Référence des AWS SDK pour PHP API*. 

------
#### [ PowerShell ]

**Outils pour PowerShell V4**  
**Exemple 1 : supprime la table spécifiée. Vous êtes invité à confirmer avant que l’opération ne se poursuive.**  

```
Remove-DDBTable -TableName "myTable"
```
**Exemple 2 : supprime la table spécifiée. Aucune confirmation ne vous est demandée avant le début de l’opération.**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  Pour plus de détails sur l'API, reportez-vous [DeleteTable](https://docs.aws.amazon.com/powershell/v4/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V4)*. 

**Outils pour PowerShell V5**  
**Exemple 1 : supprime la table spécifiée. Vous êtes invité à confirmer avant que l’opération ne se poursuive.**  

```
Remove-DDBTable -TableName "myTable"
```
**Exemple 2 : supprime la table spécifiée. Aucune confirmation ne vous est demandée avant le début de l’opération.**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  Pour plus de détails sur l'API, reportez-vous [DeleteTable](https://docs.aws.amazon.com/powershell/v5/reference)à la section *Référence des Outils AWS pour PowerShell applets de commande (V5)*. 

------
#### [ Python ]

**Kit SDK for Python (Boto3)**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 

```
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 delete_table(self):
        """
        Deletes the table.
        """
        try:
            self.table.delete()
            self.table = None
        except ClientError as err:
            logger.error(
                "Couldn't delete table. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  Pour plus de détails sur l'API, consultez [DeleteTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DeleteTable)le *AWS manuel de référence de l'API SDK for Python (Boto3*). 

------
#### [ Ruby ]

**Kit SDK pour Ruby**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples). 

```
# Encapsulates an Amazon DynamoDB table of movie data.
class Scaffold
  attr_reader :dynamo_resource, :table_name, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table_name = table_name
    @table = nil
    @logger = Logger.new($stdout)
    @logger.level = Logger::DEBUG
  end

  # Deletes the table.
  def delete_table
    @table.delete
    @table = nil
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't delete table. Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  Pour plus de détails sur l'API, voir [DeleteTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/DeleteTable)la section *Référence des AWS SDK pour Ruby API*. 

------
#### [ Rust ]

**SDK pour Rust**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples). 

```
pub async fn delete_table(client: &Client, table: &str) -> Result<DeleteTableOutput, Error> {
    let resp = client.delete_table().table_name(table).send().await;

    match resp {
        Ok(out) => {
            println!("Deleted table");
            Ok(out)
        }
        Err(e) => Err(Error::Unhandled(e.into())),
    }
}
```
+  Pour plus de détails sur l'API, voir [DeleteTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.delete_table)la section de *référence de l'API AWS SDK for Rust*. 

------
#### [ SAP ABAP ]

**Kit SDK pour SAP ABAP**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples). 

```
    TRY.
        lo_dyn->deletetable( iv_tablename = iv_table_name ).
        " Wait till the table is actually deleted.
        lo_dyn->get_waiter( )->tablenotexists(
          iv_max_wait_time = 200
          iv_tablename     = iv_table_name ).
        MESSAGE 'Table ' && iv_table_name && ' deleted.' TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table ' && iv_table_name && ' does not exist' TYPE 'E'.
      CATCH /aws1/cx_dynresourceinuseex.
        MESSAGE 'The table cannot be deleted since it is in use' TYPE 'E'.
    ENDTRY.
```
+  Pour plus de détails sur l'API, consultez [DeleteTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)la section de référence du *AWS SDK pour l'API SAP ABAP*. 

------
#### [ Swift ]

**Kit SDK pour Swift**  
 Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le [référentiel d’exemples de code AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples). 

```
import AWSDynamoDB


    ///
    /// Deletes the table from Amazon DynamoDB.
    ///
    func deleteTable() async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = DeleteTableInput(
                tableName: self.tableName
            )
            _ = try await client.deleteTable(input: input)
        } catch {
            print("ERROR: deleteTable:", dump(error))
            throw error
        }
    }
```
+  Pour plus de détails sur l'API, reportez-vous [DeleteTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/deletetable(input:))à la section *AWS SDK pour la référence de l'API Swift*. 

------

Pour obtenir plus d’exemples avec DynamoDB, consultez [Exemples de code pour DynamoDB utilisant AWS SDKs](service_code_examples.md).

# Poursuivre l’apprentissage concernant DynamoDB
<a name="getting-started-NextSteps"></a>

Pour plus d’informations sur l’utilisation d’Amazon DynamoDB, consultez les rubriques suivantes :
+ [Utilisation de tables et de données dans DynamoDB](WorkingWithTables.md)
+ [Utilisation d’éléments et d’attributs dans DynamoDB](WorkingWithItems.md)
+ [Interrogation de tables dans DynamoDB](Query.md)
+ [Utilisation d’index secondaires globaux dans DynamoDB](GSI.md)
+ [Utilisation des transactionsExemple de code](transactions.md)
+ [Accélération en mémoire avec DynamoDB Accelerator (DAX)](DAX.md)
+ [Programmation avec DynamoDB et le AWS SDKs](Programming.md)

# Générez du code d'infrastructure pour Amazon DynamoDB à l'aide de Console-to-Code
<a name="console-to-code"></a>

La Console-to-Code fonctionnalité Amazon Q Developer simplifie la gestion de l'infrastructure pour Amazon DynamoDB en transformant les étapes de création manuelle de tables en code d'automatisation reproductible. Cette fonctionnalité aide les développeurs à mettre à l’échelle efficacement la configuration des ressources de base de données dans leurs environnements. Pour plus d'informations, consultez [Automatiser Services AWS avec Amazon Q Developer Console-to-Code](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/console-to-code.html).

Console-to-Code capture les configurations détaillées des tables DynamoDB, y compris les clés de partition, les clés de tri, les paramètres de débit provisionnés et les index secondaires, et les convertit en modèles précis. infrastructure-as-code Grâce à l’IA générative, cet outil garantit que le code généré maintient la compatibilité des paramètres établie au cours du flux de travail de la console.

Les développeurs peuvent générer du code d’infrastructure DynamoDB dans plusieurs formats, tels que :
+ AWS Cloud Development Kit (AWS CDK) TypeScript en Python et Java
+ CloudFormation en YAML ou JSON

Cette approche permet aux équipes de :
+ normaliser la gestion des ressources de base de données ;
+ mettre en œuvre une infrastructure contrôlée par version ;
+ réduire les erreurs de configuration manuelle.

Console-to-Code pour Amazon DynamoDB est disponible dans toutes les régions AWS commerciales, fournissant une solution puissante pour transformer les configurations manuelles en code d'infrastructure automatisé et reproductible.

## Comment ça marche
<a name="how-it-works"></a>

Lors de l'utilisation Console-to-Code avec DynamoDB, le processus implique généralement :

1. **Prototypage dans la console** : utilisez la console DynamoDB pour créer et configurer des ressources telles que des tables. Consultez [Connect to Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStartedDynamoDB.html) pour plus d’informations.

1. **Enregistrement des actions** : Console-to-Code enregistre ces actions au fur et à mesure que vous les effectuez.

1. **Génération de code** : cette fonctionnalité utilise les capacités d’IA générative d’Amazon Q Developer pour transformer les actions de votre console en code réutilisable dans le format de votre choix.

1. **Personnalisation du code** : vous pouvez ensuite copier ou télécharger ce code et le personnaliser davantage en fonction de vos charges de travail de production.

## Avantages de l'utilisation Console-to-Code avec DynamoDB
<a name="benefits"></a>

**Automatisation simplifiée**  
Convertissez la création et la configuration manuelles de tables DynamoDB en code réutilisable d’un simple clic.

**Bonnes pratiques**  
Le code généré suit les meilleures pratiques AWS guidées pour des déploiements fiables.

**Pont entre la console et le code**  
Vous n'avez pas à choisir entre utiliser le AWS Management Console ou Infrastructure-as-Code (iAc). Vous pouvez utiliser les deux approches ensemble.

**Développement accéléré**  
Démarrez rapidement avec un code d’automatisation qui peut être davantage personnalisé pour une utilisation en production.

## Exemples de cas d’utilisation
<a name="example-use-cases"></a>
+ Création de tables DynamoDB avec des attributs, des clés et des paramètres de capacité spécifiques
+ Configuration d’index secondaires globaux et d’index secondaires locaux
+ Configuration de politiques d’autoscaling pour les tables DynamoDB
+ Définition de configurations de sauvegarde et de restauration
+ Création et gestion de DynamoDB Streams

## Prise en main
<a name="getting-started"></a>

Pour commencer à utiliser Console-to-Code DynamoDB :

1. Connectez-vous à la console DynamoDB AWS Management Console et ouvrez-la à l'adresse. [https://console.aws.amazon.com/dynamodbv2/](https://console.aws.amazon.com/dynamodbv2/)

1. Commencez à créer ou à modifier des ressources DynamoDB via l’interface de console.

1. Utilisez Console-to-Code cette fonctionnalité pour générer du code pour vos actions dans le format de votre choix.

1. Copiez ou téléchargez le code généré et personnalisez-le selon vos besoins spécifiques.

Pour plus d'informations et des instructions détaillées sur l'utilisation Console-to-Code, consultez [Automating Services AWS with Amazon Q Developer Console-to-Code](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/console-to-code.html) dans le *guide de l'utilisateur Amazon Q Developer*.