

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Nozioni di base su DynamoDB
<a name="GettingStartedDynamoDB"></a>

Le seguenti sezioni forniscono informazioni sulla connessione alle tabelle DynamoDB e la loro creazione e gestione.

Prima di iniziare, dovresti apprendere i concetti di base di Amazon DynamoDB. Sono disponibili una rapida panoramica in [Che cos'è Amazon DynamoDB?](Introduction.md) e un approfondimento in [Componenti principali di Amazon DynamoDB](HowItWorks.CoreComponents.md). Quindi, continua con [Prerequisiti](#GettingStarted.SettingUp.DynamoWebService).

**Nota**  
[Quando ti registri AWS, puoi iniziare a usare DynamoDB utilizzando AWS il piano gratuito.](https://aws.amazon.com/free/) Se non sono ancora stati utilizzati tutti i vantaggi previsti dal piano gratuito per Amazon DynamoDB, non verrà addebitato alcun costo per gli esempi in questa sezione. In caso contrario, verranno addebitati i costi di utilizzo standard di DynamoDB dal momento della creazione fino all’eliminazione.  
Se non si desidera sottoscrivere un account per un piano gratuito, è possibile configurare [DynamoDB locale (versione scaricabile)](DynamoDBLocal.md) sul computer. La versione scaricabile consente di sviluppare e testare applicazioni localmente senza registrare un AWS account o accedere al servizio web DynamoDB.

**Topics**
+ [Risorse Amazon DynamoDB per gli utenti alle prime armi](dynamodb-resources-first-time-users.md)
+ [Accesso a DynamoDB](AccessingDynamoDB.md)
+ [Prerequisiti](#GettingStarted.SettingUp.DynamoWebService)
+ [Configurazione di DynamoDB](SettingUp.md)
+ [Fase 1: creare una tabella DynamoDB](getting-started-step-1.md)
+ [Fase 2: scrivere dati in una tabella DynamoDB](getting-started-step-2.md)
+ [Fase 3: leggere i dati da una tabella DynamoDB](getting-started-step-3.md)
+ [Fase 4: aggiornare i dati in una tabella](getting-started-step-4.md)
+ [Fase 5: eseguire query sui dati in una tabella DynamoDB](getting-started-step-5.md)
+ [Fase 6: (facoltativo) eliminare la tabella DynamoDB per eseguire la pulizia delle risorse](getting-started-step-6.md)
+ [Conoscenze aggiuntive su DynamoDB](getting-started-NextSteps.md)
+ [Genera codice di infrastruttura per Amazon DynamoDB utilizzando Console-to-Code](console-to-code.md)

# Risorse Amazon DynamoDB per gli utenti alle prime armi
<a name="dynamodb-resources-first-time-users"></a>

Si consiglia agli utenti alle prime armi di iniziare a leggere le seguenti sezioni e di farvi riferimento ogni volta che è necessario.


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

**Example**  
**[Aspetti salienti e prezzi del servizio](https://aws.amazon.com/dynamodb/)**  
Fornisce una panoramica generale del prodotto su DynamoDB, i casi d'uso più comuni, i punti salienti del servizio e i prezzi.  |  

**Example**  
**[Risorse DynamoDB](https://aws.amazon.com/dynamodb/resources/)**  
Video, tutorial e linee guida prescrittive che introducono al servizio, ai concetti di modellazione dei dati e alle caratteristiche e funzionalità principali.  | 
|  

**Example**  
**[Nozioni di base](GettingStartedDynamoDB.md)**  
Informazioni sulla configurazione di DynamoDB, sulla creazione di tabelle di esempio e sul caricamento dei dati.  |  

**Example**  
**[Corso di base su DynamoDB](https://explore.skillbuilder.aws/learn/course/external/view/elearning/16104/amazon-dynamodb-basics)**  
Corso digitale gratuito che insegna i fondamenti di DynamoDB, tra cui la progettazione di tabelle, i tipi di dati e le operazioni di base.  | 
|  

**Example**  
**[Pepite DynamoDB](https://www.youtube.com/playlist?list=PLhr1KZpdzukemNOO71Hca0GpjG0QmXwEd)**  
Video tutorial brevi e mirati che spiegano i concetti e le funzionalità chiave di DynamoDB.  |  

**Example**  
**[Archivio di esempi di codice DynamoDB](https://github.com/aws-samples/aws-dynamodb-examples)**  
Esempi pratici di codice DynamoDB in vari linguaggi di programmazione.  | 
|  

**Example**  
**[Formazione gratuita su DynamoDB](https://skillbuilder.aws/learn/WC3K4Y4S5N/amazon-dynamodb-getting-started/)**  
AWS offre corsi di formazione digitali gratuiti che coprono concetti, funzionalità e best practice di DynamoDB.  |  

**Example**  
**[Workbench NoSQL per DynamoDB](https://youtu.be/p5va6ZX9_o0)**  
Strumento visivo unificato che fornisce funzionalità di modellazione, visualizzazione dei dati e sviluppo di query.  | 
|  

**Example**  
**[Modelli di progettazione DynamoDB](best-practices.md)**  
Best practice ed esempi di modellazione dei dati per diversi casi d'uso con esempi di codice pratici.  |  

**Example**  
**[Tutorial pratici](https://aws.amazon.com/tutorials/create-nosql-table/)**  
Step-by-step sono disponibili tutorial Console di gestione AWS che guidano l'utente attraverso le attività più comuni di DynamoDB.  | 
|  

**Example**  
**[Migrazione a DynamoDB](migration-guide.md)**  
Panoramica del processo, degli strumenti e delle strategie per la migrazione di un database in DynamoDB.  |  

**Example**  
**[AWS Lente Well-Architected per DynamoDB](bp-wal.md)**  
Le migliori pratiche architettoniche per progettare e gestire applicazioni affidabili, sicure, efficienti ed economiche utilizzando DynamoDB.  | 

## Best practice aggiuntive di Amazon DynamoDB per gli utenti alle prime armi
<a name="additional-reading"></a>

Al termine delle sezioni precedenti, leggi queste sezioni:
+  **[Capacità di throughput di DynamoDB](capacity-mode.md)** 

  Fornisce una panoramica delle due modalità di throughput disponibili per DynamoDB e considerazioni sulla selezione della modalità di capacità appropriata per l’applicazione. La modalità on demand è l’opzione di throughput predefinita e consigliata per la maggior parte dei carichi di lavoro DynamoDB.
+  **[Best practice per la progettazione e l'architettura con DynamoDB](best-practices.md)** 

  Identificazione e risoluzione di problemi per massimizzare le prestazioni e ridurre al minimo i costi durante l’utilizzo di DynamoDB.

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

Se desideri utilizzare l'interfaccia a riga di AWS comando (AWS CLI), puoi utilizzare questi documenti per aiutarti a iniziare:
+  **Documentazione di [AWS CLI](https://docs.aws.amazon.com/cli/)** 

   Questa sezione fornisce informazioni su come scaricare AWS CLI, far AWS CLI funzionare il sistema e fornire le AWS credenziali. 
+  **[AWS CLI documentazione per DynamoDB](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/index.html)** 

   Questo documento separato copre tutti i comandi di DynamoDB, inclusi la sintassi e gli esempi. AWS CLI 

## Risorse di programmazione
<a name="new-user-programming-resources"></a>

È possibile scrivere programmi applicativi per utilizzare l’API DynamoDB con una serie di linguaggi di programmazione comuni. Ecco alcune risorse:
+  **[Strumenti per Amazon Web Services](https://aws.amazon.com/developer/tools/)** 

   AWS fornisce una serie di kit di sviluppo software (SDKs) con supporto per DynamoDB. È possibile scrivere codice per DynamoDB utilizzando Java, .NET, PHP, Ruby e altri linguaggi. Questi SDKs possono semplificare notevolmente lo sviluppo delle applicazioni formattando le richieste in DynamoDB, analizzando le risposte e fornendo la logica dei tentativi e la gestione degli errori. 
+  ** [Documentazione di riferimento dell’API DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/Welcome.html)**

   Se non desideri utilizzare il AWS SDKs, puoi interagire con DynamoDB direttamente utilizzando l'API DynamoDB. Questo documento riguarda tutte le operazioni API DynamoDB, inclusi la sintassi e gli esempi. In questa sezione puoi trovare suggerimenti per risolvere i problemi e informazioni su come creare e autenticare richieste e gestire risposte. 

# Accesso a DynamoDB
<a name="AccessingDynamoDB"></a>

 Puoi accedere ad Amazon DynamoDB utilizzando, Console di gestione AWS the AWS CLI() o AWS Command Line Interface l'API DynamoDB.

**Topics**
+ [Utilizzo della console](#ConsoleDynamoDB)
+ [Utilizzando il AWS CLI](#Tools.CLI)
+ [Utilizzo dell’API](#Using.API)
+ [Utilizzo di NoSQL Workbench per DynamoDB](#Using.Workbench)
+ [Intervalli di indirizzi IP](#Using.IPRanges)
+ [Endpoint dual-stack per Internet Protocol versione 6 () IPv6](#dual-stackipv4-6)

## Utilizzo della console
<a name="ConsoleDynamoDB"></a>

[Puoi accedere a Amazon DynamoDB da casahttps://console.aws.amazon.com/dynamodb/. Console di gestione AWS](https://console.aws.amazon.com/dynamodb/home)

Ecco alcune delle azioni che è possibile eseguire nella console DynamoDB:
+ **Gestione di tabelle**: creazione, aggiornamento ed eliminazione di tabelle. Il calcolatore di capacità può essere utile per stimare i requisiti di capacità.
+ **Interazione con i dati**: visualizzazione, aggiunta, aggiornamento ed eliminazione degli elementi presenti nelle tabelle. Gestione delle impostazioni del Time to Live (TTL).
+ **Monitoraggio e analisi**: visualizzazione di dashboard, monitoraggio e configurazione di allarmi, nonché analisi di metriche e avvisi per le tabelle DynamoDB.
+ **Ottimizzazione ed estensione**: gestione di indici secondari, flussi, trigger, capacità riservata e altre funzionalità avanzate per migliorare l’utilizzo di DynamoDB.

La console DynamoDB fornisce un’interfaccia completa per la gestione delle risorse DynamoDB. Si consiglia di accedere alla console e interagire con essa per saperne di più.

## Utilizzando il AWS CLI
<a name="Tools.CLI"></a>

 È possibile utilizzare il AWS Command Line Interface (AWS CLI) per controllare più AWS servizi dalla riga di comando e automatizzarli tramite script. È possibile utilizzarlo AWS CLI per operazioni ad hoc, come la creazione di una tabella. È possibile utilizzarla anche per incorporare operazioni Amazon DynamoDB all'interno di script di utilità.

 Prima di poterlo utilizzare AWS CLI con DynamoDB, è necessario ottenere un ID della chiave di accesso e una chiave di accesso segreta. Per ulteriori informazioni, consulta [Concessione dell'accesso programmatico](SettingUp.DynamoWebService.md#SettingUp.DynamoWebService.GetCredentials). 

[Per un elenco completo di tutti i comandi disponibili per DynamoDB in, consulta AWS CLIAWS CLI il riferimento ai comandi.](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/index.html)

**Topics**

### Scaricamento e configurazione di AWS CLI
<a name="Tools.CLI.DownloadingAndRunning"></a>

 AWS CLI È disponibile all'indirizzo [http://aws.amazon.com/cli](https://aws.amazon.com/cli). Viene eseguita su Windows, macOS o Linux. Dopo averlo scaricato AWS CLI, segui questi passaggi per installarlo e configurarlo:

1. Passa alla [Guida per l'utente di AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/).

1. Segui le istruzioni riportate in [Installazione della AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/installing.html) e [Configurazione della AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html).

### Utilizzo di AWS CLI con DynamoDB
<a name="Tools.CLI.UsingWithDDB"></a>

Il formato della riga di comando è costituito dal nome dell'operazione DynamoDB seguito dai parametri per l'operazione. AWS CLI Supporta una sintassi abbreviata per i valori dei parametri, oltre a JSON.

Ad esempio, il seguente comando crea una tabella denominata *Music*. La chiave di partizione è *Artist* e la chiave di ordinamento è. *SongTitle* Per facilitare la leggibilità, in questa sezione i comandi lunghi sono suddivisi su righe separate.

```
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
```

I seguenti comandi aggiungono nuovi item alla tabella. In questi esempi viene utilizzata una combinazione di sintassi abbreviata e 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
```

Sulla riga di comando, può essere difficile comporre un JSON valido. Tuttavia, AWS CLI può leggere i file JSON. Considera ad esempio il seguente frammento di codice JSON, che viene memorizzato in un file denominato *key-conditions.json*:

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

È ora possibile emettere una richiesta `Query` utilizzando l' AWS CLI. In questo esempio il contenuto del file *key-conditions.json* viene utilizzato per il parametro `--key-conditions`:

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

### Utilizzo di AWS CLI con DynamoDB local
<a name="Tools.CLI.UsingWithDDBLocal"></a>

 AWS CLI Possono anche interagire con DynamoDB locale (versione scaricabile) in esecuzione sul computer. Per abilitare questo comportamento, aggiungi il seguente parametro a ciascun comando:

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

L'esempio seguente utilizza AWS CLI per elencare le tabelle in un database locale.

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

Se DynamoDB sta usando un numero di porta diverso da quello predefinito (8000), modificare di conseguenza il valore di `--endpoint-url`.

**Nota**  
Non AWS CLI possono utilizzare la versione locale di DynamoDB (versione scaricabile) come endpoint predefinito. Di conseguenza devi specificare `--endpoint-url` per ogni comando. 

## Utilizzo dell’API
<a name="Using.API"></a>

 Puoi usare Console di gestione AWS and the AWS Command Line Interface per lavorare in modo interattivo con Amazon DynamoDB. Tuttavia, per ottenere il massimo da DynamoDB, è possibile scrivere codice applicativo utilizzando. AWS SDKs

 AWS SDKs [https://aws.amazon.com/sdk-for-go](https://aws.amazon.com/sdk-for-go)

Prima di poterlo utilizzare AWS SDKs con DynamoDB, è necessario ottenere AWS un ID della chiave di accesso e una chiave di accesso segreta. Per ulteriori informazioni, consulta [Configurazione di DynamoDB (servizio Web)](SettingUp.DynamoWebService.md). 

 Per una panoramica di alto livello sulla programmazione di applicazioni DynamoDB con, vedere. AWS SDKs [Programmazione con DynamoDB e AWS SDKs](Programming.md) 

## Utilizzo di NoSQL Workbench per DynamoDB
<a name="Using.Workbench"></a>

È possibile accedere a DynamoDB anche scaricando e utilizzando [NoSQL Workbench per DynamoDB](workbench.md).

NoSQL Workbench per Amazon DynamoDB è un'applicazione GUI lato client multipiattaforma per operazioni e sviluppo di database moderni. È disponibile per Windows, macOS e Linux. NoSQL Workbench è uno strumento visuale di sviluppo che offre funzionalità di modellazione, visualizzazione dei dati, nonché funzionalità di sviluppo di query che consentono di progettare, creare, eseguire query e gestire le tabelle DynamoDB. NoSQL Workbench ora include la versione locale di DynamoDB come parte opzionale del processo di installazione, il che semplifica la modellazione dei dati nella versione locale di DynamoDB. Per ulteriori informazioni sulla versione locale di DynamoDB e i relativi requisiti, consulta [Configurazione di DynamoDB locale (versione scaricabile)](DynamoDBLocal.md).

**Nota**  
Il NoSQL Workbench per DynamoDB attualmente non AWS supporta gli accessi configurati con l'autenticazione a due fattori (2FA).

**Modellazione dei dati**  
Grazie a NoSQL Workbench per DynamoDB, è possibile creare nuovi modelli di dati o progettare modelli in base ai modelli di dati esistenti che soddisfino i pattern di accesso ai dati delle applicazioni. Puoi anche importare ed esportare il modello di dati progettato alla fine del processo. Per ulteriori informazioni, consulta [Creazione di modelli di dati con NoSQL Workbench](workbench.Modeler.md).

**Creazione di operazioni**  
NoSQL Workbench offre una ricca intergaffia utente grafica per query di sviluppo e test. È possibile utilizzare *Operation builder* per visualizzare, esplorare ed eseguire query sui set di dati in tempo reale. È possibile anche utilizzare l'Operation builder strutturato per creare ed eseguire operazioni di data plane. Supporta le espressioni si proiezione e di condizione e consente di generare codice di esempio in più lingue. Per ulteriori informazioni, consulta [Esplorazione di set di dati e creazione di operazioni con NoSQL Workbench](workbench.querybuilder.md).

## Intervalli di indirizzi IP
<a name="Using.IPRanges"></a>

Amazon Web Services (AWS) pubblica i propri intervalli di indirizzi IP correnti in formato JSON. Per vedere gli intervalli correnti, scarica [ip-ranges.json](https://ip-ranges.amazonaws.com/ip-ranges.json). Per ulteriori informazioni, consulta [Intervalli di indirizzi IP di AWS](https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html) nella Riferimenti generali di AWS.

Per trovare gli intervalli di indirizzi IP che puoi usare per [accedere alle tabelle e agli indici di DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Operations_Amazon_DynamoDB.html), cerca nel file ip-ranges.json la seguente stringa: `"service": "DYNAMODB"`.

**Nota**  
Gli intervalli di indirizzi IP non si applicano a DynamoDB Streams o DynamoDB Accelerator (DAX). 

## Endpoint dual-stack per Internet Protocol versione 6 () IPv6
<a name="dual-stackipv4-6"></a>

DynamoDB offre endpoint dual-stack compatibili con entrambi e. IPv4 IPv6 Le convenzioni di denominazione degli endpoint sono:
+ `dynamodb.<region>.api.aws`
+ `<account-id>.ddb.<region>.api.aws`
+ `streams-dynamodb.<region>.api.aws`
+ `dax.<region>.api.aws`
+ `dynamodb-fips.<region>.api.aws`

*Per un elenco completo degli endpoint DynamoDB e della disponibilità regionale, consulta l'argomento Endpoint e [quote di Amazon DynamoDB nella guida di riferimento generale](https://docs.aws.amazon.com/general/latest/gr/ddb.html).AWS *

*Per ulteriori informazioni sulla configurazione della AWS CLI per l'utilizzo di endpoint dual-stack, consulta la sezione [Impostare l'uso degli endpoint dual-stack per tutti i servizi nella guida all'interfaccia a riga di comando](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-endpoints.html#endpoints-dual-stack). AWS AWS *

[https://docs.aws.amazon.com/sdkref/latest/guide/feature-endpoints.html](https://docs.aws.amazon.com/sdkref/latest/guide/feature-endpoints.html)

Prima di utilizzare DynamoDB IPv6 con, è necessario aggiornare il ruolo utente IAM o le policy basate sulle risorse utilizzate per il filtraggio degli indirizzi IP per includere gli intervalli di indirizzi. IPv6 Le politiche di filtraggio degli indirizzi IP che non tengono conto dell'indirizzo possono causare problemi di IPv6 accesso. Per ulteriori informazioni, vedere la sezione [Operatori delle condizioni dell'indirizzo IP](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_IPAddress) nella *guida AWS Identity and Access Management*.

## Prerequisiti
<a name="GettingStarted.SettingUp.DynamoWebService"></a>

Prima di iniziare con il tutorial per Amazon DynamoDB, consulta i modi in cui è possibile accedere a DynamoDB in [Accesso a DynamoDB](AccessingDynamoDB.md). Quindi, configura DynamoDB tramite il servizio web o la versione scaricata in locale in [Configurazione di DynamoDB](SettingUp.md). Dopodiché, continua con [Fase 1: creare una tabella DynamoDB](getting-started-step-1.md).

**Nota**  
Se prevedi di interagire con DynamoDB solo tramite Console di gestione AWS, non hai bisogno AWS di una chiave di accesso. Completa la procedura descritta nella [sezione Registrazione](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html#SettingUp.DynamoWebService.SignUpForAWS) a AWS, quindi continua con. [Fase 1: creare una tabella DynamoDB](getting-started-step-1.md)
Se non vuoi sottoscrivere un account per un piano gratuito, puoi configurare la [versione locale di DynamoDB (versione scaricabile)](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html). Poi prosegui con [Fase 1: creare una tabella DynamoDB](getting-started-step-1.md). 
Esistono differenze quando si lavora con i comandi CLI nei terminali su Linux e Windows. La seguente guida presenta i comandi formattati per i terminali Linux (incluso macOS) e i comandi formattati per Windows CMD. Scegli il comando più adatto all'applicazione terminale che intendi usare. 

# Configurazione di DynamoDB
<a name="SettingUp"></a>

 Oltre al servizio web Amazon DynamoDB AWS , fornisce una versione scaricabile di DynamoDB che puoi eseguire sul tuo computer. La versione scaricabile è utile per sviluppare e testare il codice. La versione scaricabile consente di scrivere e testare applicazioni in locale, senza effettuare l'accesso al servizio Web DynamoDB. 

 Gli argomenti contenuti in questa sezione descrivono come configurare DynamoDB (versione scaricabile) e il servizio Web DynamoDB. 

**Topics**
+ [Configurazione di DynamoDB (servizio Web)](SettingUp.DynamoWebService.md)
+ [Configurazione di DynamoDB locale (versione scaricabile)](DynamoDBLocal.md)

# Configurazione di DynamoDB (servizio Web)
<a name="SettingUp.DynamoWebService"></a>

 Per utilizzare il servizio Web Amazon DynamoDB: 

1.  [Registrazione per AWS](#SettingUp.DynamoWebService.SignUpForAWS) 

1.  [Ottieni una chiave di AWS accesso](#SettingUp.DynamoWebService.GetCredentials) (utilizzata per accedere a DynamoDB a livello di codice). 
**Nota**  
 Se prevedi di interagire con DynamoDB solo tramite Console di gestione AWS, non hai bisogno di AWS una chiave di accesso e puoi passare direttamente a. [Utilizzo della console](AccessingDynamoDB.md#ConsoleDynamoDB) 

1.  [Configura le credenziali](#SettingUp.DynamoWebService.ConfigureCredentials) (utilizzata per accedere a DynamoDB in modo programmatico). 

## Iscrizione a AWS
<a name="SettingUp.DynamoWebService.SignUpForAWS"></a>

 Per utilizzare il servizio DynamoDB, è necessario disporre di un account. AWS Se non disponi di un account, ti verrà chiesto di crearne uno durante la registrazione. Non ti viene addebitato alcun costo per AWS i servizi a cui ti iscrivi a meno che non li utilizzi. 

**Per iscriverti a AWS**

1. Apri la [https://portal.aws.amazon.com/billing/registrazione.](https://portal.aws.amazon.com/billing/signup)

1. Segui le istruzioni online.

   Nel corso della procedura di registrazione riceverai una telefonata o un messaggio di testo e ti verrà chiesto di inserire un codice di verifica attraverso la tastiera del telefono.

   Quando ti iscrivi a un Account AWS, *Utente root dell'account AWS*viene creato un. L’utente root dispone dell’accesso a tutte le risorse e tutti i Servizi AWS nell’account. Come best practice di sicurezza, assegna l’accesso amministrativo a un utente e utilizza solo l’utente root per eseguire [attività che richiedono l’accesso di un utente root](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks).

## Concessione dell'accesso programmatico
<a name="SettingUp.DynamoWebService.GetCredentials"></a>

 Prima di poter accedere a DynamoDB a livello di codice o tramite AWS CLI(), è necessario disporre AWS Command Line Interface dell'accesso programmatico. Non è necessario un accesso programmatico se si intende utilizzare solo la console DynamoDB. 

Gli utenti hanno bisogno dell'accesso programmatico se vogliono interagire con l'esterno di. AWS Console di gestione AWS Il modo per concedere l'accesso programmatico dipende dal tipo di utente che accede. AWS

Per fornire agli utenti l’accesso programmatico, scegli una delle seguenti opzioni.


****  

| Quale utente necessita dell’accesso programmatico? | Per | Come | 
| --- | --- | --- | 
| IAM | (Consigliato) Utilizza le credenziali della console come credenziali temporanee per firmare le richieste programmatiche a,, o. AWS CLI AWS SDKs AWS APIs |  Segui le istruzioni per l’interfaccia che desideri utilizzare. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 
|  Identità della forza lavoro (Utenti gestiti nel centro identità IAM)  | Utilizza credenziali temporanee per firmare le richieste programmatiche a AWS CLI, AWS SDKs, o. AWS APIs |  Segui le istruzioni per l’interfaccia che desideri utilizzare. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 
| IAM | Utilizza credenziali temporanee per firmare le richieste programmatiche a AWS CLI, AWS SDKs, o. AWS APIs | Seguendo le istruzioni riportate in [Utilizzo delle credenziali temporanee con le AWS risorse nella Guida per](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) l'utente IAM. | 
| IAM | (Non consigliato)Utilizza credenziali a lungo termine per firmare richieste programmatiche a AWS CLI,, AWS SDKs o. AWS APIs |  Segui le istruzioni per l’interfaccia che desideri utilizzare. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 

## Configurazione delle credenziali
<a name="SettingUp.DynamoWebService.ConfigureCredentials"></a>

 Prima di poter accedere a DynamoDB a livello di codice o tramite, è necessario configurare AWS CLI le credenziali per abilitare l'autorizzazione per le applicazioni. 

 Esistono vari modi per eseguire questa operazione. Ad esempio, puoi creare manualmente il file delle credenziali per archiviare l'ID chiave di accesso e la chiave di accesso segreta. È inoltre possibile utilizzare il AWS CLI comando per creare automaticamente il file`aws configure`. In alternativa, puoi utilizzare le variabili di ambiente. Per ulteriori informazioni sulla configurazione delle credenziali, consulta la guida per sviluppatori SDK specifica per la programmazione. AWS 

 Per installare e configurare il, consulta. AWS CLI[Utilizzando il AWS CLI](AccessingDynamoDB.md#Tools.CLI) 

## Integrazione con altri servizi DynamoDB
<a name="w2aab9c17b9c13"></a>

Puoi integrare DynamoDB con molti altri servizi. AWS Per ulteriori informazioni, consulta gli argomenti seguenti: 
+ [Utilizzo di DynamoDB con altri servizi AWS](OtherServices.md)
+ [CloudFormation per DynamoDB](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html)
+ [Utilizzo di AWS Backup con Dynamo DB](backuprestore_HowItWorksAWS.md)
+ [AWS Identity and Access Management (IAM) e DynamoDB](identity-and-access-mgmt.md)
+ [Utilizzo di AWS Lambda con Amazon DynamoDB](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html)

# Configurazione di DynamoDB locale (versione scaricabile)
<a name="DynamoDBLocal"></a>

 Con la versione scaricabile di Amazon DynamoDB è possibile sviluppare e testare applicazioni senza effettuare l'accesso al servizio Web DynamoDB. Il database, invece, è autonomo sul tuo computer. Una volta pronti a implementare l'applicazione in produzione, rimuovere l'endpoint locale nel codice e puntare al servizio Web DynamoDB. 

 Questa versione locale ti aiuta a risparmiare sui costi di throughput, storage dei dati e trasferimento dei dati. Inoltre, lo sviluppo dell'applicazione non richiede una connessione a Internet. 

 La versione locale di DynamoDB è disponibile solo per il [download](DynamoDBLocal.DownloadingAndRunning.md#DynamoDBLocal.DownloadingAndRunning.title) (richiede JRE), come una [dipendenza Apache Maven](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html#apache-maven) o come [immagine Docker](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html#docker). 

 Se si preferisce utilizzare il servizio Web Amazon DynamoDB, consulta [Configurazione di DynamoDB (servizio Web)](SettingUp.DynamoWebService.md). 

**Topics**
+ [Distribuzione di DynamoDB in locale sul computer](DynamoDBLocal.DownloadingAndRunning.md)
+ [Note per l'utilizzo locale di DynamoDB](DynamoDBLocal.UsageNotes.md)
+ [Cronologia delle versioni di DynamoDB Local](DynamoDBLocalHistory.md)
+ [Telemetria in DynamoDB locale](DynamoDBLocalTelemetry.md)

# Distribuzione di DynamoDB in locale sul computer
<a name="DynamoDBLocal.DownloadingAndRunning"></a>

**Nota**  
DynamoDB locale è disponibile in tre versioni: v3.x (Corrente), v2.x (Legacy) e v1.x (Obsoleta).
Si consiglia DynamoDB v3.x per test e sviluppo in locale.
La migrazione della versione di DynamoDB locale da V2.x a V3.x richiede l’aggiornamento delle istruzioni di importazione da `com.amazonaws.services.dynamodbv2` a `software.amazon.dynamodb` e l’aggiornamento delle dipendenze Maven per gli utenti Maven.
Se stai migrando un’applicazione che utilizza l’SDK per Java v1.x all’SDK per Java 2.x, segui la procedura per [SDK AWS per Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/migration.html).

## Download di DynamoDB locale
<a name="DynamoDBLocal.DownloadingAndRunning.V2"></a>

Completare la procedura riportata di seguito per configurare ed eseguire DynamoDB sul proprio computer.

**Come configurare DynamoDB sul computer**

1. Scarica DynamoDB locale gratuitamente da una delle seguenti posizioni.  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html)
**Importante**  
 Per eseguire DynamoDB v2.6.0 sul computer è necessaria la versione 17.x o successiva dell’ambiente di runtime Java (JRE). L'applicazione non verrà eseguita nelle versioni di JRE precedenti.

1.  Dopo aver scaricato l'archivio, estrai i contenuti e copia la directory estratta in una ubicazione a scelta. 

1.  Per avviare DynamoDB sul computer, aprire una finestra del prompt dei comandi, spostarsi nella directory in cui è stato estratto `DynamoDBLocal.jar`, quindi immettere il comando seguente. 

   ```
   java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb
   ```
**Nota**  
 Se usi Windows PowerShell, assicurati di includere il nome del parametro o l'intero nome e valore in questo modo:   
 ` java -D"java.library.path=./DynamoDBLocal_lib" -jar DynamoDBLocal.jar `   
 DynamoDB esegue le richieste in arrivo fino al suo arresto. Per arrestare DynamoDB, digitare Ctrl\$1C al prompt dei comandi.   
 DynamoDB utilizza la porta 8000 per impostazione predefinita. Se la porta 8000 non è disponibile, il comando genera un'eccezione. Per un elenco completo delle opzioni di runtime di DynamoDB, incluso `-port`, immettere il comando seguente.   
 ` java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -help ` 

1. Prima di poter accedere a AWS Command Line Interface in modo programmatico o tramite (AWS CLI), è necessario configurare le credenziali per abilitare l'autorizzazione per le applicazioni. Perché possa funzionare, la versione scaricabile di DynamoDB richiede le credenziali, come mostrato nell'esempio seguente. 

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

    È possibile utilizzare il comando `aws configure` di AWS CLI per impostare le credenziali. Per ulteriori informazioni, consulta [Utilizzando il AWS CLI](AccessingDynamoDB.md#Tools.CLI). 

1.  Inizia a scrivere le applicazioni. Per accedere a DynamoDB in esecuzione localmente con, utilizzare AWS CLI il parametro. `--endpoint-url ` Ad esempio, per elencare le tabelle DynamoDB utilizzare il seguente comando: 

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

## Esecuzione di DynamoDB locale come immagine Docker
<a name="DynamoDBLocal.DownloadingAndRunning.Docker"></a>

 La versione scaricabile di Amazon DynamoDB è disponibile come parte dell'immagine Docker. Per ulteriori informazioni, consulta [dynamodb-local](https://hub.docker.com/r/amazon/dynamodb-local). Per visualizzare la versione corrente di DynamoDB locale, immetti il seguente comando:

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

 Per un esempio di utilizzo di DynamoDB local come parte di un'applicazione REST basata su AWS SAM(), consulta Applicazione [SAM DynamoDB](https://github.com/aws-samples/aws-sam-java-rest) per AWS Serverless Application Model la gestione degli ordini. Questa applicazione di esempio mostra come utilizzare DynamoDB locale per i test. 

 Se desideri eseguire un'applicazione multi-container che utilizza anche il container DynamoDB Local, utilizza Docker Compose per definire ed eseguire tutti i servizi nell'applicazione, incluso DynamoDB Local. 

**Per installare ed eseguire DynamoDB in locale con Docker Compose:**

1.  Scarica e installa [Docker Desktop](https://www.docker.com/products/docker-desktop). 

1.  Copiare il codice seguente in un file e salvarlo con nome `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
   ```

    Se vuoi che l'applicazione e DynamoDB locale si trovino in container separati, utilizza il file yaml seguente. 

   ```
   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
   ```

    Lo script docker-compose.yml crea un container `app-node` e un container `dynamodb-local`. Lo script esegue un comando nel container `app-node` che utilizza la AWS CLI per connettersi al container `dynamodb-local` e descrive i limiti di account e tabelle. 

    Per utilizzarlo con la propria immagine dell'applicazione, sostituire il valore `image` nell'esempio seguente con quello dell'applicazione: 

   ```
   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'
   ```
**Nota**  
 Gli script YAML richiedono di specificare una chiave di AWS accesso e una chiave AWS segreta, ma non devono essere AWS chiavi valide per accedere a DynamoDB locale. 

1.  Emettere il seguente comando dalla riga di comando: 

   ```
   docker-compose up
   ```

## Esecuzione di DynamoDB locale come dipendenza Apache Maven
<a name="DynamoDBLocal.DownloadingAndRunning.Maven.v2"></a>

**Nota**  
Se stai migrando un’applicazione che utilizza l’SDK per Java v1.x all’SDK per Java 2.x, segui la procedura per [SDK AWS per Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/migration.html).

 Completare la seguente procedura per utilizzare Amazon DynamoDB nell'applicazione come dipendenza. 

**Come distribuire DynamoDB come repository Apache Maven**

1.  Scarica e installa Apache Maven. Per ulteriori informazioni, consulta le pagine relative al [download di Apache Maven](https://maven.apache.org/download.cgi) e all'[installazione di Apache Maven](https://maven.apache.org/install.html). 

1.  Aggiungi il repository Maven DynamoDB al file POM (Project Object Model) dell'applicazione: 

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

    Modello di esempio da utilizzare con Spring Boot 3 Spring Framework 6: and/or 

   ```
   <?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>
   ```
**Nota**  
 Puoi anche utilizzare l'URL di [Maven Central Repository](https://mvnrepository.com/artifact/com.amazonaws/DynamoDBLocal?repo=dynamodb-local-release). 

## Esegui DynamoDB in locale in AWS CloudShell
<a name="DynamoDBLocal.DynamoDB.Local.CloudShell"></a>

AWS CloudShell è una shell preautenticata basata su browser che puoi avviare direttamente da. Console di gestione AWSÈ possibile accedere AWS CloudShell da diversi modi Console di gestione AWS . Per ulteriori informazioni, consulta [Guida introduttiva AWS CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/getting-started.html).

Segui questi passaggi per eseguire DynamoDB localmente ovunque AWS CloudShell nel. Console di gestione AWS

**Per eseguire DynamoDB in locale nel AWS CloudShell Console di gestione AWS**

1. Avvia AWS CloudShell dall'interfaccia della console, scegli una shell disponibile Regione AWS e passa alla shell preferita, come Bash o la shell PowerShell Z.

1. Per sceglierne una Regione AWS, vai al menu **Seleziona una regione** e seleziona una [supportata Regione AWS](https://docs.aws.amazon.com/cloudshell/latest/userguide/supported-aws-regions.html). (Le Regioni disponibili sono evidenziate.)

1. Da Console di gestione AWS, avvia AWS CloudShell scegliendo una delle seguenti opzioni:

   1. Nella barra di navigazione seleziona l’icona **AWS CloudShell**.

   1. Nella casella **Cerca**, inserisci la parola CloudShell, quindi scegli **CloudShell**.

   1. Nel widget **Visitato di recente**, scegli **CloudShell**.

   1. Dalla barra degli strumenti della console, scegli **CloudShell**.

1. Per eseguire DynamoDB AWS CloudShell in locale puoi usare l'alias. `dynamodb-local` È possibile specificare opzioni aggiuntive della riga di comando per modificare le impostazioni di DynamoDB locale. Consulta [Note per l'utilizzo locale di DynamoDB](DynamoDBLocal.UsageNotes.md) per conoscere le opzioni disponibili.
**Nota**  
Per eseguire DynamoDB in locale in background, esegui DynamoDB local utilizzando:. AWS CloudShell `dynamodb-local &`

1. Per accedere a DynamoDB AWS CloudShell in esecuzione localmente con, utilizzare AWS CLI il parametro. `--endpoint-url` Ad esempio, per elencare le tabelle DynamoDB utilizza il seguente comando:

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

Per un esempio di progetto che mostra diversi approcci per configurare e utilizzare DynamoDB locale, tra cui il download di file JAR, l’esecuzione come immagine Docker e l’utilizzo come dipendenza Maven, consulta [DynamoDB Local Sample Java Project.](https://github.com/awslabs/amazon-dynamodb-local-samples/tree/main)

# Note per l'utilizzo locale di DynamoDB
<a name="DynamoDBLocal.UsageNotes"></a>

 A eccezione dell'endpoint, le applicazioni eseguite con la versione scaricabile di Amazon DynamoDB dovrebbero funzionare anche con il servizio Web DynamoDB. Tuttavia, quando si utilizza DynamoDB in locale, è necessario tenere presente quanto riportato di seguito: 
+  *Se si utilizza l'`-sharedDb`opzione, DynamoDB crea un singolo file di database denominato .db. shared-local-instance* Tutti i programmi che si connettono a DynamoDB hanno accesso a questo file. Se elimini il file, tutti i dati in esso archiviati andranno persi. 
+  Se si omette`-sharedDb`, il file di database viene denominato *myaccesskeyid\$1region.db*, con l'ID della chiave di AWS accesso e la AWS regione così come appaiono nella configurazione dell'applicazione. Se elimini il file, tutti i dati in esso archiviati andranno persi. 
+  Se si utilizza l'opzione `-inMemory`, DynamoDB non scrive alcun file di database. Tutti i dati verranno invece scritti in memoria e non verranno salvati all'arresto di DynamoDB. 
+  Se si utilizza l’opzione `-inMemory`, è richiesta anche l'opzione `-sharedDb`. 
+  Se si utilizza l'opzione `-optimizeDbBeforeStartup`, è necessario specificare anche il parametro `-dbPath`, in modo che DynamoDB sia in grado di individuare il file di database. 
+  AWS SDKs Per DynamoDB è necessario che la configurazione dell'applicazione specifichi un valore della chiave di accesso e AWS un valore Region. A meno che non stia utilizzando l'opzione `-sharedDb` o `-inMemory`, DynamoDB usa questi valori per denominare il file di database locale. Questi valori non devono essere necessariamente validi per essere eseguiti AWS localmente. Tuttavia, potresti trovare utile utilizzare valori validi in modo da poter eseguire il codice nel cloud successivamente, modificando solo l'endpoint in uso. 
+  La versione locale di DynamoDB restituisce sempre un valore null per `billingModeSummary.` 
+  DynamoDB local `AWS_ACCESS_KEY_ID` può contenere solo lettere (A–Z, a–z) e numeri (0-9). 
+ DynamoDB local non [Point-in-time supporta il ripristino](Point-in-time-recovery.md) (PITR).

**Topics**
+ [Opzioni della riga di comando](#DynamoDBLocal.CommandLineOptions)
+ [Impostazione dell'endpoint locale](#DynamoDBLocal.Endpoint)
+ [Differenze tra DynamoDB scaricabile e il servizio Web DynamoDB](#DynamoDBLocal.Differences)

## Opzioni della riga di comando
<a name="DynamoDBLocal.CommandLineOptions"></a>

 Con la versione scaricabile di DynamoDB è possibile utilizzare le opzioni della riga di comando seguenti: 
+  `-cors``value`— Abilita il supporto per la condivisione di risorse tra origini diverse (CORS) per. JavaScript È necessario fornire un elenco di domini specifici "consentiti" separati da virgole. L'impostazione predefinita di `-cors` è un asterisco (\$1), che permette l'accesso pubblico. 
+  `-dbPath` `value`: la directory in cui DynamoDB scrive il file di database. Se non specifichi questa opzione, il file verrà scritto nella directory corrente. Non puoi specificare sia `-dbPath` che `-inMemory` contemporaneamente. 
+  `-delayTransientStatuses`: fa sì che DynamoDB introduca ritardi per determinate operazioni. DynamoDB (versione scaricabile) può eseguire alcune attività quasi istantaneamente, come le operazioni su tabelle e indici. create/update/delete Tuttavia, il servizio DynamoDB richiede più tempo per queste attività. L'impostazione di questo parametro consente a DynamoDB in esecuzione sul computer di simulare più da vicino il comportamento del servizio Web DynamoDB. Attualmente, questo parametro causa ritardi solo per i Global Secondary Indexes in stato *CREATING* o *DELETING*. 
+  `-help`: stampa un riepilogo di utilizzo e le opzioni. 
+  `-inMemory`: DynamoDB viene eseguito in memoria invece di utilizzare un file di database. Quando si arresta DynamoDB, i dati non verranno salvati. Non puoi specificare sia `-dbPath` che `-inMemory` contemporaneamente. 
+  `-optimizeDbBeforeStartup`: ottimizza le tabelle di database sottostanti prima di avviare DynamoDB sul computer. Inoltre, quando utilizzi questo parametro, è necessario specificare `-dbPath`. 
+  `-port` `value`: il numero di porta utilizzato da DynamoDB per comunicare con l'applicazione. Se non viene specificata questa opzione, la porta predefinita è `8000`. 
**Nota**  
 DynamoDB utilizza la porta 8000 per impostazione predefinita. Se la porta 8000 non è disponibile, il comando genera un'eccezione. Puoi utilizzare l'opzione `-port` per specificare un numero di porta diverso. Per un elenco completo delle opzioni di runtime di DynamoDB, tra cui `-port`, digitare il comando seguente:   
 `java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -help` 
+  `-sharedDb`: se si specifica `-sharedDb`, DynamoDB utilizza un singolo file di database anziché file separati per ogni credenziale e regione. 
+  `-disableTelemetry`: quando specificato, DynamoDB locale non invierà alcuna telemetria. 
+ `-version`: stampa la versione di DynamoDB locale.

## Impostazione dell'endpoint locale
<a name="DynamoDBLocal.Endpoint"></a>

 Per impostazione predefinita, gli strumenti AWS SDKs and utilizzano gli endpoint per il servizio Web Amazon DynamoDB. Per utilizzare gli strumenti SDKs e con la versione scaricabile di DynamoDB, è necessario specificare l'endpoint locale: 

 `http://localhost:8000` 

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

 Puoi usare il AWS Command Line Interface (AWS CLI) per interagire con DynamoDB scaricabile. 

 Per accedere a DynamoDB eseguito in locale, utilizza il parametro `--endpoint-url`. Di seguito è riportato un esempio di utilizzo di AWS CLI per elencare le tabelle in DynamoDB sul computer. 

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

**Nota**  
 Non AWS CLI possono utilizzare la versione scaricabile di DynamoDB come endpoint predefinito. Pertanto, è necessario specificare con ogni comando. `--endpoint-url` AWS CLI 

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

 Il modo in cui viene specificato un endpoint dipende dal linguaggio di programmazione e dall'SDK AWS in uso. Nelle seguenti sezioni viene descritto come procedere: 
+  [Java: impostazione della AWS regione e dell'endpoint](CodeSamples.Java.md#CodeSamples.Java.RegionAndEndpoint)(DynamoDB local supporta l'SDK AWS per Java V1 e V2) 
+ CodeSamples.Java. RegionAndEndpoint [.NET: impostazione della AWS regione e dell'endpoint](CodeSamples.DotNet.md#CodeSamples.DotNet.RegionAndEndpoint) 

## Differenze tra DynamoDB scaricabile e il servizio Web DynamoDB
<a name="DynamoDBLocal.Differences"></a>

 La versione scaricabile di DynamoDB è destinata solo a scopi di sviluppo e test. Per contro, il servizio Web DynamoDB è un servizio gestito con caratteristiche di scalabilità, disponibilità e durabilità che lo rendono ideale per l'uso in produzione. 

 Le differenze tra la versione scaricabile di DynamoDB e il servizio Web sono le seguenti: 
+ Regioni AWS e distinct non Account AWS sono supportati a livello di client. 
+  Le impostazioni di velocità effettiva assegnata vengono ignorate nella versione scaricabile di DynamoDB, sebbene siano richieste dall'operazione `CreateTable`. In `CreateTable`, puoi specificare i numeri che preferisci di throughput di lettura e scrittura assegnato, sebbene questi numeri non vengano utilizzati. Puoi chiamare `UpdateTable` tutte le volte al giorno che desideri. Tuttavia, le modifiche ai valori di throughput assegnato vengono ignorate. 
+  Le operazioni `Scan` vengono eseguite in sequenza. Le scansioni in parallelo non sono supportate. I parametri `Segment` e `TotalSegments` dell'operazione `Scan` vengono ignorati. 
+  La velocità delle operazioni di lettura e scrittura sui dati della tabella è limitata solo dalla velocità del computer. Le operazioni `CreateTable`, `UpdateTable` e `DeleteTable` hanno luogo immediatamente e lo stato della tabella è sempre ACTIVE. Le operazioni `UpdateTable` che modificano solo le impostazioni di throughput di cui è stato effettuato il provisioning sulle tabelle o sui Global Secondary Indexes si verificano immediatamente. Se un'operazione `UpdateTable` crea o elimina alcuni indici secondari globali, tali indici passeranno attraverso gli stati normali (come CREATING e DELETING, rispettivamente) prima di raggiungere lo stato ACTIVE. La tabella rimane in stato ACTIVE (Attivo) durante questa fase. 
+  Le operazioni di lettura hanno consistenza finale. Tuttavia, a causa della velocità dell’esecuzione di DynamoDB locale sul computer, la maggior parte delle letture risulta a elevata consistenza. 
+  I parametri di raccolta di item e le dimensioni di raccolta di item non vengono monitorati. Nelle risposte delle operazioni, vengono restituiti valori null anziché parametri di raccolta di item. 
+  In DynamoDB, il limite di dati restituiti per ogni set di risultati è 1 MB. Sia il servizio Web DynamoDB che la versione scaricabile impongono questo limite. Tuttavia, durante l'esecuzione di una query su un indice, il servizio DynamoDB calcola solo la dimensione della chiave e degli attributi proiettati. Per contro, la versione scaricabile di DynamoDB calcola la dimensione dell'intero elemento. 
+  Se si utilizzano i flussi DynamoDB, la velocità di creazione degli shard potrebbe variare. Nel servizio Web DynamoDB, il comportamento della creazione di shard è in parte influenzato dall'attività di partizionamento della tabella. Quando si esegue DynamoDB in locale, non si verifica un partizionamento di tabella. Nei due casi, gli shard sono temporanei, per cui l'applicazione non deve dipendere dal comportamento degli shard. 
+  `TransactionConflictExceptions`non vengono generati da DynamoDB scaricabile per transazioni. APIs Ti consigliamo di utilizzare un framework fittizio Java per simulare `TransactionConflictExceptions` nel gestore DynamoDB per testare la modalità di risposta dell'applicazione alle transazioni in conflitto. 
+  Nel servizio web DynamoDB, indipendentemente dal fatto che l'accesso avvenga tramite la console o tramite, i nomi delle tabelle fanno distinzione AWS CLI tra maiuscole e minuscole. Una tabella denominata `Authors` e una denominata `authors` possono esistere entrambe come tabelle separate. Nella versione scaricabile, i nomi di tabella rispettano la distinzione tra maiuscole e minuscole e il tentativo di creare queste due tabelle genera un errore. 
+ L’assegnazione di tag non è supportata nella versione scaricabile di DynamoDB.
+ [La versione scaricabile di DynamoDB ignora il parametro Limit in. [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)

# Cronologia delle versioni di DynamoDB Local
<a name="DynamoDBLocalHistory"></a>

Nella tabella seguente sono descritte le modifiche importanti apportate a ogni nuova versione di *DynamoDB local*.


****  

| Versione | Modifica | Descrizione | Data | 
| --- | --- | --- | --- | 
| 3.3.0 |  Aggiungere il supporto per chiavi multiattributo per gli indici secondari globali  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  19 gennaio 2026  | 
| 3.2.0 |  Risolti i problemi di compatibilità con più versioni di Kotlin  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  09 gennaio 2026  | 
| 3.1.0 |  Miglioramento delle prestazioni per le query PartiQL, inclusa la dipendenza Joda-time  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  14 settembre 2025  | 
| 3.0.0 |  Migrazione da AWS SDK Java V1 a V2  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  17 luglio 2025  | 
| 2.6.0 |  Supporta la tabella ARN come nome della tabella in DynamoDB APIs Correzione delle prestazioni e aggiornamenti di sicurezza  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  13 marzo 2025  | 
| 2.5.4 |  Aggiornamento a dipendenze Jetty  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  12 dicembre 2024  | 
| 2.5.3 |  Aggiornamento delle dipendenze Jackson alla versione 2.17.x in Log4j Core (Risolve CVE-2022-1471)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  6 novembre 2024  | 
| 2.5.2 | Correzione di bug per il flusso di lavoro di aggiornamento delle tabelle | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  | 20 giugno 2024 | 
| 2.5.1 | Patch per i bug introdotti nella funzionalità OndemandThroughPut  | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html) | 5 giugno 2024 | 
| 2.5.0 |  Support per un throughput massimo configurabile per tabelle on demand, `ReturnValuesOnConditionCheckFailure`, `BatchExecuteStatement` e `ExecuteTransactionRequest`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  28 maggio 2024  | 
| 2.4.0 |  Supporto per `ReturnValuesOnConditionCheckFailure` – Modalità con embedding  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  17 aprile 2024  | 
| 2.3.0 |  Aggiornamento di Jetty e JDK  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  14 marzo 2024  | 
| 2.2.0 |  Aggiunta del supporto per la protezione dall’eliminazione delle tabelle e per il parametro `ReturnValuesOnConditionCheckFailure`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  14 dicembre 2023  | 
| 2.1.0 |  Support per progetti SQLLite Native Libraries for Maven e aggiunta di telemetria  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  23 ottobre 2023  | 
| 2.0.0 |  Migrazione da javax a jakarta namespace e Support JDK11   |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  5 luglio 2023  | 
| 1.25.1 |  Aggiornamento delle dipendenze Jackson alla versione 2.17.x in Log4j Core (Risolve CVE-2022-1471)  |  Aggiornamento delle dipendenze Jackson alla versione 2.17.x in Log4j Core (Risolve CVE-2022-1471) per risolvere una vulnerabilità di sicurezza critica nella libreria SnakeYAML, che è una dipendenza transitiva  |  6 novembre 2024  | 
| 1.25.0 |  Aggiunta del supporto per la protezione dall’eliminazione delle tabelle e per il parametro `ReturnValuesOnConditionCheckFailure`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  18 dicembre 2023  | 
| 1.24.0 |  Support per progetti SQLLite Native Libraries for Maven e aggiunta di telemetria  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  23 ottobre 2023  | 
| 1.23.0 |  Gestione dell'accesso non valido e chiave segreta all'avvio del server  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  28 giugno 2023  | 
| 1.22.0 |  Supporto di Limit Operation per PartiQL  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  8 giugno 2023  | 
| 1.21.0 |  Supporto per 100 azioni per transazione  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  26 gennaio 2023  | 
| 1.20.0 |  Aggiunto il supporto per M1 Mac  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  12 settembre 2022  | 
| 1.19.0 |  Aggiornato il parser PartiQL  |  Aggiornato il parser PartiQL e altre librerie correlate  |  27 luglio 2022  | 
| 1.18.0 | Aggiornati log4j-core e Jackson-core | Aggiornato log4j-core a 2.17.1 e Jackson-core 2.10.x a 2.12.0 | 10 gennaio 2022 | 
| 1.17.2 | Aggiornato log4j-core | Aggiornata dipendenza log4j-core alla versione 2.16 | 16 gennaio 2021 | 
| 1.17.1 | Aggiornato log4j-core | Aggiornata dipendenza log4j-core per correggere l'exploit zero-day per impedire l'esecuzione di codice in modalità remota - Log4Shel | 10 gennaio 2021 | 
| 1.17.0 | Javascript Web Shell obsoleta |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  | 8 gennaio 2021 | 

# Telemetria in DynamoDB locale
<a name="DynamoDBLocalTelemetry"></a>

 In AWS, sviluppiamo e lanciamo servizi basati su ciò che apprendiamo dalle interazioni con i clienti e utilizziamo il feedback dei clienti per iterare sui nostri prodotti. La telemetria offre informazioni aggiuntive che ci consentono di comprendere meglio le necessità dei clienti, diagnosticare i problemi e fornire funzionalità per migliorare l'esperienza cliente. 

 DynamoDB locale raccoglie dati di telemetria, come metriche di utilizzo generiche, informazioni sui sistemi e sull'ambiente ed errori. Per informazioni dettagliate sui tipi di telemetria raccolti, consulta. [Tipo di informazioni da raccogliere](#DynamoDBLocalTelemetry.TypesOfInformationCollected) 

 DynamoDB locale non raccoglie informazioni personali, come nomi utente o indirizzi e-mail. Inoltre, non estrae informazioni sensibili a livello di progetto. 

 In qualità di cliente, puoi controllare se la telemetria è attivata e puoi modificare le impostazioni in qualsiasi momento. Se la telemetria resta attiva, DynamoDB locale invia i dati di telemetria in background senza richiedere alcuna interazione aggiuntiva al cliente. 

## Disattivazione della telemetria utilizzando le opzioni della riga di comando
<a name="DynamoDBLocalTelemetry.cli"></a>

 Puoi disattivare la telemetria utilizzando le opzioni della riga di comando all'avvio di DynamoDB locale utilizzando l'opzione `-disableTelemetry`. Per ulteriori informazioni, consulta [Opzioni della riga di comando](DynamoDBLocal.UsageNotes.md#DynamoDBLocal.CommandLineOptions).

## Disattivazione della telemetria per una singola sessione
<a name="DynamoDBLocalTelemetry.TurnOffTelemetrySingleSession"></a>

 Nei sistemi operativi macOS e Linux, puoi disattivare la telemetria per una singola sessione. Per disattivare la telemetria per la sessione corrente, esegui il comando seguente per impostare la variabile di ambiente `DDB_LOCAL_TELEMETRY` su `false`. Ripeti il comando per ogni nuovo terminale o sessione. 

```
export DDB_LOCAL_TELEMETRY=0
```

## Disattivazione della telemetria per il tuo profilo in tutte le sessioni
<a name="DynamoDBLocalTelemetry.TurnOffTelemetryForAllSessions"></a>

 Esegui i seguenti comandi per disattivare la telemetria per tutte le sessioni quando esegui DynamoDB locale sul tuo sistema operativo. 

**Per disattivare la telemetria in Linux**

1.  Esegui: 

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

1.  Esegui: 

   ```
   source ~/.profile
   ```

**Per disattivare la telemetria in Linux**

1.  Esegui: 

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

1.  Esegui: 

   ```
   source ~/.profile
   ```

**Per disattivare la telemetria in Linux**

1.  Esegui: 

   ```
   setx DDB_LOCAL_TELEMETRY 0
   ```

1.  Esegui: 

   ```
   refreshenv
   ```

## Disattivazione della telemetria con DynamoDB locale con embedding in progetti Maven
<a name="DynamoDBLocalTelemetry.maven"></a>

 È possibile disattivare la telemetria utilizzando DynamoDB locale con embedding nei progetti Maven. 

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

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

## Tipo di informazioni da raccogliere
<a name="DynamoDBLocalTelemetry.TypesOfInformationCollected"></a>
+  **Informazioni sull'utilizzo**: la telemetria generica, ad esempio il server start/stop e l'API o l'operazione chiamata. 
+  **Informazioni sul sistema e sull'ambiente**: la versione Java, il sistema operativo (Windows, Linux o macOS), l'ambiente in cui viene eseguito DynamoDB locale (ad esempio, JAR indipendente, container Docker o come dipendenza Maven) e i valori hash degli attributi di utilizzo. 

## Ulteriori informazioni
<a name="DynamoDBLocalTelemetry.LearnMore"></a>

 I dati di telemetria raccolti localmente da DynamoDB rispettano le politiche sulla privacy dei dati. AWS Per ulteriori informazioni, consulta gli argomenti seguenti: 
+  [AWS termini del servizio](https://aws.amazon.com/service-terms/) 
+  [Domande frequenti sulla privacy dei dati](https://aws.amazon.com/compliance/data-privacy-faq/) 

# Fase 1: creare una tabella DynamoDB
<a name="getting-started-step-1"></a>

In questa fase, viene creata una tabella `Music` in Amazon DynamoDB. La tabella presenta i seguenti dettagli:
+ Chiave di partizione: `Artist`
+ Chiave di ordinamento: `SongTitle`

Per ulteriori informazioni sulle operazioni delle tabelle, consulta [Utilizzo di tabelle e dati in DynamoDB](WorkingWithTables.md). 

**Nota**  
Prima di iniziare, accertati di aver seguito i passaggi in [Prerequisiti](GettingStartedDynamoDB.md#GettingStarted.SettingUp.DynamoWebService).

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

Per creare una nuova tabella `Music` utilizzando la console DynamoDB:

1. Accedi Console di gestione AWS e apri la console DynamoDB all'indirizzo. [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)

1. Nel riquadro di navigazione a sinistra, selezionare **Tables (Tabelle)**. 

1. Scegliere **Create table (Crea tabella)**.

1. Inserisci i **Dettagli tabella** come segue:

   1. Nel campo **Table name (Nome tabella)** immetti **Music**.

   1. In **Partition key** (Chiave di partizione), inserisci **Artist**.

   1. Per **Chiave di ordinamento**, immetti **SongTitle**.

1. Per **Impostazioni tabella**, mantieni la selezione predefinita di **Impostazioni predefinite**.

1. Per creare la tabella seleziona **Crea tabella**.  
![\[La pagina Crea tabella con i dettagli della tabella compilati.\]](http://docs.aws.amazon.com/it_it/amazondynamodb/latest/developerguide/images/GettingStarted/CreateTableMusic.png)

1. Una volta che la tabella è nello stato `ACTIVE`, si consiglia di abilitare [Backup point-in-time per DynamoDB](Point-in-time-recovery.md) sulla tabella eseguendo la procedura seguente:

   1. Seleziona il nome della tabella per aprirla.

   1. Seleziona **Backup**.

   1. Scegli **Modifica nella sezione** di **Point-in-time ripristino (PITR**).

   1. Nella pagina **Modifica impostazioni point-in-time di ripristino**, scegli **Attiva il point-in-time ripristino**.

   1. Scegli **Save changes** (Salva modifiche).

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

L' AWS CLI esempio seguente crea una nuova `Music` tabella utilizzando`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
```

Utilizzando `create-table` viene restituito il seguente risultato di esempio.

```
{
    "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"
        }
    }
}
}
```

Da notare che il valore del campo `TableStatus` è impostato su `CREATING`.

Per verificare se DynamoDB ha terminato la creazione della tabella `Music`, utilizza il comando `describe-table`. 

**Linux**

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

**Windows CMD**

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

Questo comando restituisce il seguente risultato. Quando DynamoDB termina la creazione della tabella, il valore del campo `TableStatus` è impostato su `ACTIVE`. 

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

Una volta che la tabella è in stato `ACTIVE`, la best practice è abilitare [Backup point-in-time per DynamoDB](Point-in-time-recovery.md) sulla tabella eseguendo il comando seguente:

**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
```

Questo comando restituisce il seguente risultato.

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

**Nota**  
L'attivazione di backup continui con point-in-time ripristino comporta implicazioni in termini di costi. Per ulteriori informazioni sui prezzi, consulta [Prezzi di Amazon DynamoDB](https://aws.amazon.com/dynamodb/pricing).

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

Gli esempi di codice seguenti mostrano come creare una tabella DynamoDB utilizzando un SDK AWS .

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

**SDK per .NET (v4)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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;
        }
    }
```
+  Per i dettagli sull'API, consulta la [CreateTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/CreateTable)sezione *AWS SDK per .NET API Reference*. 

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

**AWS CLI con lo script Bash**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
}
```
Le funzioni di utilità utilizzate in questo esempio.  

```
###############################################################################
# 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
}
```
+  Per i dettagli sull'API, consulta [CreateTable AWS CLI](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)*Command Reference*. 

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

**SDK per C\$1\$1**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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);
}
```
Codice che attende che la tabella diventi attiva.  

```
//! 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;
}
```
+  Per i dettagli sull'API, consulta la [CreateTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/CreateTable)sezione *AWS SDK per C\$1\$1 API Reference*. 

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

**AWS CLI**  
**Esempio 1: come creare una tabella con tag**  
L’esempio `create-table` seguente utilizza gli attributi e lo schema di chiavi specificati per creare una tabella denominata `MusicCollection`. Questa tabella utilizza la velocità effettiva assegnata ed è crittografata a riposo utilizzando la CMK di AWS proprietà predefinita. Il comando applica inoltre un tag alla tabella, con una chiave `Owner` e un valore `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
```
Output:  

```
{
    "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"
    }
}
```
Per ulteriori informazioni, consulta [Operazioni di base per le tabelle](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 2: come creare una tabella in modalità on demand**  
L’esempio seguente crea una tabella denominata `MusicCollection` utilizzando la modalità on demand, anziché la modalità basata su throughput allocato. Ciò risulta utile per le tabelle con carichi di lavoro imprevedibili.  

```
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
```
Output:  

```
{
    "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"
        }
    }
}
```
Per ulteriori informazioni, consulta [Operazioni di base per le tabelle](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 3: come creare una tabella e crittografarla con una chiave gestita dal cliente (CMK).**  
L’esempio seguente crea una tabella denominata `MusicCollection` e la crittografa utilizzando una chiave gestita dal cliente (CMK).  

```
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
```
Output:  

```
{
    "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"
        }
    }
}
```
Per ulteriori informazioni, consulta [Operazioni di base per le tabelle](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 4: come creare una tabella con un indice secondario locale**  
Nell’esempio seguente vengono utilizzati gli attributi e lo schema di chiavi specificati per creare una tabella denominata `MusicCollection` con un indice secondario locale denominato `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\"]
                }
            }
        ]"
```
Output:  

```
{
    "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"
            }
        ]
    }
}
```
Per ulteriori informazioni, consulta [Operazioni di base per le tabelle](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 5: come creare una tabella con un indice secondario globale**  
L’esempio seguente crea una tabella denominata `GameScores` con un indice secondario globale denominato `GameTitleIndex`. La tabella di base ha una chiave di partizione di `UserId` e una chiave di ordinamento di `GameTitle`, permettendo di trovare il miglior punteggio di un singolo utente per un gioco specifico in modo efficiente, mentre il GSI ha una chiave di partizione di `GameTitle` e una chiave di ordinamento di `TopScore`, permettendo di trovare rapidamente il punteggio più alto complessivo per un determinato gioco.  

```
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
                }
            }
        ]"
```
Output:  

```
{
    "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"
            }
        ]
    }
}
```
Per ulteriori informazioni, consulta [Operazioni di base per le tabelle](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 6: come creare una tabella con più indici secondari globali contemporaneamente**  
Nell’esempio seguente viene creata una tabella denominata `GameScores` con due indici secondari globali. Gli schemi GSI vengono passati tramite un file, anziché nella riga di comando.  

```
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
```
Contenuto di `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
        }
    }
]
```
Output:  

```
{
    "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"
            }
        ]
    }
}
```
Per ulteriori informazioni, consulta [Operazioni di base per le tabelle](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 7: come creare una tabella con i flussi abilitati**  
L’esempio seguente crea una tabella denominata `GameScores` con i flussi DynamoDB abilitati. Le immagini vecchie e nuove di ciascun elemento verranno scritte nel flusso.  

```
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
```
Output:  

```
{
    "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"
    }
}
```
Per ulteriori informazioni, consulta [Operazioni di base per le tabelle](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 8: come creare una tabella con il flusso KEYS\$1ONLY abilitato**  
L’esempio seguente crea una tabella denominata `GameScores` con i flussi DynamoDB abilitati. Solo gli attributi chiave dell’elemento modificato vengono scritti nel flusso.  

```
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
```
Output:  

```
{
    "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
    }
}
```
Per ulteriori informazioni, consulta [Acquisizione dei dati di modifica per DynamoDB Streams](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 9: come creare una tabella con la classe Accesso infrequente standard**  
L’esempio seguente crea una tabella denominata `GameScores` e assegna la classe di tabella Accesso Infrequente Amazon DynamoDB Standard (AI Amazon DynamoDB Standard). Questa classe di tabelle è ottimizzata a livello di archiviazione in quanto l’archiviazione rappresenta il costo principale.  

```
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
```
Output:  

```
{
    "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
    }
}
```
Per ulteriori informazioni, consulta [Classi di tabelle](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.TableClasses.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 10: come creare una tabella con l’opzione Protezione da eliminazione abilitata**  
L’esempio seguente crea una tabella denominata `GameScores` e abilita la protezione da eliminazione.  

```
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
```
Output:  

```
{
    "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
    }
}
```
Per ulteriori informazioni, consulta [Uso della protezione da eliminazione](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeletionProtection) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
+  *Per i dettagli sull'API, consulta Command [CreateTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/create-table.html)Reference AWS CLI .* 

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

**SDK per Go V2**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
}
```
+  Per i dettagli sull'API, consulta la [CreateTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.CreateTable)sezione *AWS SDK per Go API Reference*. 

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

**SDK per Java 2.x**  
 C'è di più su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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 "";
    }
}
```
+  Per i dettagli sull'API, [CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/CreateTable)consulta *AWS SDK for Java 2.x API Reference*. 

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

**SDK per JavaScript (v3)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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;
};
```
+  Per ulteriori informazioni, consulta la [Guida per sviluppatori di AWS SDK per JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table). 
+  Per i dettagli sull'API, [CreateTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/CreateTableCommand)consulta *AWS SDK per JavaScript API Reference*. 

**SDK per JavaScript (v2)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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);
  }
});
```
+  Per ulteriori informazioni, consulta la [Guida per sviluppatori di AWS SDK per JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table). 
+  Per i dettagli sull'API, [CreateTable](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/CreateTable)consulta *AWS SDK per JavaScript API Reference*. 

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

**SDK per Kotlin**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
    }
}
```
+  Per i dettagli sull'API, [CreateTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)consulta *AWS SDK for Kotlin* API reference. 

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

**SDK per PHP**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples). 
Creare una tabella.  

```
        $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],
        ]);
    }
```
+  Per i dettagli sull'API, [CreateTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/CreateTable)consulta *AWS SDK per PHP API Reference*. 

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

**Strumenti per PowerShell V4**  
**Esempio 1: Questo esempio crea una tabella denominata Thread con una chiave primaria composta da 'ForumName' (hash del tipo di chiave) e 'Subject' (intervallo dei tipi di chiave). Lo schema utilizzato per costruire la tabella può essere inserito in ogni cmdlet come mostrato o specificato mediante il parametro -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
```
**Output:**  

```
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  : {}
```
**Esempio 2: Questo esempio crea una tabella denominata Thread con una chiave primaria composta da 'ForumName' (hash del tipo di chiave) e 'Subject' (intervallo dei tipi di chiave). Viene inoltre definito un indice secondario locale. La chiave dell'indice secondario locale verrà impostata automaticamente dalla chiave hash primaria sulla tabella ()ForumName. Lo schema utilizzato per costruire la tabella può essere inserito in ogni cmdlet come mostrato o specificato mediante il parametro -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
```
**Output:**  

```
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}
```
**Esempio 3: Questo esempio mostra come utilizzare una singola pipeline per creare una tabella denominata Thread con una chiave primaria composta da '' ForumName (hash del tipo di chiave) e 'Subject' (intervallo dei tipi di chiave) e un indice secondario locale. Add- DDBKey Schema e Add- DDBIndex Schema creano automaticamente un nuovo TableSchema oggetto se uno non viene fornito dalla pipeline o dal parametro -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
```
**Output:**  

```
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}
```
+  Per i dettagli sull'API, vedere [CreateTable](https://docs.aws.amazon.com/powershell/v4/reference)in *AWS Strumenti per PowerShell Cmdlet Reference* (V4). 

**Strumenti per V5 PowerShell **  
**Esempio 1: Questo esempio crea una tabella denominata Thread con una chiave primaria composta da 'ForumName' (hash del tipo di chiave) e 'Subject' (intervallo dei tipi di chiave). Lo schema utilizzato per costruire la tabella può essere inserito in ogni cmdlet come mostrato o specificato mediante il parametro -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
```
**Output:**  

```
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  : {}
```
**Esempio 2: Questo esempio crea una tabella denominata Thread con una chiave primaria composta da 'ForumName' (hash del tipo di chiave) e 'Subject' (intervallo dei tipi di chiave). Viene inoltre definito un indice secondario locale. La chiave dell'indice secondario locale verrà impostata automaticamente dalla chiave hash primaria sulla tabella ()ForumName. Lo schema utilizzato per costruire la tabella può essere inserito in ogni cmdlet come mostrato o specificato mediante il parametro -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
```
**Output:**  

```
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}
```
**Esempio 3: Questo esempio mostra come utilizzare una singola pipeline per creare una tabella denominata Thread con una chiave primaria composta da '' ForumName (hash del tipo di chiave) e 'Subject' (intervallo dei tipi di chiave) e un indice secondario locale. Add- DDBKey Schema e Add- DDBIndex Schema creano automaticamente un nuovo TableSchema oggetto se uno non viene fornito dalla pipeline o dal parametro -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
```
**Output:**  

```
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}
```
+  Per i dettagli sull'API, vedere [CreateTable](https://docs.aws.amazon.com/powershell/v5/reference)in *AWS Strumenti per PowerShell Cmdlet Reference* (V5). 

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

**SDK per Python (Boto3)**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 
Crea una tabella per la memorizzazione dei dati del filmato.  

```
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
```
+  Per i dettagli sull'API, consulta [CreateTable AWS](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/CreateTable)*SDK for Python (Boto3) API Reference*. 

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

**SDK per Ruby**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
```
+  Per i dettagli sull'API, [CreateTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/CreateTable)consulta *AWS SDK per Ruby API Reference*. 

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

**SDK per Rust**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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))
        }
    }
}
```
+  Per i dettagli sulle API, consulta la [CreateTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.create_table)guida di *riferimento all'API AWS SDK for Rust*. 

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

**SDK per SAP ABAP**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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.
```
+  Per i dettagli sulle API, [CreateTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)consulta *AWS SDK for SAP ABAP* API reference. 

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

**SDK per Swift**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
        }
    }
```
+  Per i dettagli sull'API, consulta la [CreateTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/createtable(input:))guida di riferimento all'*API AWS SDK for Swift*. 

------

Per ulteriori esempi di DynamoDB, consulta [Esempi di codice per l'utilizzo di DynamoDB AWS SDKs](service_code_examples.md).

Dopo aver creato la nuova tabella, procedere a [Fase 2: scrivere dati in una tabella DynamoDB](getting-started-step-2.md).

# Fase 2: scrivere dati in una tabella DynamoDB
<a name="getting-started-step-2"></a>

In questa fase, inserire diverse voci nella tabella `Music` creata in [Fase 1: creare una tabella DynamoDB](getting-started-step-1.md). 

Per ulteriori informazioni sulle operazioni di scrittura, consulta [Scrittura di un elemento](WorkingWithItems.md#WorkingWithItems.WritingData).

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

Seguire questi passaggi per scrivere i dati nella tabella `Music` utilizzando la console DynamoDB.

1. Apri la console DynamoDB all'indirizzo. [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)

1. Nel riquadro di navigazione a sinistra, selezionare **Tables (Tabelle)**. 

1. Nella pagina **Tabelle**, seleziona la tabella **Musica**.

1. Scegli **Explore table items** (Esplora elementi della tabella).

1. Nella sezione **Elementi restituiti**, seleziona **Crea elemento**.

1. Nella pagina **Crea elemento**, procedi come segue per aggiungere elementi alla tabella:

   1. Scegli **Add new attribute (Aggiungi nuovo attributo)** e quindi scegli **Number (Numero)**.

   1. Per Nome attributo inserisci **Awards**.

   1. Ripeti questo processo per creare un **AlbumTitle** di tipo **String (Stringa)**.

   1. Inserisci i valori seguenti per il tuo elemento:

      1. In **Artist**, digita **No One You Know**.

      1. In **SongTitle**, immettere **Call Me Today**.

      1. In **AlbumTitle**, immettere **Somewhat Famous**.

      1. Per **Awards (Premi)**, inserisci **1**.

1. Scegli **Create Item (Crea elemento)**.

1. Ripeti questo processo e crea un'altra voce con i seguenti valori:

   1. In **Artist**, digita **Acme Band**.

   1. Per **SongTitle**entrare. **Happy Day**

   1. In **AlbumTitle**, immettere **Songs About Life**.

   1. Per **Awards (Premi)**, inserisci **10**.

1. Fatelo ancora una volta per creare un altro elemento con lo stesso **Artista** come il passaggio precedente, ma valori diversi per gli altri attributi:

   1. In **Artist**, digita **Acme Band**.

   1. Per **SongTitle**entrare**PartiQL Rocks**.

   1. In **AlbumTitle**, immettere **Another Album Title**.

   1. Per **Awards (Premi)**, inserisci **8**.

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

L' AWS CLI esempio seguente crea diversi nuovi elementi nella `Music` tabella. È possibile farlo tramite l'API DynamoDB o [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), un linguaggio di query compatibile con SQL per 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'}"
```

Per ulteriori informazioni sulla scrittura di dati con PartiQL, consulta [Istruzioni insert di PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.insert.html).

------

Per ulteriori informazioni sui tipi di dati supportati in DynamoDB, consulta [Tipi di dati](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes). 

Per ulteriori informazioni su come rappresentare i tipi di dati DynamoDB in JSON, consulta [Valori degli attributi](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html). 

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

I seguenti esempi di codice mostrano come scrivere un elemento in una tabella DynamoDB utilizzando un SDK. AWS 

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

**SDK per .NET (v4)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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;
        }
    }
```
+  Per i dettagli sull'API, [PutItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/PutItem)consulta *AWS SDK per .NET API Reference*. 

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

**AWS CLI con lo script Bash**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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

}
```
Le funzioni di utilità utilizzate in questo esempio.  

```
###############################################################################
# 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
}
```
+  Per i dettagli sull'API, consulta [PutItem AWS CLI](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem)*Command Reference*. 

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

**SDK per C\$1\$1**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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);
}
```
Codice che attende che la tabella diventi attiva.  

```
//! 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;
}
```
+  Per i dettagli sull'API, [PutItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/PutItem)consulta *AWS SDK per C\$1\$1 API Reference*. 

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

**AWS CLI**  
**Esempio 1: come aggiungere un elemento a una tabella**  
L'`put-item`esempio seguente aggiunge un nuovo elemento alla *MusicCollection*tabella.  

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

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

```
{
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    },
    "ItemCollectionMetrics": {
        "ItemCollectionKey": {
            "Artist": {
                "S": "No One You Know"
            }
        },
        "SizeEstimateRangeGB": [
            0.0,
            1.0
        ]
    }
}
```
Per ulteriori informazioni, consulta [Scrittura di un elemento](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 2: come sovrascrivere in base a una condizione un elemento in una tabella**  
L’esempio `put-item` seguente sovrascrive un elemento esistente nella tabella `MusicCollection` solo se tale elemento include un attributo `AlbumTitle` con il valore `Greatest Hits`. Il comando restituisce il valore precedente dell’elemento.  

```
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
```
Contenuto di `item.json`:  

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

```
{
    "#A": "AlbumTitle"
}
```
Contenuto di `values.json`:  

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

```
{
    "Attributes": {
        "AlbumTitle": {
            "S": "Greatest Hits"
        },
        "Artist": {
            "S": "No One You Know"
        },
        "SongTitle": {
            "S": "Call Me Today"
        }
    }
}
```
Se la chiave esiste già, verrà visualizzato l’output seguente:  

```
A client error (ConditionalCheckFailedException) occurred when calling the PutItem operation: The conditional request failed.
```
Per ulteriori informazioni, consulta [Scrittura di un elemento](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
+  Per i dettagli sull'API, vedere [PutItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/put-item.html)in *AWS CLI Command Reference*. 

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

**SDK per Go V2**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
}
```
Definisce una struttura di filmato utilizzata in questo esempio.  

```
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"])
}
```
+  Per i dettagli sull'API, [PutItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.PutItem)consulta *AWS SDK per Go API Reference*. 

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

**SDK per Java 2.x**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
Mette un elemento in una tabella utilizzando [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);
        }
    }
}
```
+  Per i dettagli sull'API, vedi [PutItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem)in *AWS SDK for Java 2.x API Reference*. 

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

**SDK per JavaScript (v3)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Questo esempio utilizza il client di documenti per semplificare il lavoro con gli elementi in DynamoDB. Per i dettagli sull'API, consulta [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;
};
```
+  Per i dettagli sulle API, consulta la [PutItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/PutItemCommand)sezione *AWS SDK per JavaScript API Reference*. 

**SDK per JavaScript (v2)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples). 
Inserisci un elemento in una tabella.  

```
// 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);
  }
});
```
Inserisci un elemento in una tabella utilizzando il client documento 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);
  }
});
```
+  Per ulteriori informazioni, consulta la [Guida per sviluppatori di AWS SDK per 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). 
+  Per i dettagli sull'API, [PutItem](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/PutItem)consulta *AWS SDK per JavaScript API Reference*. 

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

**SDK per Kotlin**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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.")
    }
}
```
+  Per i dettagli sull'API, [PutItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)consulta *AWS SDK for Kotlin* API reference. 

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

**SDK per PHP**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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);
    }
```
+  Per i dettagli sull'API, [PutItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/PutItem)consulta *AWS SDK per PHP API Reference*. 

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

**Strumenti per PowerShell V4**  
**Esempio 1: crea un nuovo elemento o sostituisce un elemento esistente con uno nuovo.**  

```
$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
```
+  Per i dettagli sull'API, vedere [PutItem](https://docs.aws.amazon.com/powershell/v4/reference)in *AWS Strumenti per PowerShell Cmdlet Reference (*V4). 

**Strumenti per V5 PowerShell **  
**Esempio 1: crea un nuovo elemento o sostituisce un elemento esistente con uno nuovo.**  

```
$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
```
+  Per i dettagli sull'API, vedere [PutItem](https://docs.aws.amazon.com/powershell/v5/reference)in *AWS Strumenti per PowerShell Cmdlet Reference (*V5). 

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

**SDK per Python (Boto3)**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
```
+  Per i dettagli sull'API, consulta [PutItem AWS](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem)*SDK for Python (Boto3) API Reference*. 

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

**SDK per Ruby**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
```
+  Per i dettagli sull'API, [PutItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/PutItem)consulta *AWS SDK per Ruby API Reference*. 

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

**SDK per Rust**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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,
    })
}
```
+  Per i dettagli sulle API, consulta la [PutItem](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.put_item)guida di *riferimento all'API AWS SDK for Rust*. 

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

**SDK per SAP ABAP**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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.
```
+  Per i dettagli sulle API, [PutItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)consulta *AWS SDK for SAP ABAP* API reference. 

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

**SDK per Swift**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
    }
```
+  Per i dettagli sull'API, consulta la [PutItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/putitem(input:))guida di riferimento all'*API AWS SDK for Swift*. 

------

Per ulteriori esempi di DynamoDB, consulta [Esempi di codice per l'utilizzo di DynamoDB AWS SDKs](service_code_examples.md).

Dopo aver inserito i dati nella tabella, proseguire con [Fase 3: leggere i dati da una tabella DynamoDB](getting-started-step-3.md).

# Fase 3: leggere i dati da una tabella DynamoDB
<a name="getting-started-step-3"></a>

In questa fase, leggerai uno degli elementi creati in [Fase 2: scrivere dati in una tabella DynamoDB](getting-started-step-2.md). È possibile utilizzare la console DynamoDB o AWS CLI leggere un elemento dalla tabella `Music` specificando e. `Artist` `SongTitle` 

Per ulteriori informazioni sulle operazioni di lettura in DynamoDB, consulta [Lettura di un elemento](WorkingWithItems.md#WorkingWithItems.ReadingData). 

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

Seguire questi passaggi per leggere i dati nella tabella `Music` utilizzando la console DynamoDB.

1. Apri la console DynamoDB all'indirizzo. [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)

1. Nel riquadro di navigazione a sinistra, selezionare **Tables (Tabelle)**.

1. Nella pagina **Tabelle**, seleziona la tabella **Musica**.

1. Scegli **Explore table items** (Esplora elementi della tabella).

1. Nella sezione **Elementi restituiti**, visualizza l’elenco di elementi archiviati nella tabella, ordinati per `Artist` e `SongTitle`. Il primo elemento dell'elenco è quello con l'**artista** di nome **Acme Band** e il **SongTitle****PartiQL** Rocks.

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

L' AWS CLI esempio seguente legge un elemento da. `Music` È possibile farlo tramite l'API DynamoDB o [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), un linguaggio di query compatibile con SQL per DynamoDB.

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

**Nota**  
Il comportamento predefinito per DynamoDB è lettura a consistenza finale. Il parametro `consistent-read` viene utilizzato qui di seguito per dimostrare le letture consistenti.

**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\"}}"
```

Utilizzando `get-item` viene restituito il seguente risultato di esempio.

```
{
    "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'"
```

Utilizzando l’istruzione `Select` PartiQL viene restituito il seguente risultato di esempio.

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

Per ulteriori informazioni sulla lettura di dati con PartiQL, consulta [Istruzioni select di PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.SELECT.html).

------

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

I seguenti esempi di codice mostrano come leggere un elemento da una tabella DynamoDB utilizzando un SDK. AWS 

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

**SDK per .NET (v4)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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;
        }
    }
```
+  Per i dettagli sull'API, [GetItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/GetItem)consulta *AWS SDK per .NET API Reference*. 

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

**AWS CLI con lo script Bash**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
}
```
Le funzioni di utilità utilizzate in questo esempio.  

```
###############################################################################
# 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
}
```
+  Per i dettagli sull'API, consulta [GetItem AWS CLI](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/GetItem)*Command Reference*. 

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

**SDK per C\$1\$1**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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();
}
```
+  Per i dettagli sull'API, [GetItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/GetItem)consulta *AWS SDK per C\$1\$1 API Reference*. 

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

**AWS CLI**  
**Esempio 1: come leggere un elemento in una tabella**  
L’esempio `get-item` seguente recupera un elemento dalla tabella `MusicCollection`. La tabella ha una chiave hash-and-range primaria (`Artist`e`SongTitle`), quindi è necessario specificare entrambi questi attributi. Il comando richiede anche informazioni sulla capacità di scrittura utilizzata dall’operazione.  

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

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

```
{
    "Item": {
        "AlbumTitle": {
            "S": "Songs About Life"
        },
        "SongTitle": {
            "S": "Happy Day"
        },
        "Artist": {
            "S": "Acme Band"
        }
    },
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5
    }
}
```
Per ulteriori informazioni, consulta [Lettura di un elemento](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 2: come leggere un elemento utilizzando una lettura consistente**  
L’esempio seguente recupera un elemento dalla tabella `MusicCollection` tramite operazioni a elevata consistenza di lettura.  

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

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

```
{
    "Item": {
        "AlbumTitle": {
            "S": "Songs About Life"
        },
        "SongTitle": {
            "S": "Happy Day"
        },
        "Artist": {
            "S": "Acme Band"
        }
    },
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    }
}
```
Per ulteriori informazioni, consulta [Lettura di un elemento](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 3: come recuperare attributi specifici di un elemento**  
L’esempio seguente utilizza un’espressione di proiezione per recuperare solo tre attributi dell’elemento desiderato.  

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

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

```
{
    "Item": {
        "Price": {
            "N": "20"
        },
        "Title": {
            "S": "Book 102 Title"
        },
        "ProductCategory": {
            "S": "Book"
        }
    }
}
```
Per ulteriori informazioni, consulta [Lettura di un elemento](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
+  Per i dettagli sull'API, consulta [GetItem AWS CLI](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/get-item.html)*Command Reference*. 

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

**SDK per Go V2**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
}
```
Definisce una struttura di filmato utilizzata in questo esempio.  

```
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"])
}
```
+  Per i dettagli sull'API, [GetItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.GetItem)consulta *AWS SDK per Go API Reference*. 

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

**SDK per Java 2.x**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
Ottiene un elemento da una tabella utilizzando 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);
        }
    }
}
```
+  Per i dettagli sull'API, vedere [GetItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/GetItem)in *AWS SDK for Java 2.x API Reference*. 

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

**SDK per JavaScript (v3)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Questo esempio utilizza il client di documenti per semplificare il lavoro con gli elementi in DynamoDB. Per i dettagli sull'API, consulta [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;
};
```
+  Per i dettagli sulle API, consulta la [GetItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/GetItemCommand)sezione *AWS SDK per JavaScript API Reference*. 

**SDK per JavaScript (v2)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples). 
Ottiene un elemento da una tabella.  

```
// 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);
  }
});
```
Ottieni un elemento da una tabella utilizzando il client documento 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);
  }
});
```
+  Per ulteriori informazioni, consulta la [Guida per sviluppatori di AWS SDK per JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-dynamodb-utilities.html#dynamodb-example-document-client-get). 
+  Per i dettagli sull'API, [GetItem](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/GetItem)consulta *AWS SDK per JavaScript API Reference*. 

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

**SDK per Kotlin**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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)
        }
    }
}
```
+  Per i dettagli sull'API, [GetItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)consulta *AWS SDK for Kotlin* API reference. 

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

**SDK per PHP**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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,
        ]);
    }
```
+  Per i dettagli sull'API, [GetItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/GetItem)consulta *AWS SDK per PHP API Reference*. 

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

**Strumenti per PowerShell V4**  
**Esempio 1: restituisce l'elemento DynamoDB con la chiave di partizione e la SongTitle chiave di ordinamento Artist.**  

```
$key = @{
  SongTitle = 'Somewhere Down The Road'
  Artist = 'No One You Know'
} | ConvertTo-DDBItem

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**Output:**  

```
Name                           Value
----                           -----
Genre                          Country
SongTitle                      Somewhere Down The Road
Price                          1.94
Artist                         No One You Know
CriticRating                   9
AlbumTitle                     Somewhat Famous
```
+  Per i dettagli sull'API, vedere [GetItem](https://docs.aws.amazon.com/powershell/v4/reference)in *AWS Strumenti per PowerShell Cmdlet Reference (*V4). 

**Strumenti per V5 PowerShell **  
**Esempio 1: restituisce l'elemento DynamoDB con la chiave di partizione e la SongTitle chiave di ordinamento Artist.**  

```
$key = @{
  SongTitle = 'Somewhere Down The Road'
  Artist = 'No One You Know'
} | ConvertTo-DDBItem

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**Output:**  

```
Name                           Value
----                           -----
Genre                          Country
SongTitle                      Somewhere Down The Road
Price                          1.94
Artist                         No One You Know
CriticRating                   9
AlbumTitle                     Somewhat Famous
```
+  Per i dettagli sull'API, vedere [GetItem](https://docs.aws.amazon.com/powershell/v5/reference)in *AWS Strumenti per PowerShell Cmdlet Reference (*V5). 

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

**SDK per Python (Boto3)**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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"]
```
+  Per i dettagli sull'API, consulta [GetItem AWS](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/GetItem)*SDK for Python (Boto3) API Reference*. 

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

**SDK per Ruby**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
```
+  Per i dettagli sull'API, [GetItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/GetItem)consulta *AWS SDK per Ruby API Reference*. 

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

**SDK per SAP ABAP**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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.
```
+  Per i dettagli sulle API, [GetItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)consulta *AWS SDK for SAP ABAP* API reference. 

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

**SDK per Swift**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
        }
    }
```
+  Per i dettagli sull'API, consulta la [GetItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/getitem(input:))guida di riferimento all'*API AWS SDK for Swift*. 

------

Per ulteriori esempi di DynamoDB, consulta [Esempi di codice per l'utilizzo di DynamoDB AWS SDKs](service_code_examples.md).

Per aggiornare i dati nella tua tabella, prosegui con [Fase 4: aggiornare i dati in una tabella](getting-started-step-4.md).

# Fase 4: aggiornare i dati in una tabella
<a name="getting-started-step-4"></a>

In questa fase, aggiorna una voce che hai creato in [Fase 2: scrivere dati in una tabella DynamoDB](getting-started-step-2.md). È possibile utilizzare la console DynamoDB o AWS CLI aggiornare `AlbumTitle` un elemento nella tabella `Artist` specificando`SongTitle`, e `Music` l'aggiornamento. `AlbumTitle` 

Per ulteriori informazioni sulle operazioni di scrittura, consulta [Scrittura di un elemento](WorkingWithItems.md#WorkingWithItems.WritingData).

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

Puoi utilizzare la console DynamoDB per aggiornare i dati nella tabella `Music`.

1. Apri la console DynamoDB all'indirizzo. [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)

1. Nel riquadro di navigazione a sinistra, selezionare **Tables (Tabelle)**.

1. Nell'elenco delle tabelle, scegli la tabella **Musica**.

1. Scegli **Explore table items** (Esplora elementi della tabella).

1. In **Oggetti restituiti**, per la riga dell'elemento con **Acme Band** **Artist** e **Happy Day **SongTitle**, procedi** come segue:

   1. Posiziona il cursore sul **AlbumTitle**titolo **Songs About Life**.

   1. Seleziona l’icona Modifica.

   1. Nella finestra popup **Modifica stringa**, inserisci **Songs of Twilight**.

   1. Scegli **Save** (Salva).
**Suggerimento**  
In alternativa, per aggiornare un elemento, procedi come segue nella sezione **Elementi restituiti**:  
Scegli la riga dell'elemento con l'**artista** di nome **Acme Band** e il **SongTitle**nome **Happy** Day.
Dal menù a discesa **Operazioni**, seleziona **Modifica elemento**.
Per entrare **AlbumTitle**, inserisci**Songs of Twilight**.
Selezionare **Save and close (Salva e chiudi)**.

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

L' AWS CLI esempio seguente aggiorna un elemento nella `Music` tabella. È possibile farlo tramite l'API DynamoDB o [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), un linguaggio di query compatibile con SQL per 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’utilizzo di `update-item` restituisce il seguente risultato di esempio perché è stato specificato `return-values ALL_NEW`.

```
{
    "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’utilizzo dell’istruzione `Update` restituisce il seguente risultato di esempio perché è stato specificato `RETURNING ALL NEW *`.

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

Per ulteriori informazioni sull’aggiornamento dei dati con PartiQL, consulta [Istruzioni update di PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.update.html).

------

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

I seguenti esempi di codice mostrano come aggiornare un elemento in una tabella DynamoDB utilizzando un SDK. AWS 

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

**SDK per .NET (v4)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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;
        }
    }
```
+  Per i dettagli sull'API, [UpdateItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/UpdateItem)consulta *AWS SDK per .NET API Reference*. 

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

**AWS CLI con lo script Bash**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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

}
```
Le funzioni di utilità utilizzate in questo esempio.  

```
###############################################################################
# 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
}
```
+  Per i dettagli sull'API, consulta [UpdateItem AWS CLI](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateItem)*Command Reference*. 

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

**SDK per C\$1\$1**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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);
}
```
Codice che attende che la tabella diventi attiva.  

```
//! 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;
}
```
+  Per i dettagli sull'API, [UpdateItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/UpdateItem)consulta *AWS SDK per C\$1\$1 API Reference*. 

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

**AWS CLI**  
**Esempio 1: come aggiornare un elemento in una tabella**  
L’esempio `update-item` seguente legge una voce dalla tabella `MusicCollection`. Aggiunge un nuovo attributo (`Year`) e modifica l’attributo `AlbumTitle`. Tutti gli attributi dell’elemento come appaiono dopo l’aggiornamento vengono restituiti nella risposta.  

```
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
```
Contenuto di `key.json`:  

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

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

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

```
{
    "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
        ]
    }
}
```
Per ulteriori informazioni, consulta [Scrittura di un elemento](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 2: come aggiornare un elemento in base a una condizione**  
L’esempio seguente aggiorna un elemento nella tabella `MusicCollection`, ma solo se l’elemento esistente non dispone già di un attributo `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)"
```
Contenuto di `key.json`:  

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

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

```
{
    ":y":{"N": "2015"},
    ":t":{"S": "Louder Than Ever"}
}
```
Se l’elemento include già un attributo `Year`, DynamoDB restituisce il seguente output.  

```
An error occurred (ConditionalCheckFailedException) when calling the UpdateItem operation: The conditional request failed
```
Per ulteriori informazioni, consulta [Scrittura di un elemento](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
+  Per i dettagli sull'API, consulta [UpdateItem AWS CLI](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-item.html)*Command Reference*. 

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

**SDK per Go V2**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
}
```
Definisce una struttura di filmato utilizzata in questo esempio.  

```
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"])
}
```
+  Per i dettagli sull'API, [UpdateItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.UpdateItem)consulta *AWS SDK per Go API Reference*. 

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

**SDK per Java 2.x**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
Aggiorna un elemento in una tabella utilizzando [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!");
    }
}
```
+  Per i dettagli sull'API, consulta la [UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)sezione *AWS SDK for Java 2.x API Reference*. 

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

**SDK per JavaScript (v3)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Questo esempio utilizza il client di documenti per semplificare il lavoro con gli elementi in DynamoDB. Per i dettagli sull'API, consulta [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;
};
```
+  Per i dettagli sulle API, consulta la [UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)sezione *AWS SDK per JavaScript API Reference*. 

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

**SDK per Kotlin**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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")
    }
}
```
+  Per i dettagli sull'API, [UpdateItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)consulta *AWS SDK for Kotlin* API reference. 

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

**SDK per PHP**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
                ]
            ],
        ]);
    }
```
+  Per i dettagli sull'API, [UpdateItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/UpdateItem)consulta *AWS SDK per PHP API Reference*. 

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

**Strumenti per PowerShell V4**  
**Esempio 1: imposta l'attributo genre su 'Rap' sull'elemento DynamoDB con la chiave di partizione e la SongTitle chiave di ordinamento 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
```
**Output:**  

```
Name                           Value
----                           -----
Genre                          Rap
```
+  Per i dettagli sull'API, vedere [UpdateItem](https://docs.aws.amazon.com/powershell/v4/reference)in *AWS Strumenti per PowerShell Cmdlet Reference (*V4). 

**Strumenti per V5 PowerShell **  
**Esempio 1: imposta l'attributo genre su 'Rap' sull'elemento DynamoDB con la chiave di partizione e la SongTitle chiave di ordinamento 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
```
**Output:**  

```
Name                           Value
----                           -----
Genre                          Rap
```
+  Per i dettagli sull'API, vedere [UpdateItem](https://docs.aws.amazon.com/powershell/v5/reference)in *AWS Strumenti per PowerShell Cmdlet Reference (*V5). 

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

**SDK per Python (Boto3)**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 
Aggiorna un elemento utilizzando un’espressione di aggiornamento.  

```
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"]
```
Aggiorna un elemento utilizzando un’espressione di aggiornamento che include un’operazione aritmetica.  

```
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"]
```
Aggiorna un elemento solo quando soddisfa determinate condizioni.  

```
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"]
```
+  Per i dettagli sull'API, consulta [UpdateItem AWS](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)*SDK for Python (Boto3) API Reference*. 

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

**SDK per Ruby**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
```
+  Per i dettagli sull'API, [UpdateItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/UpdateItem)consulta *AWS SDK per Ruby API Reference*. 

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

**SDK per SAP ABAP**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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.
```
+  Per i dettagli sulle API, [UpdateItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)consulta *AWS SDK for SAP ABAP* API reference. 

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

**SDK per Swift**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
        }
    }
```
+  Per i dettagli sull'API, consulta la [UpdateItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/updateitem(input:))guida di riferimento all'*API AWS SDK for Swift*. 

------

Per ulteriori esempi di DynamoDB, consulta [Esempi di codice per l'utilizzo di DynamoDB AWS SDKs](service_code_examples.md).

Per eseguire una query dei dati nella tabella `Music`, continua con [Fase 5: eseguire query sui dati in una tabella DynamoDB](getting-started-step-5.md).

# Fase 5: eseguire query sui dati in una tabella DynamoDB
<a name="getting-started-step-5"></a>

In questa fase, esegui le query dei dati che hai scritto nella tabella `Music` in [Fase 2: scrivere dati in una tabella DynamoDB](getting-started-step-2.md) specificando `Artist`. In questo modo verranno visualizzate tutte le canzoni associate alla chiave di partizione: `Artist`.

Per ulteriori informazioni sulle operazioni delle query, consulta [Esecuzione di query in DynamoDB](Query.md). 

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

Segui questi passaggi per utilizzare la console DynamoDB per eseguire query dei dati nella tabella `Music`.

1. Apri la console DynamoDB all'indirizzo. [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)

1. Nel riquadro di navigazione a sinistra, selezionare **Tables (Tabelle)**.

1. Nell'elenco delle tabelle, scegli la tabella **Musica**.

1. Scegli **Explore table items** (Esplora elementi della tabella).

1. In **Scansiona o interroga gli elementi**, assicurati che sia selezionata l’opzione **Query**.

1. In **Partition key (Chiave di partizione)**, inserisci **Acme Band**, quindi scegli **Run (Esegui)**.

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

L' AWS CLI esempio seguente interroga un elemento nella tabella. `Music` È possibile farlo tramite l'API DynamoDB o [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), un linguaggio di query compatibile con SQL per DynamoDB.

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

È possibile eseguire una query su un elemento tramite l'API DynamoDB utilizzando `query` e fornendo la chiave di partizione.

**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\"}}"
```

L’utilizzo di `query` restituisce tutte le canzoni associate a questo particolare `Artist`.

```
{
    "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 ]

È possibile eseguire una query su PartiQL utilizzando l’istruzione `Select` e fornendo la chiave di partizione.

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

L’utilizzo della dichiarazione `Select` in questo modo restituisce tutte le canzoni associate a questo particolare `Artist`.

```
{
    "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"
            }
        }
    ]
}
```

Per ulteriori informazioni sull’esecuzione di query sui dati con PartiQL, consulta [Istruzioni select di PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.select.html).

------

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

I seguenti esempi di codice mostrano come eseguire una query su una tabella DynamoDB utilizzando un SDK AWS .

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

**SDK per .NET (v4)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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;
        }
    }
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/Query) nella *documentazione di riferimento dell’API AWS SDK per .NET *. 

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

**AWS CLI con lo script Bash**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
}
```
Le funzioni di utilità utilizzate in questo esempio.  

```
###############################################################################
# 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
}
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/Query) nella *documentazione di riferimento di AWS CLI *. 

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

**SDK per C\$1\$1**  
 C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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;
}
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/Query) nella *documentazione di riferimento dell’API AWS SDK per C\$1\$1 *. 

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

**AWS CLI**  
**Esempio 1: come eseguire una query su una tabella.**  
L’esempio `query` seguente esegue query sulle voce della tabella `MusicCollection`. La tabella ha una chiave hash-and-range primaria (`Artist`and`SongTitle`), ma questa query specifica solo il valore della chiave hash. Restituisce i titoli dei brani dell’artista “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
```
Contenuto di `expression-attributes.json`:  

```
{
    ":v1": {"S": "No One You Know"}
}
```
Output:  

```
{
    "Items": [
        {
            "SongTitle": {
                "S": "Call Me Today"
            },
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5
    }
}
```
Per ulteriori informazioni, consulta [Utilizzo delle query in DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 2: come eseguire una query su una tabella utilizzando l’elevata consistenza di lettura e attraversare l’indice in ordine decrescente**  
L’esempio seguente esegue la stessa query del primo esempio, ma restituisce i risultati in ordine inverso e utilizza operazioni a elevata consistenza di lettura.  

```
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
```
Contenuto di `expression-attributes.json`:  

```
{
    ":v1": {"S": "No One You Know"}
}
```
Output:  

```
{
    "Items": [
        {
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        },
        {
            "SongTitle": {
                "S": "Call Me Today"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    }
}
```
Per ulteriori informazioni, consulta [Utilizzo delle query in DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 3: come filtrare risultati specifici**  
L’esempio seguente esegue una query su `MusicCollection` ma esclude i risultati con valori specifici nell’attributo `AlbumTitle`. Nota che ciò non influisce su `ScannedCount` o `ConsumedCapacity`, poiché il filtro viene applicato dopo la lettura degli elementi.  

```
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
```
Contenuto di `values.json`:  

```
{
    ":v1": {"S": "No One You Know"},
    ":v2": {"S": "Blue Sky Blues"},
    ":v3": {"S": "Greatest Hits"}
}
```
Contenuto di `names.json`:  

```
{
    "#n1": "Artist",
    "#n2": "AlbumTitle"
}
```
Output:  

```
{
    "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
    }
}
```
Per ulteriori informazioni, consulta [Utilizzo delle query in DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 4: come recuperare solo il conteggio degli elementi**  
L’esempio seguente recupera il conteggio degli elementi corrispondenti alla query, ma non recupera nessuno degli elementi stessi.  

```
aws dynamodb query \
    --table-name MusicCollection \
    --select COUNT \
    --key-condition-expression "Artist = :v1" \
    --expression-attribute-values file://expression-attributes.json
```
Contenuto di `expression-attributes.json`:  

```
{
    ":v1": {"S": "No One You Know"}
}
```
Output:  

```
{
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": null
}
```
Per ulteriori informazioni, consulta [Utilizzo delle query in DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
**Esempio 5: come eseguire una query su un indice**  
L’esempio seguente esegue una query sull’indice globale secondario `AlbumTitleIndex`. La query restituisce tutti gli attributi della tabella di base proiettati nell’indice secondario locale. Nota che durante l’esecuzione di query su un indice secondario locale o su un indice secondario globale è necessario fornire anche il nome della tabella di base mediante il parametro `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
```
Contenuto di `expression-attributes.json`:  

```
{
    ":v1": {"S": "No One You Know"}
}
```
Output:  

```
{
    "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
            }
        }
    }
}
```
Per ulteriori informazioni, consulta [Utilizzo delle query in DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
+  Per informazioni dettagliate sull’API, consulta [Query](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/query.html) nella *documentazione di riferimento di AWS CLI *. 

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

**SDK per Go V2**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
}
```
Definisce una struttura di filmato utilizzata in questo esempio.  

```
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"])
}
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.Query) nella *documentazione di riferimento dell’API AWS SDK per Go *. 

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

**SDK per Java 2.x**  
 C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
Interroga una tabella utilizzando [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;
    }
}
```
Esegue query su una tabella utilizzando `DynamoDbClient` e un indice secondario.  

```
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);
        }
    }
}
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query) nella *documentazione di riferimento dell’API AWS SDK for Java 2.x *. 

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

**SDK per JavaScript (v3)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Questo esempio utilizza il client di documenti per semplificare il lavoro con gli elementi in DynamoDB. Per i dettagli sull'API, consulta [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;
};
```
+  Per ulteriori informazioni, consulta la [Guida per sviluppatori di AWS SDK per JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying). 
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand) nella *documentazione di riferimento dell’API AWS SDK per JavaScript *. 

**SDK per JavaScript (v2)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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);
  }
});
```
+  Per ulteriori informazioni, consulta la [Guida per sviluppatori di AWS SDK per JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying). 
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/Query) nella *documentazione di riferimento dell’API AWS SDK per JavaScript *. 

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

**SDK per Kotlin**  
 C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
    }
}
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://sdk.amazonaws.com/kotlin/api/latest/index.html) nella *documentazione di riferimento dell’API AWS SDK per Kotlin*. 

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

**SDK per PHP**  
 C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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);
    }
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/Query) nella *documentazione di riferimento dell’API AWS SDK per PHP *. 

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

**Strumenti per PowerShell V4**  
**Esempio 1: richiama una query che restituisce elementi DynamoDB con l'elemento Artist specificato. 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
```
**Output:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/powershell/v4/reference) nella *documentazione di riferimento dei cmdlet di AWS Strumenti per PowerShell (V4)*. 

**Strumenti per V5 PowerShell **  
**Esempio 1: richiama una query che restituisce elementi DynamoDB con l'elemento Artist specificato. 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
```
**Output:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/powershell/v5/reference) nella *documentazione di riferimento dei cmdlet di AWS Strumenti per PowerShell (V5)*. 

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

**SDK per Python (Boto3)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 
Esegui la query degli elementi utilizzando un’espressione di condizione chiave.  

```
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"]
```
Esegui la query degli elementi e proiettali per restituire un sottoinsieme di dati.  

```
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"]
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query) nella *documentazione di riferimento dell’API SDK for Python (Boto3)AWS *. 

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

**SDK per Ruby**  
 C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/Query) nella *documentazione di riferimento dell’API AWS SDK per Ruby *. 

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

**SDK per Rust**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples). 
Trova i filmati realizzati nell’anno specificato.  

```
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![])
    }
}
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.query) nella *documentazione di riferimento dell’API SDK AWS per Rust*. 

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

**SDK per SAP ABAP**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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.
```
+  Per informazioni dettagliate sull’API, consulta [Query](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html) nella *documentazione di riferimento dell’API AWS SDK per SAP ABAP*. 

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

**SDK per Swift**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
        }
    }
```
+  Per informazioni dettagliate sulle API, consulta [Query](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/query(input:)) nella *Documentazione di riferimento per le API di SDK AWS per Swift*. 

------

Per ulteriori esempi di DynamoDB, consulta [Esempi di codice per l'utilizzo di DynamoDB AWS SDKs](service_code_examples.md).

Per creare un indice globale secondario per la tua tabella, procedi con [Fase 6: (facoltativo) eliminare la tabella DynamoDB per eseguire la pulizia delle risorse](getting-started-step-6.md).

# Fase 6: (facoltativo) eliminare la tabella DynamoDB per eseguire la pulizia delle risorse
<a name="getting-started-step-6"></a>

Se non hai più bisogno della tabella Amazon DynamoDB creata per il tutorial, puoi eliminarla. In questo modo hai la certezza che non ti vengano addebitati costi per risorse che non stai utilizzando. È possibile utilizzare la console DynamoDB o eliminare AWS CLI `Music` la tabella in cui è stata creata. [Fase 1: creare una tabella DynamoDB](getting-started-step-1.md)

Per ulteriori informazioni sulle operazioni della tabella in DynamoDB, consulta [Utilizzo di tabelle e dati in DynamoDB](WorkingWithTables.md). 

## Console di gestione AWS
<a name="getting-started-step-8-Console"></a>

Per eliminare la tabella `Music` utilizzando la console:

1. Apri la console DynamoDB all'indirizzo. [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)

1. Nel riquadro di navigazione a sinistra, selezionare **Tables (Tabelle)**.

1. Seleziona la casella di spunta accanto alla tabella **Musica** nell’elenco delle tabelle.

1. Scegli **Elimina**.

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

L' AWS CLI esempio seguente elimina la `Music` tabella utilizzando. `delete-table`

```
aws dynamodb delete-table --table-name Music
```

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

I seguenti esempi di codice mostrano come eliminare una tabella DynamoDB usando un SDK AWS .

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

**SDK per .NET (v4)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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;
        }
    }
```
+  Per i dettagli sull'API, [DeleteTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/DeleteTable)consulta *AWS SDK per .NET API Reference*. 

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

**AWS CLI con lo script Bash**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
}
```
Le funzioni di utilità utilizzate in questo esempio.  

```
###############################################################################
# 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
}
```
+  Per i dettagli sull'API, consulta [DeleteTable AWS CLI](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteTable)*Command Reference*. 

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

**SDK per C\$1\$1**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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();
}
```
+  Per i dettagli sull'API, [DeleteTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/DeleteTable)consulta *AWS SDK per C\$1\$1 API Reference*. 

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

**AWS CLI**  
**Come eliminare una tabella**  
L’esempio `delete-table` seguente elimina la tabella `MusicCollection`.  

```
aws dynamodb delete-table \
    --table-name MusicCollection
```
Output:  

```
{
    "TableDescription": {
        "TableStatus": "DELETING",
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableName": "MusicCollection",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "WriteCapacityUnits": 5,
            "ReadCapacityUnits": 5
        }
    }
}
```
Per ulteriori informazioni, consulta [Eliminazione di una tabella](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeleteTable) nella *Guida per gli sviluppatori di Amazon DynamoDB*.  
+  Per i dettagli sull'API, consulta [DeleteTable AWS CLI](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/delete-table.html)*Command Reference*. 

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

**SDK per Go V2**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
}
```
+  Per i dettagli sull'API, [DeleteTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.DeleteTable)consulta *AWS SDK per Go API Reference*. 

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

**SDK per Java 2.x**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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!");
    }
}
```
+  Per i dettagli sull'API, [DeleteTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DeleteTable)consulta *AWS SDK for Java 2.x API Reference*. 

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

**SDK per JavaScript (v3)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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;
};
```
+  Per i dettagli sull'API, [DeleteTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DeleteTableCommand)consulta *AWS SDK per JavaScript API Reference*. 

**SDK per JavaScript (v2)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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);
  }
});
```
+  Per ulteriori informazioni, consulta la [Guida per sviluppatori di AWS SDK per JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-deleting-a-table). 
+  Per i dettagli sull'API, [DeleteTable](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/DeleteTable)consulta *AWS SDK per JavaScript API Reference*. 

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

**SDK per Kotlin**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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")
    }
}
```
+  Per i dettagli sull'API, [DeleteTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)consulta *AWS SDK for Kotlin* API reference. 

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

**SDK per PHP**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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,
            ]);
        });
    }
```
+  Per i dettagli sull'API, [DeleteTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/DeleteTable)consulta *AWS SDK per PHP API Reference*. 

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

**Strumenti per PowerShell V4**  
**Esempio 1: elimina la tabella specificata. Prima di procedere con l’operazione, viene richiesta una conferma.**  

```
Remove-DDBTable -TableName "myTable"
```
**Esempio 2: elimina la tabella specificata. Prima di procedere con l’operazione, non viene richiesta una conferma.**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  Per i dettagli sull'API, vedere [DeleteTable](https://docs.aws.amazon.com/powershell/v4/reference)in *AWS Strumenti per PowerShell Cmdlet Reference (*V4). 

**Strumenti per V5 PowerShell **  
**Esempio 1: elimina la tabella specificata. Prima di procedere con l’operazione, viene richiesta una conferma.**  

```
Remove-DDBTable -TableName "myTable"
```
**Esempio 2: elimina la tabella specificata. Prima di procedere con l’operazione, non viene richiesta una conferma.**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  Per i dettagli sull'API, vedere [DeleteTable](https://docs.aws.amazon.com/powershell/v5/reference)in *AWS Strumenti per PowerShell Cmdlet Reference (*V5). 

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

**SDK per Python (Boto3)**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
```
+  Per i dettagli sull'API, consulta [DeleteTable AWS](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DeleteTable)*SDK for Python (Boto3) API Reference*. 

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

**SDK per Ruby**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
```
+  Per i dettagli sull'API, [DeleteTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/DeleteTable)consulta *AWS SDK per Ruby API Reference*. 

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

**SDK per Rust**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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())),
    }
}
```
+  Per i dettagli sulle API, consulta la [DeleteTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.delete_table)guida di *riferimento all'API AWS SDK for Rust*. 

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

**SDK per SAP ABAP**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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.
```
+  Per i dettagli sulle API, [DeleteTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)consulta *AWS SDK for SAP ABAP* API reference. 

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

**SDK per Swift**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice 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
        }
    }
```
+  Per i dettagli sull'API, consulta la [DeleteTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/deletetable(input:))guida di riferimento all'*API AWS SDK for Swift*. 

------

Per ulteriori esempi di DynamoDB, consulta [Esempi di codice per l'utilizzo di DynamoDB AWS SDKs](service_code_examples.md).

# Conoscenze aggiuntive su DynamoDB
<a name="getting-started-NextSteps"></a>

Per ulteriori informazioni sull'utilizzo di Amazon DynamoDB, consulta i seguenti argomenti:
+ [Utilizzo di tabelle e dati in DynamoDB](WorkingWithTables.md)
+ [Utilizzo di elementi e attributi in DynamoDB](WorkingWithItems.md)
+ [Esecuzione di query in DynamoDB](Query.md)
+ [Utilizzo degli indici secondari globali in DynamoDB](GSI.md)
+ [Utilizzo delle transazioniCodice di esempio](transactions.md)
+ [Accelerazione in memoria con DynamoDB Accelerator (DAX)](DAX.md)
+ [Programmazione con DynamoDB e AWS SDKs](Programming.md)

# Genera codice di infrastruttura per Amazon DynamoDB utilizzando Console-to-Code
<a name="console-to-code"></a>

La Console-to-Code funzionalità di Amazon Q Developer semplifica la gestione dell'infrastruttura per Amazon DynamoDB trasformando le fasi di creazione manuale delle tabelle in codice di automazione riproducibile. Questa funzionalità aiuta gli sviluppatori a scalare in modo efficiente la configurazione delle risorse di database nei loro ambienti. Per ulteriori informazioni, consulta [Automating Servizi AWS with Amazon Q Developer Console-to-Code](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/console-to-code.html).

Console-to-Code acquisisce configurazioni dettagliate delle tabelle DynamoDB, incluse chiavi di partizione, chiavi di ordinamento, impostazioni di throughput assegnate e indici secondari, e le converte in modelli precisi. infrastructure-as-code Utilizzando l’IA generativa, lo strumento assicura che il codice generato mantenga la compatibilità dei parametri stabilita durante il flusso di lavoro della console.

Gli sviluppatori possono generare il codice dell’infrastruttura DynamoDB in diversi formati, come:
+ AWS Cloud Development Kit (AWS CDK) in TypeScript Python e Java
+ CloudFormation in YAML o JSON

Questo approccio consente ai team di:
+ Standardizzare la gestione delle risorse del database
+ Implementare un’infrastruttura con controllo delle versioni
+ Ridurre gli errori dovuti alla configurazione manuale

Console-to-Code for Amazon DynamoDB è disponibile in tutte le regioni AWS commerciali e offre una potente soluzione per trasformare le configurazioni manuali in codice di infrastruttura automatizzato e riproducibile.

## Come funziona
<a name="how-it-works"></a>

Quando si utilizza Console-to-Code con DynamoDB, il processo prevede in genere:

1. **Prototipazione nella console**: utilizzo della console DynamoDB per creare e configurare risorse come le tabelle. Per ulteriori informazioni, consulta [Connect to Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStartedDynamoDB.html).

1. **Registrazione delle azioni**: Console-to-Code registra queste azioni mentre le esegui.

1. **Generazione di codice**: la funzionalità utilizza le funzionalità di IA generativa di Amazon Q Developer per trasformare le azioni della console in codice riutilizzabile nel formato preferito.

1. **Personalizzazione del codice**: è possibile quindi copiare o scaricare questo codice e personalizzarlo ulteriormente per i propri carichi di lavoro di produzione.

## Vantaggi dell'utilizzo Console-to-Code con DynamoDB
<a name="benefits"></a>

**Automazione semplificata**  
Conversione della creazione e della configurazione manuali di tabelle DynamoDB in codice riutilizzabile con un solo clic.

**Best practice**  
Il codice generato segue le migliori pratiche AWS guidate per implementazioni affidabili.

**Un ponte tra console e codice**  
Non è necessario scegliere tra l'utilizzo di Console di gestione AWS o Infrastructure-as-Code (IaC). È possibile utilizzare entrambi gli approcci insieme.

**Sviluppo più veloce**  
Avvio rapido con un codice di automazione che può essere ulteriormente personalizzato per l’uso in produzione.

## Casi d'uso di esempio
<a name="example-use-cases"></a>
+ Creazione di tabelle DynamoDB con attributi, chiavi e impostazioni di capacità specifici
+ Configurazione di indici secondari globali e indici secondari locali
+ Configurazione di policy di dimensionamento automatico per le tabelle DynamoDB
+ Creazione di configurazioni di backup e ripristino
+ Creazione e gestione di flussi DynamoDB

## Nozioni di base
<a name="getting-started"></a>

Per iniziare a utilizzare Console-to-Code con DynamoDB:

1. Accedi Console di gestione AWS e apri la console DynamoDB all'indirizzo. [https://console.aws.amazon.com/dynamodbv2/](https://console.aws.amazon.com/dynamodbv2/)

1. Inizia a creare o modificare le risorse DynamoDB tramite l’interfaccia della console.

1. Usa la Console-to-Code funzione per generare codice per le tue azioni nel tuo formato preferito.

1. Copia o scarica il codice generato e personalizzalo in base alle esigenze specifiche.

Per ulteriori informazioni e istruzioni dettagliate sull'uso Console-to-Code, consulta [Automating Servizi AWS with Amazon Q Developer Console-to-Code nella Amazon Q Developer](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/console-to-code.html) *User Guide*.