

# Conceitos básicos do DynamoDB
<a name="GettingStartedDynamoDB"></a>

Você aprenderá a se conectar, criar e gerenciar tabelas do DynamoDB nas seções a seguir.

Antes de começar, é importante conhecer os conceitos básicos do Amazon DynamoDB. Você pode obter uma rápida visão geral em [O que é o Amazon DynamoDB?](Introduction.md) e uma análise mais aprofundada em [Componentes principais do Amazon DynamoDB](HowItWorks.CoreComponents.md). Em seguida, continue com os [Pré-requisitos](#GettingStarted.SettingUp.DynamoWebService).

**nota**  
Ao se cadastrar na AWS, você poderá começar a usar o DynamoDB pelo [nível gratuito da AWS](https://aws.amazon.com/free/). Se você ainda não tiver utilizado todos os benefícios do nível gratuito do Amazon DynamoDB, não haverá nenhum custo para concluir os exemplos desta seção. Caso contrário, você incorrerá nas taxas de uso padrão do DynamoDB desde o momento em que criar as tabelas até quando excluí-las.  
Se você não quiser criar uma conta de nível gratuito, poderá configurar o [DynamoDB local (versão disponível para download)](DynamoDBLocal.md) no computador. A versão para download permite desenvolver e testar aplicações localmente sem que seja necessário cadastrar uma conta AWS ou acessar o serviço da web do DynamoDB.

**Topics**
+ [Recursos do Amazon DynamoDB para usuários iniciantes](dynamodb-resources-first-time-users.md)
+ [Acessar o DynamoDB](AccessingDynamoDB.md)
+ [Pré-requisitos](#GettingStarted.SettingUp.DynamoWebService)
+ [Configurar o DynamoDB](SettingUp.md)
+ [Etapa 1: crie uma tabela no DynamoDB](getting-started-step-1.md)
+ [Etapa 2: grave dados em uma tabela do DynamoDB](getting-started-step-2.md)
+ [Etapa 3: leia os dados de uma tabela do DynamoDB](getting-started-step-3.md)
+ [Etapa 4: atualize os dados em uma tabela do DynamoDB](getting-started-step-4.md)
+ [Etapa 5: consulte os dados de uma tabela do DynamoDB](getting-started-step-5.md)
+ [Etapa 6: (Opcional) exclua uma tabela do DynamoDB para limpar os recursos](getting-started-step-6.md)
+ [Aprender mais sobre o DynamoDB](getting-started-NextSteps.md)
+ [Gerar código de infraestrutura para o Amazon DynamoDB usando o Console-to-Code.](console-to-code.md)

# Recursos do Amazon DynamoDB para usuários iniciantes
<a name="dynamodb-resources-first-time-users"></a>

Recomendamos que os usuários iniciantes comecem lendo as seguintes seções e as consultem conforme necessário.


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

**Example**  
**[Destaques do serviço e preços](https://aws.amazon.com/dynamodb/)**  
Oferece uma visão geral de produto do DynamoDB, casos de uso comuns, destaques do serviço e preços.  |  

**Example**  
**[Recursos do DynamoDB](https://aws.amazon.com/dynamodb/resources/)**  
Vídeos, tutoriais e orientações prescritivas que apresentam o serviço, os conceitos de modelagem de dados e os principais recursos e capacidades.  | 
|  

**Example**  
**[Introdução](GettingStartedDynamoDB.md)**  
Informações sobre como configurar o DynamoDB, criar tabelas de exemplo e fazer upload de dados.  |  

**Example**  
**[Curso básico sobre o DynamoDB](https://explore.skillbuilder.aws/learn/course/external/view/elearning/16104/amazon-dynamodb-basics)**  
Um curso digital gratuito que ensina os fundamentos do DynamoDB, como design de tabelas, tipos de dados e operações básicas.  | 
|  

**Example**  
**[DynamoDB Nuggets](https://www.youtube.com/playlist?list=PLhr1KZpdzukemNOO71Hca0GpjG0QmXwEd)**  
Tutoriais em vídeo de curta duração e específicos que explicam os principais conceitos e recursos do DynamoDB.  |  

**Example**  
**[Repositório de exemplos de código do DynamoDB](https://github.com/aws-samples/aws-dynamodb-examples)**  
Exemplos práticos de código do DynamoDB em várias linguagens de programação.  | 
|  

**Example**  
**[Treinamento gratuito no DynamoDB](https://skillbuilder.aws/learn/WC3K4Y4S5N/amazon-dynamodb-getting-started/)**  
A AWS oferece cursos digitais gratuitos que abrangem conceitos, recursos e práticas recomendadas do DynamoDB.  |  

**Example**  
**[NoSQL Workbench para DynamoDB](https://youtu.be/p5va6ZX9_o0)**  
Uma ferramenta visual unificada que oferece recursos de modelagem de dados, visualização de dados e desenvolvimento de consultas.  | 
|  

**Example**  
**[Padrões de design do DynamoDB](best-practices.md)**  
Práticas recomendadas e exemplos de modelagem de dados para diferentes casos de uso com exemplos práticos de código.  |  

**Example**  
**[Tutoriais práticos](https://aws.amazon.com/tutorials/create-nosql-table/)**  
Tutoriais passo a passo no Console de gerenciamento da AWS que orientam você em tarefas comuns do DynamoDB.  | 
|  

**Example**  
**[Migração para o DynamoDB](migration-guide.md)**  
Visão geral do processo, das ferramentas e das estratégias para migrar um banco de dados para o DynamoDB.  |  

**Example**  
**[Lentes do AWS Well-Architected para o DynamoDB](bp-wal.md)**  
Práticas recomendadas de arquitetura para projetar e operar aplicações confiáveis, seguras, eficientes e econômicas usando o DynamoDB.  | 

## Práticas recomendadas adicionais do Amazon DynamoDB para usuários iniciantes
<a name="additional-reading"></a>

Depois de completar as seções anteriores, leia estas seções:
+  **[Capacidade de throughput do DynamoDB](capacity-mode.md)** 

  Apresenta uma visão geral dos dois modos de throughput disponíveis para o DynamoDB e considerações sobre a seleção do modo de capacidade adequado para a aplicação. O modo sob demanda é a opção de throughput padrão e recomendada para a maioria das workloads do DynamoDB.
+  **[Práticas recomendadas para desenhar e arquitetar com o DynamoDB](best-practices.md)** 

  Identifique e resolva problemas para maximizar o desempenho e minimizar os custos ao trabalhar com o DynamoDB.

## AWS CLIRecursos do
<a name="new-users-aws-cli-resources"></a>

Se quiser usar a AWS Command Line Interface (AWS CLI), poderá usar estes documentos para ajudar você a começar:
+  **[AWS CLI Documentação da](https://docs.aws.amazon.com/cli/)** 

   Esta seção fornece informações sobre como baixar a AWS CLI, fazer a AWS CLI funcionar no seu sistema e fornecer suas credenciais da AWS. 
+  **[AWS CLI Documentação da para o DynamoDB](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/index.html)** 

   Esse documento separado abrange todos os aspectos da AWS CLI para comandos do DynamoDB, incluindo sintaxe e exemplos. 

## Recursos de programação
<a name="new-user-programming-resources"></a>

Você pode escrever programas de aplicação para usar a API do DynamoDB com uma variedade de linguagens de programação conhecidas. Aqui estão alguns recursos:
+  **[Ferramentas para a Amazon Web Services](https://aws.amazon.com/developer/tools/)** 

   A AWS fornece uma série de kits de desenvolvimento de software (SDKs) compatíveis com o DynamoDB. Você pode escrever código para o DynamoDB usando Java, .NET, PHP, Ruby e outras linguagens. Esses SDKs podem simplificar consideravelmente o desenvolvimento da aplicação, formatando solicitações para o DynamoDB, analisando respostas e fornecendo a lógica de repetição e o tratamento de erros. 
+  ** [Referência de API do DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/Welcome.html)**

   Se não quiser usar os SDKs da AWS, você poderá interagir com o DynamoDB diretamente usando a API do DynamoDB. Esse documento abrange todas as operações da API do DynamoDB, incluindo a sintaxe e exemplos. É possível encontrar dicas de solução de problemas e informações sobre como criar e autenticar solicitações e lidar com respostas nesta seção. 

# Acessar o DynamoDB
<a name="AccessingDynamoDB"></a>

 Você pode acessar o Amazon DynamoDB usando o Console de gerenciamento da AWS, a AWS Command Line Interface (AWS CLI) ou a API do DynamoDB.

**Topics**
+ [Utilizar o console](#ConsoleDynamoDB)
+ [Como usar o AWS CLI](#Tools.CLI)
+ [Usar a API](#Using.API)
+ [Usar o NoSQL Workbench para DynamoDB](#Using.Workbench)
+ [Intervalos de endereços IP](#Using.IPRanges)
+ [Endpoints de pilha dupla para o Protocolo de Internet versão 6 (IPv6)](#dual-stackipv4-6)

## Utilizar o console
<a name="ConsoleDynamoDB"></a>

Você pode acessar o Console de gerenciamento da AWS para Amazon DynamoDB em [https://console.aws.amazon.com/dynamodb/home](https://console.aws.amazon.com/dynamodb/home).

Aqui estão algumas das ações que você pode realizar no console do DynamoDB:
+ **Gerenciar tabelas**: crie, atualize e exclua tabelas. A calculadora de capacidade pode ajudar a estimar os requisitos de capacidade.
+ **Interagir com dados**: visualize, adicione, atualize e exclua itens das tabelas. Gerencie as configurações de vida útil (TTL).
+ **Monitorar e analisar**: visualize painéis, monitore e configure alarmes e analise métricas e alertas das tabelas do DynamoDB.
+ **Otimizar e ampliar**: gerencie índices secundários, fluxos, acionadores, capacidade reservada e outros recursos avançados para aprimorar o uso do DynamoDB.

O console do DynamoDB fornece uma interface abrangente para gerenciar os recursos do DynamoDB. Recomendamos que você acesse o console e interaja com ele para saber mais.

## Como usar o AWS CLI
<a name="Tools.CLI"></a>

 Você pode usar a AWS Command Line Interface (AWS CLI) para controlar vários serviços da AWS via linha de comando e automatizá-los usando scripts. Use o AWS CLI para operações ad hoc, como a criação de uma tabela. Ela também pode ser usada para incorporar operações do Amazon DynamoDB em scripts utilitários.

 Antes de usar a AWS CLI com o DynamoDB, você deve obter um ID de chave de acesso e uma chave de acesso secreta. Para obter mais informações, consulte [Conceder acesso programático](SettingUp.DynamoWebService.md#SettingUp.DynamoWebService.GetCredentials). 

Para obter uma lista completa de todos os comandos disponíveis para o DynamoDB na AWS CLI, consulte a [Referência de comandos da AWS CLI](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/index.html).

**Topics**

### Download e configuração da AWS CLI
<a name="Tools.CLI.DownloadingAndRunning"></a>

O AWS CLI está disponível em [http://aws.amazon.com/cli](https://aws.amazon.com/cli). Ela é executada no Windows, macOS ou Linux. Depois de fazer download da AWS CLI, siga estas etapas para instalá-la e configurá-la:

1. Acesse o [Guia do usuário do AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/).

1. Siga as instruções de [Instalação da AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/installing.html) e [Configuração da AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html).

### Como usar a AWS CLI com o DynamoDB
<a name="Tools.CLI.UsingWithDDB"></a>

O formato de linha de comando consiste em um nome de operação do DynamoDB seguido pelos parâmetros dessa operação. O AWS CLI suporta uma sintaxe abreviada para os valores de parâmetro, assim como JSON.

Por exemplo, o comando a seguir cria uma tabela chamada *Music*. A chave de partição é *Artist*, e a chave de classificação é *SongTitle*. (Para facilitar a leitura, comandos longos nesta seção são divididos em linhas separadas.)

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

Os comandos a seguir adicionam novos itens à tabela. Esses exemplos usam uma combinação de sintaxe abreviada 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
```

Na linha de comando, pode ser difícil compor um JSON válido. No entanto, a AWS CLI pode ler arquivos JSON. Por exemplo, considere o seguinte trecho de código JSON, que é armazenado em um arquivo chamado *key-conditions.json*.

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

Agora você pode emitir uma solicitação `Query` usando a AWS CLI. Neste exemplo, o conteúdo do arquivo *key-conditions.json* é usado para o parâmetro `--key-conditions`.

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

### Usar a AWS CLI com o DynamoDB local
<a name="Tools.CLI.UsingWithDDBLocal"></a>

A AWS CLI também pode interagir com o DynamoDB local (versão para download) executado no computador. Para ativar isso, adicione o parâmetro a seguir em cada comando:

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

O exemplo a seguir usa a AWS CLI para listar as tabelas em um banco de dados local.

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

Se o DynamoDB estiver usando um número de porta diferente do padrão (8000), modifique o valor `--endpoint-url` de acordo com a necessidade.

**nota**  
A AWS CLI não pode usar o DynamoDB local (versão para download) como um endpoint padrão. Portanto, você deve especificar `--endpoint-url` com cada comando. 

## Usar a API
<a name="Using.API"></a>

 Você pode usar o Console de gerenciamento da AWS e a AWS Command Line Interface para trabalhar de forma interativa com o Amazon DynamoDB. No entanto, para aproveitar ao máximo o DynamoDB, você pode escrever o código da aplicação usando os AWS SDKs.

Os SDKs da AWS oferecem amplo suporte para o DynamoDB em [ Java](https://aws.amazon.com/sdk-for-java), [JavaScript no navegador](https://aws.amazon.com/sdk-for-browser), [.NET](https://aws.amazon.com/sdk-for-net), [Node.js](https://aws.amazon.com/sdk-for-node-js), [PHP](https://aws.amazon.com/sdk-for-php), [Python](https://aws.amazon.com/sdk-for-python), [Ruby](https://aws.amazon.com/sdk-for-ruby), [C\$1\$1](https://aws.amazon.com/sdk-for-cpp), [Go](https://aws.amazon.com/sdk-for-go), [Android](https://aws.amazon.com/mobile/sdk/) e [iOS](https://aws.amazon.com/mobile/sdk/).

Antes de usar os AWS SDKs com o DynamoDB, você deve obter um ID de chave de acesso da AWS e uma chave de acesso secreta. Para obter mais informações, consulte [Configurar o DynamoDB (serviço da Web)](SettingUp.DynamoWebService.md). 

 Para obter uma visão geral de alto nível da programação de aplicações do DynamoDB com AWS SDKs, consulte [Programação com o DynamoDB e os AWS SDKs](Programming.md). 

## Usar o NoSQL Workbench para DynamoDB
<a name="Using.Workbench"></a>

Também é possível acessar o DynamoDB baixando e usando o [NoSQL Workbench para DynamoDB](workbench.md).

O NoSQL Workbench para Amazon DynamoDB é uma aplicação GUI multiplataforma do lado do cliente para operações e desenvolvimento de bancos de dados modernos. Ele está disponível para Windows, macOS e Linux. O NoSQL Workbench é uma ferramenta de desenvolvimento visual que fornece recursos de modelagem de dados, visualização de dados e desenvolvimento de consultas para ajudar você a projetar, criar, consultar e gerenciar tabelas do DynamoDB. O NoSQL Workbench agora inclui o DynamoDB local como parte opcional do processo de instalação, o que facilita a modelagem de dados no DynamoDB local. Para saber mais sobre o DynamoDB local e seus requisitos, consulte [Configurar o DynamoDB local (versão para download)](DynamoDBLocal.md).

**nota**  
No momento, o NoSQL Workbench para DynamoDB não comporta logins da AWS configurados com a autenticação de dois fatores (2FA).

**Modelagem de dados**  
Com o NoSQL Workbench para DynamoDB, você pode criar novos modelos de dados a partir de ou projetar modelos com base em modelos de dados existentes que satisfaçam os padrões de acesso a dados das suas aplicações. Pode também importar e exportar o modelo de dados designado no final do processo. Para obter mais informações, consulte [Criar modelos de dados com o NoSQL Workbench](workbench.Modeler.md).

**Criação de operação**  
O NoSQL Workbench oferece uma avançada interface gráfica do usuário para você desenvolver e testar consultas. Você pode usar o *criador de operações* para visualizar, explorar e consultar conjuntos de dados dinâmicos. Você também pode usar o criador de operações estruturadas para criar e executar operações de plano de dados. Ele oferece suporte para expressões de projeção e condição e permite que você gere código de exemplo em várias linguagens. Para obter mais informações, consulte [Explorar conjuntos de dados e criar operações com o NoSQL Workbench](workbench.querybuilder.md).

## Intervalos de endereços IP
<a name="Using.IPRanges"></a>

A Amazon Web Services (AWS) publica seus intervalos de endereços IP atuais em formato JSON. Para visualizar os intervalos atuais, faça download do arquivo [ip-ranges.json](https://ip-ranges.amazonaws.com/ip-ranges.json). Para acessar mais informações, consulte [Intervalos de endereços IP da AWS](https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html) na Referência geral da AWS.

Para encontrar os intervalos de endereços IP que podem ser usados para [acessar os índices e as tabelas do DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Operations_Amazon_DynamoDB.html), procure no arquivo ip-ranges.json a seguinte string: `"service": "DYNAMODB"`.

**nota**  
Os intervalos de endereços IP não se aplicam ao DynamoDB Streams ou ao DynamoDB Accelerator (DAX). 

## Endpoints de pilha dupla para o Protocolo de Internet versão 6 (IPv6)
<a name="dual-stackipv4-6"></a>

O DynamoDB oferece endpoints de pilha dupla compatíveis com IPv4 e IPv6. As convenções de nomenclatura de endpoints são:
+ `dynamodb.<region>.api.aws`
+ `<account-id>.ddb.<region>.api.aws`
+ `streams-dynamodb.<region>.api.aws`
+ `dax.<region>.api.aws`
+ `dynamodb-fips.<region>.api.aws`

Para ver uma lista completa de endpoints do DynamoDB e disponibilidade regional, consulte [Endpoints e cotas do Amazon DynamoDB](https://docs.aws.amazon.com/general/latest/gr/ddb.html) no *Guia de referência geral da AWS*.

Para acessar mais informações sobre como configurar a AWS CLI para usar endpoints de pilha dupla, consulte a seção [Configurar para usar endpoints de pilha dupla para todos os serviços da AWS](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-endpoints.html#endpoints-dual-stack) no *Guia da AWS Command Line Interface*.

Para acessar mais informações sobre como configurar seus clientes SDK para usar endpoints de pilha dupla, consulte o tópico [Endpoints de pilha dupla e FIPS](https://docs.aws.amazon.com/sdkref/latest/guide/feature-endpoints.html) no guia *AWS SDKs e ferramentas*.

Antes de usar o DynamoDB com IPv6, você deve atualizar seu perfil de usuário do IAM ou as políticas baseadas em recursos que você usa para a filtragem de endereços IP para incluir intervalos de endereços IPv6. As políticas de filtragem de endereços IP que não levam em conta o endereço IPv6 podem gerar problemas de acesso. Para acessar mais informações, consulte [Operadores de condição de endereço IP](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_IPAddress) no *Guia do usuário do AWS Identity and Access Management*.

## Pré-requisitos
<a name="GettingStarted.SettingUp.DynamoWebService"></a>

Antes de iniciar o tutorial do Amazon DynamoDB, saiba como acessar o DynamoDB em [Acessar o DynamoDB](AccessingDynamoDB.md). Em seguida, configure o DynamoDB por meio do serviço da web ou da versão baixada localmente em [Configurar o DynamoDB](SettingUp.md). Depois disso, continue em [Etapa 1: crie uma tabela no DynamoDB](getting-started-step-1.md).

**nota**  
Caso planeje interagir com o DynamoDB somente por meio do Console de gerenciamento da AWS, você não precisará de uma chave de acesso da AWS. Conclua as etapas em [Cadastrar-se na AWS](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html#SettingUp.DynamoWebService.SignUpForAWS) e prossiga em [Etapa 1: crie uma tabela no DynamoDB](getting-started-step-1.md).
Se você não quiser criar uma conta de nível gratuito, poderá configurar o [DynamoDB local (versão disponível para download)](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html). Em seguida, vá para [Etapa 1: crie uma tabela no DynamoDB](getting-started-step-1.md). 
Há diferenças ao trabalhar com comandos da CLI em terminais no Linux e no Windows. O guia a seguir apresenta comandos formatados para terminais do Linux (isso inclui macOS) e comandos formatados para CMD do Windows. Escolha o comando que melhor se adapta à aplicação de terminal que você está usando. 

# Configurar o DynamoDB
<a name="SettingUp"></a>

 Além do serviço da web Amazon DynamoDB, a AWS fornece uma versão disponível para download do DynamoDB que pode ser executada localmente em um computador. A versão para download é útil para desenvolver e testar código. Ela permite gravar e testar aplicações localmente sem que seja necessário acessar o serviço da web DynamoDB. 

 Os tópicos desta seção descrevem como configurar o DynamoDB (versão para download) e o serviço da Web DynamoDB. 

**Topics**
+ [Configurar o DynamoDB (serviço da Web)](SettingUp.DynamoWebService.md)
+ [Configurar o DynamoDB local (versão para download)](DynamoDBLocal.md)

# Configurar o DynamoDB (serviço da Web)
<a name="SettingUp.DynamoWebService"></a>

 Para usar o serviço da Web Amazon DynamoDB: 

1.  [Cadastre-se no AWS.](#SettingUp.DynamoWebService.SignUpForAWS) 

1.  [Obtenha uma chave de acesso da AWS](#SettingUp.DynamoWebService.GetCredentials) (usada para acessar o DynamoDB por programação). 
**nota**  
 Caso pretenda interagir com o DynamoDB somente por meio do Console de gerenciamento da AWS, você não precisará de uma chave de acesso da AWS e poderá avançar para [Utilizar o console](AccessingDynamoDB.md#ConsoleDynamoDB). 

1.  [Configure suas credenciais](#SettingUp.DynamoWebService.ConfigureCredentials) (usadas para acessar o DynamoDB por programação). 

## Como se cadastrar na AWS
<a name="SettingUp.DynamoWebService.SignUpForAWS"></a>

 Para usar o serviço DynamoDB, é necessário ter uma conta da AWS. Se você ainda não tiver uma conta, será solicitado a criar uma ao se cadastrar. Você não será cobrado por nenhum dos serviços da AWS nos quais se cadastrar, a menos que os utilize. 

**Para cadastrar-se na AWS**

1. Abra [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup).

1. Siga as instruções online.

   Parte do procedimento de inscrição envolve receber uma chamada telefônica ou uma mensagem de texto e inserir um código de verificação pelo teclado do telefone.

   Quando você se inscreve para uma Conta da AWS, um *Usuário raiz da conta da AWS* é criado. O usuário-raiz tem acesso a todos os Serviços da AWS e recursos na conta. Como prática recomendada de segurança, atribua o acesso administrativo a um usuário e use somente o usuário-raiz para executar [tarefas que exigem acesso de usuário-raiz](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks).

## Conceder acesso programático
<a name="SettingUp.DynamoWebService.GetCredentials"></a>

 Para poder acessar o DynamoDB de maneira programática ou por meio da AWS Command Line Interface (AWS CLI), você deve ter acesso programático. Você não precisa de acesso programático se planeja usar apenas o console do DynamoDB. 

Os usuários precisam de acesso programático se quiserem interagir com a AWS de fora do Console de gerenciamento da AWS. A forma de conceder acesso programático depende do tipo de usuário que está acessando a AWS.

Para conceder acesso programático aos usuários, selecione uma das seguintes opções:


****  

| Qual usuário precisa de acesso programático? | Para | Por | 
| --- | --- | --- | 
| IAM | (Recomendado) Use credenciais do console como credenciais temporárias para assinar solicitações programáticas para a AWS CLI, os AWS SDKs ou as APIs da AWS. |  Siga as instruções da interface que deseja utilizar. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 
|  Identidade da força de trabalho (Usuários gerenciados no Centro de Identidade do IAM)  | Use credenciais temporárias para assinar solicitações programáticas para a AWS CLI, os SDKs da AWS ou as APIs da AWS. |  Siga as instruções da interface que deseja utilizar. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 
| IAM | Use credenciais temporárias para assinar solicitações programáticas para a AWS CLI, os SDKs da AWS ou as APIs da AWS. | Siga as instruções em [Usar credenciais temporárias com recursos da AWS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) no Guia do usuário do IAM. | 
| IAM | (Não recomendado)Use credenciais de longo prazo para assinar solicitações programáticas para a AWS CLI, os SDKs da AWS ou as APIs da AWS. |  Siga as instruções da interface que deseja utilizar. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 

## Configurar credenciais
<a name="SettingUp.DynamoWebService.ConfigureCredentials"></a>

 Para poder acessar o DynamoDB por programação ou via AWS CLI, você deve configurar suas credenciais para habilitar a autorização para suas aplicações. 

 Há várias maneiras de fazer isso. Por exemplo, é possível criar manualmente o arquivo de credenciais para armazenar o ID da chave de acesso e a chave de acesso secreta. Também é possível usar o comando `aws configure` da AWS CLI para criar o arquivo automaticamente. Como alternativa, você pode usar variáveis de ambiente. Para obter mais informações sobre como configurar suas credenciais, consulte o guia do desenvolvedor do AWS SDK específico de programação.

 Para instalar e configurar a AWS CLI, consulte [Como usar o AWS CLI](AccessingDynamoDB.md#Tools.CLI). 

## Integração com outros serviços do DynamoDB
<a name="w2aab9c17b9c13"></a>

Você pode integrar o DynamoDB com muitos outros serviços da AWS. Para saber mais, consulte: 
+ [Usar o DynamoDB com outros serviços da AWS](OtherServices.md)
+ [CloudFormation para DynamoDB](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html)
+ [Como usar a AWS Backup com o DynamoDB](backuprestore_HowItWorksAWS.md)
+ [AWS Identity and Access Management (IAM) e DynamoDB](identity-and-access-mgmt.md)
+ [Usar o AWS Lambda com o Amazon DynamoDB](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html)

# Configurar o DynamoDB local (versão para download)
<a name="DynamoDBLocal"></a>

 Com a versão para download do Amazon DynamoDB, você pode desenvolver e testar aplicações sem acessar o serviço da Web DynamoDB. Em vez disso, o banco de dados é autossuficiente em seu computador. Quando estiver pronto para implantar a aplicação no ambiente de produção, remova o endpoint local no código e ele apontará para o serviço da Web DynamoDB. 

 Essa versão local ajuda você a economizar em throughput, armazenamento de dados e taxas de transferência de dados. Além disso, você não precisa ter uma conexão com a Internet ao desenvolver a aplicação. 

 O DynamoDB local está disponível como [download](DynamoDBLocal.DownloadingAndRunning.md#DynamoDBLocal.DownloadingAndRunning.title) (requer JRE), como [dependência do Apache Maven](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html#apache-maven) ou como [imagem do Docker](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html#docker). 

 Se você preferir usar o serviço da Web Amazon DynamoDB, consulte [Configurar o DynamoDB (serviço da Web)](SettingUp.DynamoWebService.md). 

**Topics**
+ [Implantar o DynamoDB localmente no computador](DynamoDBLocal.DownloadingAndRunning.md)
+ [Observações sobre o uso do DynamoDB local](DynamoDBLocal.UsageNotes.md)
+ [Histórico de versões do DynamoDB local](DynamoDBLocalHistory.md)
+ [Telemetria no DynamoDB local](DynamoDBLocalTelemetry.md)

# Implantar o DynamoDB localmente no computador
<a name="DynamoDBLocal.DownloadingAndRunning"></a>

**nota**  
O DynamoDB local está disponível em três versões: v3.x (atual), v2.x (legada) e v1.x (obsoleta).
O DynamoDB v3.x é recomendado para seu uso local em testes e desenvolvimento.
A migração do DynamoDB local V2.x para a V3.x requer a atualização das instruções de importação de `com.amazonaws.services.dynamodbv2` para `software.amazon.dynamodb` e a atualização das dependências do Maven para usuários do Maven.
Se você estiver migrando um aplicativo que usa o SDK para Java v1.x para o SDK para Java 2.x, siga as etapas para [AWS SDK para Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/migration.html).

## Baixar o DynamoDB local
<a name="DynamoDBLocal.DownloadingAndRunning.V2"></a>

Siga estas etapas para configurar e executar o DynamoDB em seu computador.

**Para configurar o DynamoDB em seu computador**

1. Baixe o DynamoDB local gratuitamente de um dos locais a seguir.  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html)
**Importante**  
 Para executar o DynamoDB v2.6.0 ou posterior no computador, é necessário ter o Ambiente de Execução Java (JRE) versão 17.x ou mais recente instalado. A aplicação não é executada em versões mais antigas do JRE.

1.  Depois de fazer download do arquivo, extraia o conteúdo e copie o diretório extraído para um local de sua escolha. 

1.  Para iniciar o DynamoDB em seu computador, abra uma janela de prompt de comando, vá para o diretório onde você extraiu o arquivo `DynamoDBLocal.jar` e insira o comando seguir. 

   ```
   java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb
   ```
**nota**  
 Se estiver usando o Windows PowerShell, inclua o nome do parâmetro ou todo o nome e valor da seguinte forma:   
 ` java -D"java.library.path=./DynamoDBLocal_lib" -jar DynamoDBLocal.jar `   
 O DynamoDB processa as solicitações de entrada até que você o interrompa. Para interromper o DynamoDB, pressione Ctrl\$1C no prompt de comando.   
 O DynamoDB usa a porta 8000 por padrão. Se a porta 8000 estiver indisponível, este comando lançará uma exceção. Para obter uma lista completa das opções de tempo de execução do DynamoDB, incluindo `-port`, execute este comando.   
 ` java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -help ` 

1. Para poder acessar o DynamoDB por programação ou via AWS Command Line Interface (AWS CLI), você deve configurar suas credenciais para habilitar a autorização para suas aplicações. O DynamoDB para download requer que todas as credenciais funcionem, conforme mostrado no exemplo a seguir. 

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

    Você pode usar o comando `aws configure` da AWS CLI para configurar credenciais. Para obter mais informações, consulte [Como usar o AWS CLI](AccessingDynamoDB.md#Tools.CLI). 

1.  Comece a escrever aplicações. Para acessar o DynamoDB em execução local com a AWS CLI, use o parâmetro `--endpoint-url `. Por exemplo, use o comando a seguir para listar as tabelas do DynamoDB. 

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

## Executar o DynamoDB local como imagem do Docker
<a name="DynamoDBLocal.DownloadingAndRunning.Docker"></a>

 A versão para download do Amazon DynamoDB está disponível como uma imagem do Docker. Para obter mais informações, consulte [dynamodb-local](https://hub.docker.com/r/amazon/dynamodb-local). Para ver a versão do DynamoDB local atual, execute o seguinte comando:

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

 Para obter um exemplo de uso do DynamoDB local como parte de um aplicativo REST criado com a AWS Serverless Application Model (AWS SAM), consulte [Aplicação SAM do DynamoDB para gerenciamento de pedidos](https://github.com/aws-samples/aws-sam-java-rest). Esta aplicação de exemplo demonstra como usar o DynamoDB local para testes. 

 Se você quiser executar uma aplicação de vários contêineres que também use o contêiner local do DynamoDB, use o Docker Compose para definir e executar todos os serviços em sua aplicação, incluindo o DynamoDB local. 

**Para instalar e executar o DynamoDB local com o Docker Compose:**

1.  Baixe e instale a [área de trabalho do Docker](https://www.docker.com/products/docker-desktop). 

1.  Copie o código a seguir em um arquivo e salve-o como `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 desejar que sua aplicação e o DynamoDB local estejam em contêineres separados, use o arquivo yaml a seguir. 

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

    Este script docker-compose.yml cria um contêiner `app-node` e um contêiner `dynamodb-local`. O script executa um comando no contêiner `app-node` que usa a AWS CLI para se conectar ao contêiner `dynamodb-local` e descreve os limites da conta e da tabela. 

    Para usar com sua própria imagem de aplicação, substitua o valor `image` no exemplo abaixo pelo valor da sua aplicação. 

   ```
   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**  
 Os scripts YAML exigem que você especifique uma chave de acesso da AWS e uma chave secreta da AWS, mas elas não precisam ser chaves válidas da AWS para acessar o DynamoDB local. 

1.  Execute o seguinte comando a linha de comando: 

   ```
   docker-compose up
   ```

## Executar o DynamoDB local como dependência do Apache Maven
<a name="DynamoDBLocal.DownloadingAndRunning.Maven.v2"></a>

**nota**  
Se você estiver migrando um aplicativo que usa o SDK para Java v1.x para o SDK para Java 2.x, siga as etapas para [AWS SDK para Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/migration.html).

 Siga estas etapas para usar o Amazon DynamoDB em sua aplicação como uma dependência. 

**Para implantar o DynamoDB como um repositório do Apache Maven**

1.  Faça download do Apache Maven e instale-o. Para obter mais informações, consulte [Download do Apache Maven](https://maven.apache.org/download.cgi) e [Instalação do Apache Maven](https://maven.apache.org/install.html). 

1.  Adicione o repositório Maven do DynamoDB ao arquivo Project Object Model (POM) da sua aplicação. 

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

    Exemplo de modelo para uso com o Spring Boot 3 e/ou Spring Framework 6: 

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

## Executar o DynamoDB localmente no AWS CloudShell
<a name="DynamoDBLocal.DynamoDB.Local.CloudShell"></a>

AWS CloudShell O é um shell pré-autenticado baseado em navegador que você pode iniciar diretamente do Console de gerenciamento da AWS. Você pode navegar até o AWS CloudShell por meio do Console de gerenciamento da AWS de maneiras diferentes. Para obter mais informações, consulte [Conceitos básicos do AWS CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/getting-started.html).

Siga estas etapas para executar o DynamoDB localmente no AWS CloudShell em qualquer lugar do Console de gerenciamento da AWS. 

**Como executar o DynamoDB localmente no AWS CloudShell por meio do Console de gerenciamento da AWS**

1. Inicie o AWS CloudShell por meio da interface do console, escolhe uma Região da AWS disponível e alterne para o shell de sua preferência; por exemplo, Bash, PowerShell ou shell Z.

1. Para escolher uma Região da AWS para trabalhar, acesse o menu **Selecionar uma região** e escolha uma [Região da AWS compatível](https://docs.aws.amazon.com/cloudshell/latest/userguide/supported-aws-regions.html). (As regiões disponíveis estão em destaque.)

1. Por meio do Console de gerenciamento da AWS, é possível iniciar o AWS CloudShell escolhendo uma das opções a seguir:

   1. Na barra de navegação, escolha o ícone **AWS CloudShell**.

   1. Na caixa **Pesquisar**, insira a palavra CloudShell e escolha **CloudShell**.

   1. No widget **Visitado recentemente**, escolha **CloudShell**.

   1. Na barra de ferramentas do console, escolha **CloudShell**.

1. Para executar o DynamoDB localmente no AWS CloudShell, você pode usar o alias `dynamodb-local`. É possível especificar outras opções de linha de comando para alterar as configurações locais do DynamoDB. Consulte [Observações sobre o uso do DynamoDB local](DynamoDBLocal.UsageNotes.md) para obter as opções disponíveis.
**nota**  
Para executar o DynamoDB localmente em segundo plano, execute o DynamoDB localmente no AWS CloudShell usando `dynamodb-local &`.

1. Para acessar o DynamoDB em execução local no AWS CloudShell, use o parâmetro `--endpoint-url`. Por exemplo, use o seguinte comando para listar tabelas do DynamoDB:

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

Para ver um exemplo de projeto de amostra que mostra várias abordagens para configurar e usar o DynamoDB local, inclusive baixar arquivos JAR, executá-lo como uma imagem do Docker e usá-lo como uma dependência do Maven, consulte [DynamoDB Local Sample Java Project](https://github.com/awslabs/amazon-dynamodb-local-samples/tree/main).

# Observações sobre o uso do DynamoDB local
<a name="DynamoDBLocal.UsageNotes"></a>

 Com exceção do endpoint, as aplicações que são executadas com a versão para download do Amazon DynamoDB também devem funcionar com o serviço da Web do DynamoDB. No entanto, ao usar o DynamoDB localmente, você deve estar ciente do seguinte: 
+  Se você usar a opção `-sharedDb`, o DynamoDB criará um único arquivo de banco de dados chamado *shared-local-instance.db*. Todos os programas que se conectam ao DynamoDB acessam este arquivo. Se você excluir o arquivo, perderá todos os dados armazenados nele. 
+  Se você omitir `-sharedDb`, o arquivo do banco de dados se chamará *myaccesskeyid\$1region.db*, com o ID de chave de acesso AWS e região da AWS da forma como são exibidos na configuração da aplicação. Se você excluir o arquivo, perderá todos os dados armazenados nele. 
+  Se você usar a opção `-inMemory`, o DynamoDB não gravará nenhum arquivo de banco de dados. Em vez disso, todos os dados são gravados na memória, e eles não são salvos quando o DynamoDB é terminado. 
+  Se você usar `-inMemory`, a opção `-sharedDb` também será necessária. 
+  Se você usar a opção `-optimizeDbBeforeStartup`, também deverá especificar o parâmetro `-dbPath` para que o DynamoDB possa encontrar seu arquivo de banco de dados. 
+  Os AWS SDKs para DynamoDB exigem que a configuração da sua aplicação especifique um valor de chave de acesso e um valor de região da AWS. A menos que você esteja usando a opção `-sharedDb` ou `-inMemory`, o DynamoDB usará esses valores para nomear o arquivo de banco de dados local. Esses não precisam ser valores válidos da AWS para executar localmente. No entanto, pode ser conveniente usar valores válidos, de modo que você possa executar o código na nuvem mais tarde alterando o endpoint que você está usando. 
+  O DynamoDB local sempre retorna nulo para `billingModeSummary.` 
+  O DynamoDB local `AWS_ACCESS_KEY_ID` pode conter somente letras (A-Z, a-z) e números (0-9). 
+ O DynamoDB local não comporta [recuperação para um ponto no tempo (PITR)](Point-in-time-recovery.md).

**Topics**
+ [Opções de linha de comando](#DynamoDBLocal.CommandLineOptions)
+ [Definir o endpoint local](#DynamoDBLocal.Endpoint)
+ [Diferenças entre o DynamoDB para download e o serviço da Web DynamoDB](#DynamoDBLocal.Differences)

## Opções de linha de comando
<a name="DynamoDBLocal.CommandLineOptions"></a>

 Você pode usar uma das seguintes opções de linha de comando com a versão para download do DynamoDB: 
+  `-cors` `value`: habilita o suporte ao CORS (compartilhamento de recursos entre origens) para JavaScript. Você deve fornecer uma lista de “permissões” de domínios específicos separados por vírgulas. A configuração padrão de `-cors` é um asterisco (\$1), que permite acesso público. 
+  `-dbPath` `value`: o diretório em que o DynamoDB grava seu arquivo de banco de dados. Se você não especificar essa opção, o arquivo será gravado no diretório atual. Não é possível especificar `-dbPath` e `-inMemory` ao mesmo tempo. 
+  `-delayTransientStatuses`: faz com que o DynamoDB introduza atrasos em determinadas operações. O DynamoDB (versão para download) pode executar algumas tarefas quase instantaneamente, como criar/atualizar/excluir operações em tabelas e índices. No entanto, o serviço DynamoDB requer mais tempo para essas tarefas. A definição desse parâmetro ajuda o DynamoDB em execução em seu computador a simular o comportamento do serviço da Web DynamoDB de maneira mais precisa. (No momento, esse parâmetro apresenta atrasos apenas para índices secundários globais que estão no status *CREATING* ou *DELETING*.) 
+  `-help`: imprime um resumo de uso e opções. 
+  `-inMemory`: o DynamoDB é executado na memória, em vez de usar um arquivo de banco de dados. Quando você interrompe o DynamoDB, nenhum dos dados é salvo. Não é possível especificar `-dbPath` e `-inMemory` ao mesmo tempo. 
+  `-optimizeDbBeforeStartup`: otimiza as tabelas de banco de dados subjacentes antes de iniciar o DynamoDB no seu computador. Você também deve especificar `-dbPath` ao usar este parâmetro. 
+  `-port` `value`: o número da porta que o DynamoDB usa para se comunicar com sua aplicação. Se você não especificar essa opção, a porta padrão será `8000`. 
**nota**  
 O DynamoDB usa a porta 8000 por padrão. Se a porta 8000 estiver indisponível, este comando lançará uma exceção. Você pode usar a opção `-port` para especificar um número de porta diferente. Para obter uma lista completa das opções de tempo de execução do DynamoDB, incluindo `-port`, digite este comando:   
 `java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -help` 
+  `-sharedDb`: se você especificar `-sharedDb`, o DynamoDB usará um único arquivo de banco de dados, em vez de usar arquivos separados para cada credencial e região. 
+  `-disableTelemetry`: quando especificada, o DynamoDB local não enviará nenhuma telemetria. 
+ `-version`: imprime a versão do DynamoDB local.

## Definir o endpoint local
<a name="DynamoDBLocal.Endpoint"></a>

 Por padrão, os AWS SDKs e as ferramentas usam endpoints para o serviço da Web Amazon DynamoDB. Para usar os SDKs e as ferramentas com as versões para download do DynamoDB, especifique o endpoint local: 

 `http://localhost:8000` 

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

 Você pode usar a AWS Command Line Interface (AWS CLI) para interagir com o DynamoDB para download. 

 Para acessar o DynamoDB em execução localmente, use o parâmetro `--endpoint-url`. Veja a seguir um exemplo de uso da AWS CLI para listar as tabelas do DynamoDB em seu computador. 

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

**nota**  
 A AWS CLI não pode usar a versão para download do DynamoDB como um endpoint padrão. Portanto, você deve especificar `--endpoint-url` com cada comando na AWS CLI. 

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

 A maneira como você especifica um endpoint depende da linguagem de programação e do AWS SDK que você está usando. As seções a seguir descrevem como fazer isso: 
+  [Java: configurar a região e o endpoint da AWS](CodeSamples.Java.md#CodeSamples.Java.RegionAndEndpoint) (DynamoDB local oferece suporte ao AWS SDK para Java V1 e V2) 
+ CodeSamples.Java.RegionAndEndpoint [.NET: configurar a região e o endpoint da AWS](CodeSamples.DotNet.md#CodeSamples.DotNet.RegionAndEndpoint) 

## Diferenças entre o DynamoDB para download e o serviço da Web DynamoDB
<a name="DynamoDBLocal.Differences"></a>

 A versão para download do DynamoDB deve ser usada somente para testes e desenvolvimento. Em comparação, o serviço da Web DynamoDB é um serviço gerenciado com recursos de escalabilidade, disponibilidade e durabilidade que o tornam ideal para uso no ambiente de produção. 

 A versão para download do DynamoDB difere do serviço da Web das seguintes formas: 
+ Regiões da AWS e Contas da AWS distintas não são aceitas em nível de cliente. 
+  As configurações de throughput provisionado são ignoradas no DynamoDB para download, embora a operação `CreateTable` as exija. Em `CreateTable`, você pode especificar quaisquer números desejados para o throughput de leitura e gravação provisionado, mesmo que esses números não sejam usados. Você pode chamar `UpdateTable` quantas vezes quiser por dia. No entanto, todas as alterações nos valores do throughput provisionado são ignoradas. 
+  `Scan`As operações são executadas sequencialmente. Verificações paralelas não são aceitas. Os parâmetros `Segment` e `TotalSegments` da operação `Scan` são ignorados. 
+  A velocidade das operações de leitura e gravação nos dados da tabela é limitada apenas pela velocidade do computador. As operações `CreateTable`, `UpdateTable` e `DeleteTable` ocorrem imediatamente, e o estado da tabela é sempre ACTIVE. As operações `UpdateTable` que alteram apenas as configurações de throughput provisionado em tabelas ou índices secundários globais ocorrem imediatamente. Se uma operação `UpdateTable` criar ou excluir qualquer índice secundário global, esses índices farão uma transição pelos estados normais (como CREATING e DELETING, respectivamente) antes de passarem para um estado ACTIVE. A tabela permanece no estado ACTIVE durante esse tempo. 
+  As operações de leitura são eventualmente consistentes. No entanto, devido à velocidade do DynamoDB em execução no local no computador, a maioria das leituras parecerão ser fortemente consistentes. 
+  As métricas de coleção de itens e os tamanhos de coleção de itens não são controlados. Nas respostas de operação, nulos são retornados em vez de métricas de coleção de itens. 
+  No DynamoDB, há um limite de 1 MB em dados retornados por conjunto de resultados. Tanto o serviço da Web DynamoDB quanto a versão para download impõem esse limite. No entanto, ao consultar um índice, o serviço DynamoDB calcula apenas o tamanho da chave e dos atributos projetados. Por outro lado, a versão para download do DynamoDB calcula o tamanho do item inteiro. 
+  Se você estiver usando o DynamoDB Streams, a taxa na qual fragmentos são criados poderá ser diferente. No serviço da Web DynamoDB, o comportamento de criação de fragmentos é parcialmente influenciado pela atividade da partição da tabela. Quando o DynamoDB é executado localmente, não há particionamento de tabelas. Em qualquer um dos casos, os fragmentos são efêmeros, portanto, seu aplicativo não deve ser dependente do comportamento do fragmento. 
+  `TransactionConflictExceptions` não são lançadas pelo DynamoDB para download para APIs transacionais. Recomendamos o uso de um framework de imitação Java para simular `TransactionConflictExceptions` no manipulador do DynamoDB para testar como o aplicativo responde a transações em conflito. 
+  No serviço web do DynamoDB, quer seja acessado pelo console ou pela AWS CLI, os nomes das tabelas diferenciam maiúsculas de minúsculas. Uma tabela chamada `Authors` e outra chamada `authors` podem existir como tabelas separadas. Na versão que pode ser obtida por download, os nomes de tabelas não diferenciam maiúsculas de minúsculas, e a criação dessas duas tabelas resulta em erro. 
+ A marcação não é aceita na versão para download do DynamoDB.
+ A versão para download do DynamoDB ignora o parâmetro [Limit](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ExecuteStatement.html#DDB-ExecuteStatement-request-Limit) em [ExecuteStatement](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ExecuteStatement.html).

# Histórico de versões do DynamoDB local
<a name="DynamoDBLocalHistory"></a>

A tabela a seguir descreve as alterações importantes em cada versão do *DynamoDB local*.


****  

| Versão | Alteração | Descrição | Data | 
| --- | --- | --- | --- | 
| 3.3.0 |  Adição de suporte a chaves de vários atributos para índices secundários globais.  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  19 de janeiro de 2026  | 
| 3.2.0 |  Problemas de compatibilidade corrigidos com várias versões do Kotlin.  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  9 de janeiro de 2026  | 
| 3.1.0 |  Melhoria da performance das consultas PartiQL, incluindo a dependência do horário do Joda.  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  14 de setembro de 2025  | 
| 3.0.0 |  Migrar de SDK da AWS Java V1 para V2  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  17 de julho de 2025  | 
| 2.6.0 |  Suporte ao ARN da tabela como nome de tabela nas APIs do DynamoDB Correção de performance e atualizações de segurança  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  13 de março de 2025  | 
| 2.5.4 |  Atualização para as dependências do Jetty  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  12 de dezembro de 2024  | 
| 2.5.3 |  Atualizar as dependências do Jackson para 2.17.x no Log4j Core (Resolve CVE-2022-1471)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  6 de novembro de 2024  | 
| 2.5.2 | Correção de bug para o fluxo de trabalho de atualização de tabela | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  | 20 de junho de 2024 | 
| 2.5.1 | Patch para bugs introduzidos no recurso OndemandThroughPut  | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html) | 5 de junho de 2024 | 
| 2.5.0 |  Suporte a throughput máximo configurável para tabelas sob demanda, `ReturnValuesOnConditionCheckFailure`, `BatchExecuteStatement` e `ExecuteTransactionRequest`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  28 de maio de 2024  | 
| 2.4.0 |  Suporte para `ReturnValuesOnConditionCheckFailure`: modo incorporado  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  17 de abril de 2024  | 
| 2.3.0 |  Atualização do Jetty e do JDK  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  14 de março de 2024  | 
| 2.2.0 |  Foi adicionada compatibilidade com a proteção contra exclusão de tabelas e o parâmetro `ReturnValuesOnConditionCheckFailure`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  14 de dezembro de 2023  | 
| 2.1.0 |  Suporte para bibliotecas nativas SQLite para projetos Maven e adição de telemetria  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  23 de outubro de 2023  | 
| 2.0.0 |  Migração do namespace javax para jakarta e suporte ao JDK11  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  5 de julho de 2023  | 
| 1.25.1 |  Atualizar as dependências do Jackson para 2.17.x no Log4j Core (Resolve CVE-2022-1471)  |  Atualizar as dependências do Jackson para 2.17.x no Log4j Core (Resolve CVE-2022-1471) para resolver uma vulnerabilidade crítica de segurança na biblioteca SnakeYAML, que é uma dependência transitiva  |  6 de novembro de 2024  | 
| 1.25.0 |  Foi adicionada compatibilidade com a proteção contra exclusão de tabelas e o parâmetro `ReturnValuesOnConditionCheckFailure`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  18 de dezembro de 2023  | 
| 1.24.0 |  Suporte para bibliotecas nativas SQLite para projetos Maven e adição de telemetria  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  23 de outubro de 2023  | 
| 1.23.0 |  Tratamento do acesso inválido e da chave secreta durante a inicialização do servidor  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  28 de junho de 2023  | 
| 1.22.0 |  Compatibilidade com a operação de limite para PartiQL  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  8 de junho de 2023  | 
| 1.21.0 |  Suporte para 100 ações por transação  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  26 de janeiro de 2023  | 
| 1.20.0 |  Adição de suporte para Mac M1  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  12 de setembro de 2022  | 
| 1.19.0 |  Atualização do PartiQL Parser  |  Atualização do PartiQL Parser e de outras bibliotecas relacionadas  |  27 de julho de 2022  | 
| 1.18.0 | Atualização do Log4j-core e Jackson-core | Atualização do Log4j-core para 2.17.1 e do Jackson-core 2.10.x para 2.12.0 | 10 de janeiro de 2022 | 
| 1.17.2 | Atualização do log4j-core | Atualização da dependência do log4j-core para a versão 2.16 | 16 de janeiro de 2021 | 
| 1.17.1 | Atualização do log4j-core | Atualização da dependência do log4j-core para corrigir a exploração de dia zero e evitar a execução remota de código (Log4Shel) | 10 de janeiro de 2023 | 
| 1.17.0 | Descontinuação do Javascript Web Shell |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  | 8 de janeiro de 2021 | 

# Telemetria no DynamoDB local
<a name="DynamoDBLocalTelemetry"></a>

 Na AWS, para desenvolver e lançar serviços usamos o que aprendemos nas interações com os clientes e usamos o feedback deles para iterar nossos produtos. Telemetria são informações adicionais que nos ajudam a entender melhor as necessidades dos clientes, diagnosticar problemas e fornecer recursos que aprimoram a experiência do cliente. 

 O DynamoDB local coleta telemetria, como métricas genéricas de uso, informações sobre sistemas e ambientes e erros. Para obter detalhes sobre os tipos de telemetria coletados, consulte [Tipos de informação coletados](#DynamoDBLocalTelemetry.TypesOfInformationCollected). 

 O DynamoDB local não coleta informações pessoais, como nomes de usuário ou endereços de e-mail. Ele também não extrai informações sigilosas em nível de projeto. 

 Como cliente, você controla se a telemetria está ativada e pode alterar as configurações a qualquer momento. Se a telemetria permanecer ativada, o DynamoDB local enviará dados de telemetria em segundo plano sem exigir nenhuma interação adicional com o cliente. 

## Desative a telemetria usando as opções da linha de comando
<a name="DynamoDBLocalTelemetry.cli"></a>

 Você pode desativar a telemetria por meio das opções de linha de comando ao iniciar o DynamoDB local usando a opção `-disableTelemetry`. Para obter mais informações, consulte [Opções de linha de comando](DynamoDBLocal.UsageNotes.md#DynamoDBLocal.CommandLineOptions).

## Desative a telemetria de uma única sessão
<a name="DynamoDBLocalTelemetry.TurnOffTelemetrySingleSession"></a>

 Nos sistemas operacionais macOS e Linux, você pode desativar a telemetria de uma única sessão. Para desativar a telemetria da sessão atual, execute o comando a seguir a fim de definir a variável de ambiente `DDB_LOCAL_TELEMETRY` como `false`. Repita o comando para cada novo terminal ou sessão. 

```
export DDB_LOCAL_TELEMETRY=0
```

## Desative a telemetria do seu perfil em todas as sessões
<a name="DynamoDBLocalTelemetry.TurnOffTelemetryForAllSessions"></a>

 Execute os comandos a seguir para desativar a telemetria de todas as sessões quando você estiver executando o DynamoDB local no sistema operacional. 

**Para desabilitar a telemetria no Linux**

1.  Execute: 

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

1.  Execute: 

   ```
   source ~/.profile
   ```

**Para desabilitar a telemetria no macOS**

1.  Execute: 

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

1.  Execute: 

   ```
   source ~/.profile
   ```

**Para desabilitar a telemetria no Windows**

1.  Execute: 

   ```
   setx DDB_LOCAL_TELEMETRY 0
   ```

1.  Execute: 

   ```
   refreshenv
   ```

## Desativar a telemetria usando o DynamoDB local incorporado em projetos Maven
<a name="DynamoDBLocalTelemetry.maven"></a>

 Você pode desativar a telemetria usando o DynamoDB local incorporado em projetos Maven. 

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

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

## Tipos de informação coletados
<a name="DynamoDBLocalTelemetry.TypesOfInformationCollected"></a>
+  **Informações de uso**: telemetria genérica, como início/parada do servidor e a API ou operação chamada. 
+  **Informações do sistema e do ambiente**: a versão Java, o sistema operacional (Windows, Linux ou macOS), o ambiente no qual o DynamoDB local é executado (por exemplo, JAR independente, contêiner do Docker ou como dependência do Maven) e valores de hash dos atributos de uso. 

## Saiba mais
<a name="DynamoDBLocalTelemetry.LearnMore"></a>

 Os dados de telemetria que o DynamoDB local coleta seguem as políticas de privacidade de dados da AWS. Para obter mais informações, consulte as informações a seguir. 
+  [Termos de serviço da AWS](https://aws.amazon.com/service-terms/) 
+  [Perguntas frequentes sobre privacidade de dados](https://aws.amazon.com/compliance/data-privacy-faq/) 

# Etapa 1: crie uma tabela no DynamoDB
<a name="getting-started-step-1"></a>

Nesta etapa, você criará uma tabela `Music` no Amazon DynamoDB. Essa tabela tem os seguintes detalhes:
+ Chave de partição: `Artist`
+ Chave de classificação: `SongTitle`

Para obter mais informações sobre operações em tabelas, consulte [Trabalhar com tabelas e dados no DynamoDB](WorkingWithTables.md). 

**nota**  
Antes de começar, siga as etapas em [Pré-requisitos](GettingStartedDynamoDB.md#GettingStarted.SettingUp.DynamoWebService).

## Console de gerenciamento da AWS
<a name="getting-started-step-1-Console"></a>

Para criar uma tabela `Music` usando o console do DynamoDB:

1. Faça login no Console de gerenciamento da AWS e abra o console do DynamoDB em [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/).

1. No painel de navegação à esquerda, selecione **Tables (Tabelas)**. 

1. Escolha **Criar tabela**.

1. Insira os **Detalhes da tabela** da seguinte forma:

   1. Em **Table name** (Nome da tabela), insira **Music**.

   1. Em **Partition key**, (Chave de partição), insira **Artist**.

   1. Em **Chave de classificação**, insira **SongTitle**.

1. Em **Configurações de tabela**, mantenha a seleção padrão de **Configurações padrão**.

1. Selecione **Criar tabela** para criar a tabela.  
![\[A página Criar tabela com os detalhes da tabela preenchidos.\]](http://docs.aws.amazon.com/pt_br/amazondynamodb/latest/developerguide/images/GettingStarted/CreateTableMusic.png)

1. Quando a tabela está no status `ACTIVE`, é prática recomendada habilitar [Backups para um ponto no tempo do DynamoDB](Point-in-time-recovery.md) na tabela realizando as seguintes etapas:

   1. Selecione no nome da tabela para abri-la.

   1. Escolha **Backups**.

   1. Selecione **Editar** na seção **Recuperação em um ponto anterior no tempo (PITR**).

   1. Na seção **Editar configurações de recuperação a um ponto no tempo**, selecione **Ativar a recuperação para um ponto no tempo**.

   1. Escolha **Salvar alterações**.

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

O exemplo da AWS CLI a seguir cria uma nova tabela `Music` usando `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
```

**CMD do Windows**

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

O uso de `create-table` retorna o seguinte resultado de exemplo.

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

Observe que o valor do campo `TableStatus` está definido como `CREATING`.

Para verificar se o DynamoDB terminou de criar a tabela `Music`, use o comando `describe-table`. 

**Linux**

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

**CMD do Windows**

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

Esse comando retorna o seguinte resultado. Quando o DynamoDB conclui a criação da tabela, o valor do campo `TableStatus` é definido como `ACTIVE`. 

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

Quando a tabela está no status `ACTIVE`, é uma prática recomendada habilitar [Backups para um ponto no tempo do DynamoDB](Point-in-time-recovery.md) na tabela executando o comando a seguir.

**Linux**

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

**CMD do Windows**

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

Esse comando retorna o seguinte resultado.

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

**nota**  
Há implicações de custo para a habilitação de backups contínuos com PITR. Para obter informações sobre preços, consulte [Definição de preço do Amazon DynamoDB](https://aws.amazon.com/dynamodb/pricing).

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

Os exemplos de código a seguir mostram como criar uma tabela do DynamoDB usando um AWS SDK.

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

**SDK para .NET (v4)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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;
        }
    }
```
+  Consulte detalhes da API em [CreateTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/CreateTable) na *Referência da API AWS SDK para .NET*. 

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

**AWS CLI com script Bash**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
}
```
As funções utilitárias usadas neste exemplo.  

```
###############################################################################
# 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
}
```
+  Consulte detalhes da API em [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable) na *Referência de comandos da AWS CLI*. 

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

**SDK para C\$1\$1**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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);
}
```
Código que aguarda a tabela se tornar ativa.  

```
//! 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;
}
```
+  Consulte detalhes da API em [CreateTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/CreateTable) na *Referência da API AWS SDK para C\$1\$1*. 

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

**AWS CLI**  
**Exemplo 1: como criar uma tabela com tags**  
O exemplo de `create-table` a seguir usa os atributos especificados e o esquema de chaves para criar uma tabela chamada `MusicCollection`. Essa tabela usa um throughput provisionado e é criptografada em repouso usando a CMK de propriedade padrão da AWS. O comando também aplica uma tag à tabela, com uma chave `Owner` e valor de `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
```
Resultado:  

```
{
    "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"
    }
}
```
Para obter mais informações, consulte [Operações básicas nas tabelas](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 2: como criar uma tabela no modo sob demanda**  
O exemplo a seguir cria uma tabela chamada `MusicCollection` usando o modo sob demanda, em vez do modo de throughput provisionado. Esse método é útil para tabelas com workloads imprevisíveis.  

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

```
{
    "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"
        }
    }
}
```
Para obter mais informações, consulte [Operações básicas nas tabelas](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 3: como criar uma tabela e criptografá-la com uma CMK gerenciada pelo cliente**  
O exemplo a seguir cria uma tabela chamada `MusicCollection` e a criptografa usando uma CMK gerenciada pelo cliente.  

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

```
{
    "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"
        }
    }
}
```
Para obter mais informações, consulte [Operações básicas nas tabelas](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 4: como criar uma tabela com um índice secundário local**  
O exemplo a seguir usa os atributos especificados e o esquema de chaves para criar uma tabela chamada `MusicCollection` com um índice secundário local chamado `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\"]
                }
            }
        ]"
```
Resultado:  

```
{
    "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"
            }
        ]
    }
}
```
Para obter mais informações, consulte [Operações básicas nas tabelas](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 5: como criar uma tabela com um índice secundário global**  
O exemplo a seguir cria uma tabela chamada `GameScores` com um índice secundário global chamado `GameTitleIndex`. A tabela-base tem uma chave de partição `UserId` e uma chave de classificação `GameTitle`, permitindo que você encontre a melhor pontuação de um usuário individual para um jogo específico de forma eficiente, enquanto o GSI tem uma chave de partição `GameTitle` e uma chave de classificação `TopScore`, permitindo que você encontre rapidamente a pontuação mais alta geral para um jogo específico.  

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

```
{
    "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"
            }
        ]
    }
}
```
Para obter mais informações, consulte [Operações básicas nas tabelas](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 6: como criar uma tabela com vários índices secundários globais ao mesmo tempo**  
O exemplo a seguir cria uma tabela chamada `GameScores` com dos índices secundários globais. Os esquemas do GSI são passados por meio de um arquivo, e não pela linha de 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
```
Conteúdo de `gsi.json`:  

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

```
{
    "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"
            }
        ]
    }
}
```
Para obter mais informações, consulte [Operações básicas nas tabelas](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 7: como criar uma tabela com o Streams habilitado**  
O exemplo a seguir cria uma tabela chamada `GameScores` com o DynamoDB Streams habilitado. Imagens novas e antigas de cada item serão gravadas no fluxo.  

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

```
{
    "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"
    }
}
```
Para obter mais informações, consulte [Operações básicas nas tabelas](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 8: como criar uma tabela com o fluxo somente de chaves habilitado**  
O exemplo a seguir cria uma tabela chamada `GameScores` com o DynamoDB Streams habilitado. Somente os atributos-chave dos itens modificados são gravados no fluxo.  

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

```
{
    "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
    }
}
```
Para obter mais informações, consulte [Captura de dados de alterações com o Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 9: como criar uma tabela com a classe Standard-Infrequent Access**  
O exemplo a seguir cria uma tabela chamada `GameScores` e atribui a classe de tabela Standard-Infrequent Access (DynamoDB Standard-IA). Essa classe de tabela é otimizada para que o armazenamento seja o custo dominante.  

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

```
{
    "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
    }
}
```
Para obter mais informações, consulte [Classes de tabela](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.TableClasses.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 10: como criar uma tabela com a proteção contra exclusão habilitada**  
O exemplo a seguir cria uma tabela chamada `GameScores` e habilita a proteção contra exclusão.  

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

```
{
    "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
    }
}
```
Para obter mais informações, consulte [Usar a proteção contra exclusão](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeletionProtection) no *Guia do desenvolvedor do Amazon DynamoDB*.  
+  Consulte detalhes da API em [CreateTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/create-table.html) na *Referência de comandos da AWS CLI*. 

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

**SDK para Go V2**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
}
```
+  Consulte detalhes da API em [CreateTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.CreateTable) na *Referência da API AWS SDK para Go*. 

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

**SDK para Java 2.x**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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 "";
    }
}
```
+  Consulte detalhes da API em [CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/CreateTable) na *Referência da API AWS SDK for Java 2.x*. 

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

**SDK para JavaScript (v3)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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;
};
```
+  Para obter mais informações, consulte o [Guia do desenvolvedor do AWS SDK para JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table). 
+  Consulte detalhes da API em [CreateTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/CreateTableCommand) na *Referência da API AWS SDK para JavaScript*. 

**SDK para JavaScript (v2)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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);
  }
});
```
+  Para obter mais informações, consulte o [Guia do desenvolvedor do AWS SDK para JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table). 
+  Consulte detalhes da API em [CreateTable](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/CreateTable) na *Referência da API AWS SDK para JavaScript*. 

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

**SDK para Kotlin**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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
    }
}
```
+  Consulte detalhes da API em [CreateTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html) na *Referência da API AWS SDK para Kotlin*. 

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

**SDK para PHP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples). 
Crie uma tabela.  

```
        $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],
        ]);
    }
```
+  Consulte detalhes da API em [CreateTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/CreateTable) na *Referência da API AWS SDK para PHP*. 

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

**Ferramentas para PowerShell V4**  
**Exemplo 1: este exemplo cria uma tabela chamada Thread que tem uma chave primária que consiste em “ForumName” (hash do tipo de chave) e “Subject” (intervalo de tipos de chave). O esquema usado para construir a tabela pode ser canalizado para cada cmdlet conforme mostrado ou especificado usando o parâmetro -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
```
**Saída:**  

```
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  : {}
```
**Exemplo 2: este exemplo cria uma tabela chamada “Thread” que tem uma chave primária que consiste em “ForumName” (hash do tipo de chave) e “Subject” (intervalo de tipos de chave). Um índice secundário local também é definido. A chave do índice secundário local será definida automaticamente por meio da chave de hash primária na tabela (ForumName). O esquema usado para construir a tabela pode ser canalizado para cada cmdlet conforme mostrado ou especificado usando o parâmetro -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
```
**Saída:**  

```
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}
```
**Exemplo 3: este exemplo mostra como usar um único pipeline para criar uma tabela chamada “Thread” que tem uma chave primária que consiste em “ForumName” (hash do tipo de chave) e “Subject” (intervalo de tipos de chave) e um índice secundário local. O Add-DDBKeySchema e o Add-DDBIndexSchema criam um objeto TableSchema para você se um não for fornecido pelo pipeline ou pelo parâmetro -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
```
**Saída:**  

```
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}
```
+  Para ver detalhes da API, consulte [CreateTable](https://docs.aws.amazon.com/powershell/v4/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V4)*. 

**Ferramentas para PowerShell V5**  
**Exemplo 1: este exemplo cria uma tabela chamada Thread que tem uma chave primária que consiste em “ForumName” (hash do tipo de chave) e “Subject” (intervalo de tipos de chave). O esquema usado para construir a tabela pode ser canalizado para cada cmdlet conforme mostrado ou especificado usando o parâmetro -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
```
**Saída:**  

```
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  : {}
```
**Exemplo 2: este exemplo cria uma tabela chamada “Thread” que tem uma chave primária que consiste em “ForumName” (hash do tipo de chave) e “Subject” (intervalo de tipos de chave). Um índice secundário local também é definido. A chave do índice secundário local será definida automaticamente por meio da chave de hash primária na tabela (ForumName). O esquema usado para construir a tabela pode ser canalizado para cada cmdlet conforme mostrado ou especificado usando o parâmetro -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
```
**Saída:**  

```
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}
```
**Exemplo 3: este exemplo mostra como usar um único pipeline para criar uma tabela chamada “Thread” que tem uma chave primária que consiste em “ForumName” (hash do tipo de chave) e “Subject” (intervalo de tipos de chave) e um índice secundário local. O Add-DDBKeySchema e o Add-DDBIndexSchema criam um objeto TableSchema para você se um não for fornecido pelo pipeline ou pelo parâmetro -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
```
**Saída:**  

```
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}
```
+  Para ver detalhes da API, consulte [CreateTable](https://docs.aws.amazon.com/powershell/v5/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V5)*. 

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

**SDK para Python (Boto3).**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 
Crie uma tabela para armazenar dados de filmes.  

```
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
```
+  Consulte detalhes da API em [CreateTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/CreateTable) na *Referência da API AWS SDK para Python (Boto3)*. 

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

**SDK para Ruby**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
```
+  Consulte detalhes da API em [CreateTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/CreateTable) na *Referência da API AWS SDK para Ruby*. 

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

**SDK para Rust**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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))
        }
    }
}
```
+  Consulte detalhes da API em [CreateTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.create_table) na *Referência da API AWS SDK para Rust*. 

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

**SDK para SAP ABAP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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.
```
+  Consulte detalhes da API em [CreateTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html) na *Referência da API AWS SDK para SAP ABAP*. 

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

**SDK para Swift**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
        }
    }
```
+  Para obter detalhes da API, consulte [CreateTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/createtable(input:)) na *Referência de API do AWS SDK para Swift*. 

------

Para obter mais exemplos do DynamoDB, consulte [Exemplos de código do DynamoDB usando AWS SDKs](service_code_examples.md).

Após criar uma nova tabela, acesse [Etapa 2: grave dados em uma tabela do DynamoDB](getting-started-step-2.md).

# Etapa 2: grave dados em uma tabela do DynamoDB
<a name="getting-started-step-2"></a>

Nesta etapa, insira muitos itens na tabela `Music` que você criou em [Etapa 1: crie uma tabela no DynamoDB](getting-started-step-1.md). 

Para obter mais informações sobre operações de gravação, consulte [Gravar um item](WorkingWithItems.md#WorkingWithItems.WritingData).

## Console de gerenciamento da AWS
<a name="getting-started-step-2-Console"></a>

Siga estas etapas para gravar dados na tabela `Music` usando o console do DynamoDB.

1. Abra o console do DynamoDB em [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/).

1. No painel de navegação à esquerda, selecione **Tables (Tabelas)**. 

1. Na página **Tabelas**, selecione a tabela **Música**.

1. Escolha **Explore table items** (Explorar itens da tabela).

1. Na seção **Itens retornados**, selecione **Criar item**.

1. Na página **Criar item**, faça o seguinte para adicionar itens à tabela:

   1. Selecione **Add new attribute** (Adicionar novo atributo) e depois escolha **Number** (Número).

   1. Em Nome do atributo, insira **Awards**.

   1. Repita o processo para criar um **AlbumTitle** do tipo **String**.

   1. Escolha os seguintes valores para o item:

      1. Em **Artist** (Artista), insira **No One You Know**.

      1. Em **SongTitle** (Nome da música), insira **Call Me Today**.

      1. Em **AlbumTitle** (Nome do álbum), insira **Somewhat Famous**.

      1. Em **Awards** (Prêmios), insira **1**.

1. Selecione **Create Item** (Criar item).

1. Repita o processo para criar outro item com os seguintes valores:

   1. Em **Artist** (Artista), insira **Acme Band**.

   1. Em **SongTitle** (Nome da música) insira **Happy Day**.

   1. Em **AlbumTitle** (Nome do álbum), insira **Songs About Life**.

   1. Em **Awards** (Prêmios), insira **10**.

1. Faça isso mais uma vez para criar outro item com o mesmo **Artist** (Artista) como na etapa anterior, mas com valores diferentes para os outros atributos:

   1. Em **Artist** (Artista), insira **Acme Band**.

   1. Em **SongTitle** (Nome da música) insira **PartiQL Rocks**.

   1. Em **AlbumTitle** (Nome do álbum), insira **Another Album Title**.

   1. Em **Awards** (Prêmios), insira **8**.

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

O exemplo da AWS CLI a seguir cria muitos itens novos na tabela `Music`. É possível fazer isso com a API do DynamoDB ou [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), uma linguagem de consulta compatível com SQL para o 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"}}'
```

**CMD do Windows**

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

**CMD do Windows**

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

Para obter mais informações sobre gravação de dados com PartiQL, consulte [Instruções Insert em PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.insert.html).

------

Para obter mais informações sobre tipos de dados compatíveis com o DynamoDB, consulte [Tipos de dados](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes). 

Para obter mais informações sobre como representar os tipos de dados do DynamoDB em JSON, consulte [Valores de atributos](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html). 

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

Os exemplos de código a seguir mostram como gravar um item em uma tabela do DynamoDB usando um AWS SDK.

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

**SDK para .NET (v4)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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;
        }
    }
```
+  Consulte detalhes da API em [PutItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/PutItem) na *Referência da API AWS SDK para .NET*. 

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

**AWS CLI com script Bash**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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

}
```
As funções utilitárias usadas neste exemplo.  

```
###############################################################################
# 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
}
```
+  Consulte detalhes da API em [PutItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem) na *Referência de comandos da AWS CLI*. 

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

**SDK para C\$1\$1**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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);
}
```
Código que aguarda a tabela se tornar ativa.  

```
//! 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;
}
```
+  Consulte detalhes da API em [PutItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/PutItem) na *Referência da API AWS SDK para C\$1\$1*. 

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

**AWS CLI**  
**Exemplo 1: como adicionar um item a uma tabela**  
O exemplo de `put-item` a seguir adiciona um novo item à tabela *MusicCollection*.  

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

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

```
{
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    },
    "ItemCollectionMetrics": {
        "ItemCollectionKey": {
            "Artist": {
                "S": "No One You Know"
            }
        },
        "SizeEstimateRangeGB": [
            0.0,
            1.0
        ]
    }
}
```
Para obter mais informações, consulte [Gravar um item](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 2: como substituir condicionalmente um item em uma tabela**  
O exemplo de `put-item` a seguir substitui um item existente na tabela `MusicCollection` somente se o item existente tiver um atributo `AlbumTitle` com o valor `Greatest Hits`. O comando retorna o valor anterior do item.  

```
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
```
Conteúdo de `item.json`:  

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

```
{
    "#A": "AlbumTitle"
}
```
Conteúdo de `values.json`:  

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

```
{
    "Attributes": {
        "AlbumTitle": {
            "S": "Greatest Hits"
        },
        "Artist": {
            "S": "No One You Know"
        },
        "SongTitle": {
            "S": "Call Me Today"
        }
    }
}
```
Se a chave já existir, você verá a seguinte saída:  

```
A client error (ConditionalCheckFailedException) occurred when calling the PutItem operation: The conditional request failed.
```
Para obter mais informações, consulte [Gravar um item](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) no *Guia do desenvolvedor do Amazon DynamoDB*.  
+  Consulte detalhes da API em [PutItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/put-item.html) na *Referência de comandos da AWS CLI*. 

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

**SDK para Go V2**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
}
```
Defina uma estrutura de filme usada neste exemplo.  

```
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"])
}
```
+  Consulte detalhes da API em [PutItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.PutItem) na *Referência da API do AWS SDK para Go*. 

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

**SDK para Java 2.x**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
Coloca um item em uma tabela usando o [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);
        }
    }
}
```
+  Consulte detalhes da API em [PutItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem) na *Referência da API AWS SDK for Java 2.x*. 

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

**SDK para JavaScript (v3)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Neste exemplo, é usado o cliente de documentos para simplificar o trabalho com itens no DynamoDB. Para obter detalhes da API, consulte [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;
};
```
+  Consulte detalhes da API em [PutItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/PutItemCommand) na *Referência da API AWS SDK para JavaScript*. 

**SDK para JavaScript (v2)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples). 
Coloque um item em uma tabela.  

```
// 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);
  }
});
```
Coloque um item em uma tabela usando o cliente de documento do 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);
  }
});
```
+  Para obter mais informações, consulte o [Guia do desenvolvedor do AWS SDK para 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). 
+  Consulte detalhes da API em [PutItem](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/PutItem) na *Referência da API AWS SDK para JavaScript*. 

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

**SDK para Kotlin**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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.")
    }
}
```
+  Consulte detalhes da API em [PutItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html) na *Referência da API AWS SDK para Kotlin*. 

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

**SDK para PHP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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);
    }
```
+  Consulte detalhes da API em [PutItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/PutItem) na *Referência da API AWS SDK para PHP*. 

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

**Ferramentas para PowerShell V4**  
**Exemplo 1: cria um item ou substitui um item por um novo item.**  

```
$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
```
+  Para ver detalhes da API, consulte [PutItem](https://docs.aws.amazon.com/powershell/v4/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V4)*. 

**Ferramentas para PowerShell V5**  
**Exemplo 1: cria um item ou substitui um item por um novo item.**  

```
$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
```
+  Para ver detalhes da API, consulte [PutItem](https://docs.aws.amazon.com/powershell/v5/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V5)*. 

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

**SDK para Python (Boto3).**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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
```
+  Consulte detalhes da API em [PutItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem) na *Referência da API AWS SDK para Python (Boto3)*. 

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

**SDK para Ruby**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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
```
+  Consulte detalhes da API em [PutItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/PutItem) na *Referência da API AWS SDK para Ruby*. 

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

**SDK para Rust**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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,
    })
}
```
+  Consulte detalhes da API em [PutItem](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.put_item) na *Referência da API AWS SDK para Rust*. 

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

**SDK para SAP ABAP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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.
```
+  Consulte detalhes da API em [PutItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html) na *Referência da API AWS SDK para SAP ABAP*. 

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

**SDK para Swift**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
    }
```
+  Para obter detalhes da API, consulte [PutItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/putitem(input:)) na *Referência de API do AWS SDK para Swift*. 

------

Para obter mais exemplos do DynamoDB, consulte [Exemplos de código do DynamoDB usando AWS SDKs](service_code_examples.md).

Após gravar os dados na sua tabela, acesse [Etapa 3: leia os dados de uma tabela do DynamoDB](getting-started-step-3.md).

# Etapa 3: leia os dados de uma tabela do DynamoDB
<a name="getting-started-step-3"></a>

Nessa etapa, você lerá um dos itens criados em [Etapa 2: grave dados em uma tabela do DynamoDB](getting-started-step-2.md). Você pode usar o console do DynamoDB ou a AWS CLI para ler um item da tabela `Music` especificando `Artist` e `SongTitle`. 

Para ver mais informações sobre as operações de leitura no DynamoDB, consulte [Ler um item](WorkingWithItems.md#WorkingWithItems.ReadingData). 

## Console de gerenciamento da AWS
<a name="getting-started-step-3-Console"></a>

Siga estas etapas para ler os dados da tabela `Music` usando o console do DynamoDB.

1. Abra o console do DynamoDB em [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/).

1. No painel de navegação à esquerda, selecione **Tables (Tabelas)**.

1. Na página **Tabelas**, selecione a tabela **Música**.

1. Escolha **Explore table items** (Explorar itens da tabela).

1. Na seção **Itens retornados**, veja a lista de itens armazenados na tabela, classificados por `Artist` e `SongTitle`. O primeiro item da lista é aquele com o **Artista** chamado **Acme Band** e o **TítulodaMúsica** **PartiQL Rock**.

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

O exemplo da AWS CLI a seguir lê um item da tabela `Music`. É possível fazer isso com a API do DynamoDB ou [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), uma linguagem de consulta compatível com SQL para o DynamoDB.

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

**nota**  
O comportamento padrão do DynamoDB é o de leituras finais consistentes. O parâmetro `consistent-read` é usado abaixo para demonstrar leituras altamente consistentes.

**Linux**

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

**CMD do Windows**

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

O uso de `get-item` retorna o seguinte resultado de exemplo.

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

**CMD do Windows**

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

Usar a instrução `Select` PartiQL retorna o resultado de exemplo a seguir.

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

Para obter mais informações sobre leitura de dados com PartiQL, consulte [Instruções Select em PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.SELECT.html).

------

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

Os exemplos de código a seguir mostram como ler um item em uma tabela do DynamoDB usando um AWS SDK.

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

**SDK para .NET (v4)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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;
        }
    }
```
+  Consulte detalhes da API em [GetItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/GetItem) na *Referência da API AWS SDK para .NET*. 

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

**AWS CLI com script Bash**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
}
```
As funções utilitárias usadas neste exemplo.  

```
###############################################################################
# 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
}
```
+  Consulte detalhes da API em [GetItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/GetItem) na *Referência de comandos da AWS CLI*. 

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

**SDK para C\$1\$1**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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();
}
```
+  Consulte detalhes da API em [GetItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/GetItem) na *Referência da API AWS SDK para C\$1\$1*. 

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

**AWS CLI**  
**Exemplo 1: como ler um item em uma tabela**  
O exemplo de `get-item` a seguir recupera um item da tabela `MusicCollection`. A tabela tem uma chave primária de hash e intervalo (`Artist` e `SongTitle`), portanto, você deve especificar esses dois atributos. O comando também solicita informações sobre a capacidade de leitura consumida pela operação.  

```
aws dynamodb get-item \
    --table-name MusicCollection \
    --key file://key.json \
    --return-consumed-capacity TOTAL
```
Conteúdo de `key.json`:  

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

```
{
    "Item": {
        "AlbumTitle": {
            "S": "Songs About Life"
        },
        "SongTitle": {
            "S": "Happy Day"
        },
        "Artist": {
            "S": "Acme Band"
        }
    },
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5
    }
}
```
Para obter mais informações, consulte [Ler um item](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 2: como ler um item usando uma leitura consistente**  
O exemplo a seguir recupera um item da tabela `MusicCollection` usando leituras altamente consistentes.  

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

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

```
{
    "Item": {
        "AlbumTitle": {
            "S": "Songs About Life"
        },
        "SongTitle": {
            "S": "Happy Day"
        },
        "Artist": {
            "S": "Acme Band"
        }
    },
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    }
}
```
Para obter mais informações, consulte [Ler um item](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 3: como recuperar atributos específicos de um item**  
O exemplo a seguir usa uma expressão de projeção para recuperar apenas três atributos do item desejado.  

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

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

```
{
    "Item": {
        "Price": {
            "N": "20"
        },
        "Title": {
            "S": "Book 102 Title"
        },
        "ProductCategory": {
            "S": "Book"
        }
    }
}
```
Para obter mais informações, consulte [Ler um item](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData) no *Guia do desenvolvedor do Amazon DynamoDB*.  
+  Consulte detalhes da API em [GetItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/get-item.html) na *Referência de comandos da AWS CLI*. 

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

**SDK para Go V2**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
}
```
Defina uma estrutura de filme usada neste exemplo.  

```
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"])
}
```
+  Consulte detalhes da API em [GetItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.GetItem) na *Referência da API do AWS SDK para Go*. 

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

**SDK para Java 2.x**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
Obtenha um item de uma tabela usando o 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);
        }
    }
}
```
+  Consulte detalhes da API em [GetItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/GetItem) na *Referência da API AWS SDK for Java 2.x*. 

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

**SDK para JavaScript (v3)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Neste exemplo, é usado o cliente de documentos para simplificar o trabalho com itens no DynamoDB. Para obter detalhes da API, consulte [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;
};
```
+  Consulte detalhes da API em [GetItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/GetItemCommand) na *Referência da API AWS SDK para JavaScript*. 

**SDK para JavaScript (v2)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples). 
Obtenha um item de uma tabela.  

```
// 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);
  }
});
```
Obtenha um item de uma tabela usando o cliente de documento do 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);
  }
});
```
+  Para obter mais informações, consulte o [Guia do desenvolvedor do AWS SDK para JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-dynamodb-utilities.html#dynamodb-example-document-client-get). 
+  Consulte detalhes da API em [GetItem](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/GetItem) na *Referência da API AWS SDK para JavaScript*. 

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

**SDK para Kotlin**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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)
        }
    }
}
```
+  Consulte detalhes da API em [GetItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html) na *Referência da API AWS SDK para Kotlin*. 

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

**SDK para PHP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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,
        ]);
    }
```
+  Consulte detalhes da API em [GetItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/GetItem) na *Referência da API AWS SDK para PHP*. 

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

**Ferramentas para PowerShell V4**  
**Exemplo 1: exibe o item do DynamoDB com a chave de partição SongTitle e a chave de classificação Artist.**  

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

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**Saída:**  

```
Name                           Value
----                           -----
Genre                          Country
SongTitle                      Somewhere Down The Road
Price                          1.94
Artist                         No One You Know
CriticRating                   9
AlbumTitle                     Somewhat Famous
```
+  Para ver detalhes da API, consulte [GetItem](https://docs.aws.amazon.com/powershell/v4/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V4)*. 

**Ferramentas para PowerShell V5**  
**Exemplo 1: exibe o item do DynamoDB com a chave de partição SongTitle e a chave de classificação Artist.**  

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

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**Saída:**  

```
Name                           Value
----                           -----
Genre                          Country
SongTitle                      Somewhere Down The Road
Price                          1.94
Artist                         No One You Know
CriticRating                   9
AlbumTitle                     Somewhat Famous
```
+  Para ver detalhes da API, consulte [GetItem](https://docs.aws.amazon.com/powershell/v5/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V5)*. 

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

**SDK para Python (Boto3).**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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"]
```
+  Consulte detalhes da API em [GetItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/GetItem) na *Referência da API AWS SDK para Python (Boto3)*. 

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

**SDK para Ruby**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
```
+  Consulte detalhes da API em [GetItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/GetItem) na *Referência da API AWS SDK para Ruby*. 

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

**SDK para SAP ABAP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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.
```
+  Consulte detalhes da API em [GetItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html) na *Referência da API AWS SDK para SAP ABAP*. 

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

**SDK para Swift**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
        }
    }
```
+  Para obter detalhes da API, consulte [GetItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/getitem(input:)) na *Referência de API do AWS SDK para Swift*. 

------

Para obter mais exemplos do DynamoDB, consulte [Exemplos de código do DynamoDB usando AWS SDKs](service_code_examples.md).

Para atualizar os dados na tabela, acesse [Etapa 4: atualize os dados em uma tabela do DynamoDB](getting-started-step-4.md).

# Etapa 4: atualize os dados em uma tabela do DynamoDB
<a name="getting-started-step-4"></a>

Nesta etapa, você atualiza um item que criou em [Etapa 2: grave dados em uma tabela do DynamoDB](getting-started-step-2.md). Você pode usar o console do DynamoDB ou a AWS CLI para atualizar o `AlbumTitle` de um item na tabela `Music` especificando `Artist`, `SongTitle` e o `AlbumTitle` atualizado. 

Para obter mais informações sobre operações de gravação, consulte [Gravar um item](WorkingWithItems.md#WorkingWithItems.WritingData).

## Console de gerenciamento da AWS
<a name="getting-started-step-4-Console"></a>

Você pode usar o console do DynamoDB para atualizar os dados na tabela `Music`.

1. Abra o console do DynamoDB em [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/).

1. No painel de navegação à esquerda, selecione **Tables (Tabelas)**.

1. Escolha a tabela **Music** (Música) na lista de tabelas.

1. Escolha **Explore table items** (Explorar itens da tabela).

1. Em **Itens retornados**, para a linha de itens com **Acme Band** em **Artista** e **Happy Day** em **TítulodaMúsica**, faça o seguinte:

   1. Coloque o cursor no **TítulodoÁlbum** chamado **Songs about Life**.

   1. Selecione o ícone Editar.

   1. Na janela pop-up **Editar string**, digite **Songs of Twilight**.

   1. Escolha **Salvar**.
**dica**  
Opcionalmente, para atualizar um item, faça o seguinte na seção **Itens retornados**:  
Selecione a linha do item com o **Artista** chamado **Acme Band** e o **TítulodaMúsica** **Happy Day**.
Na lista suspensa **Ações**, selecione **Editar item**.
Em **TítulodoÁlbum**, insira **Songs of Twilight**.
Escolha **Save and close**.

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

O exemplo da AWS CLI a seguir atualiza um item da tabela `Music`. É possível fazer isso com a API do DynamoDB ou [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), uma linguagem de consulta compatível com SQL para o 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
```

**CMD do Windows**

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

Usar `update-item` retornará o seguinte resultado de exemplo porque `return-values ALL_NEW` foi especificado.

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

**CMD do Windows**

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

Usar a instrução `Update` retornará o seguinte resultado de exemplo porque `RETURNING ALL NEW *` foi especificado.

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

Para obter mais informações sobre a atualização de dados com PartiQL, consulte [Instruções Update em PartiQL ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.update.html).

------

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

Os exemplos de código a seguir mostram como atualizar um item em uma tabela do DynamoDB usando um AWS SDK.

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

**SDK para .NET (v4)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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;
        }
    }
```
+  Consulte detalhes da API em [UpdateItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/UpdateItem) na *Referência da API AWS SDK para .NET*. 

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

**AWS CLI com script Bash**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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

}
```
As funções utilitárias usadas neste exemplo.  

```
###############################################################################
# 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
}
```
+  Consulte detalhes da API em [UpdateItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateItem) na *Referência de comandos da AWS CLI*. 

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

**SDK para C\$1\$1**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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);
}
```
Código que aguarda a tabela se tornar ativa.  

```
//! 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;
}
```
+  Consulte detalhes da API em [UpdateItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/UpdateItem) na *Referência da API do AWS SDK para C\$1\$1*. 

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

**AWS CLI**  
**Exemplo 1: como atualizar um item em uma tabela**  
O exemplo da `update-item` a seguir atualiza um item da tabela `MusicCollection`. Ele adiciona um novo atributo (`Year`) e modifica o atributo `AlbumTitle`. Todos os atributos no item, conforme aparecem após a atualização, são retornados na resposta.  

```
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
```
Conteúdo de `key.json`:  

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

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

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

```
{
    "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
        ]
    }
}
```
Para obter mais informações, consulte [Gravar um item](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 2: como atualizar um item de forma condicional**  
O exemplo a seguir atualiza um item na tabela `MusicCollection`, mas somente se o item existente ainda não tiver um atributo `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)"
```
Conteúdo de `key.json`:  

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

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

```
{
    ":y":{"N": "2015"},
    ":t":{"S": "Louder Than Ever"}
}
```
Se o item já tiver um atributo `Year`, o DynamoDB retornará saída a seguir.  

```
An error occurred (ConditionalCheckFailedException) when calling the UpdateItem operation: The conditional request failed
```
Para obter mais informações, consulte [Gravar um item](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData) no *Guia do desenvolvedor do Amazon DynamoDB*.  
+  Consulte detalhes da API em [UpdateItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-item.html) na *Referência de comandos da AWS CLI*. 

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

**SDK para Go V2**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
}
```
Defina uma estrutura de filme usada neste exemplo.  

```
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"])
}
```
+  Consulte detalhes da API em [UpdateItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.UpdateItem) na *Referência da API do AWS SDK para Go*. 

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

**SDK para Java 2.x**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
Atualiza um item em uma tabela usando o [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!");
    }
}
```
+  Consulte detalhes da API em [UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem) na *Referência da API AWS SDK for Java 2.x*. 

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

**SDK para JavaScript (v3)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Neste exemplo, é usado o cliente de documentos para simplificar o trabalho com itens no DynamoDB. Para obter detalhes da API, consulte [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;
};
```
+  Consulte detalhes da API em [UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand) na *Referência da API AWS SDK para JavaScript*. 

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

**SDK para Kotlin**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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")
    }
}
```
+  Consulte detalhes da API em [UpdateItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html) na *Referência da API AWS SDK para Kotlin*. 

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

**SDK para PHP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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
                ]
            ],
        ]);
    }
```
+  Consulte detalhes da API em [UpdateItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/UpdateItem) na *Referência da API AWS SDK para PHP*. 

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

**Ferramentas para PowerShell V4**  
**Exemplo 1: define o atributo de gênero como “Rap” no item do DynamoDB com a chave de partição SongTitle e a chave de classificação 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
```
**Saída:**  

```
Name                           Value
----                           -----
Genre                          Rap
```
+  Para ver detalhes da API, consulte [UpdateItem](https://docs.aws.amazon.com/powershell/v4/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V4)*. 

**Ferramentas para PowerShell V5**  
**Exemplo 1: define o atributo de gênero como “Rap” no item do DynamoDB com a chave de partição SongTitle e a chave de classificação 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
```
**Saída:**  

```
Name                           Value
----                           -----
Genre                          Rap
```
+  Para ver detalhes da API, consulte [UpdateItem](https://docs.aws.amazon.com/powershell/v5/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V5)*. 

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

**SDK para Python (Boto3).**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 
Atualize um item usando uma expressão de atualização.  

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def 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"]
```
Atualize um item usando uma expressão de atualização que inclui uma operação aritmética.  

```
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"]
```
Atualize um item somente quando ele atender a determinadas condições.  

```
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"]
```
+  Consulte detalhes da API em [UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem) na *Referência da API AWS SDK para Python (Boto3)*. 

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

**SDK para Ruby**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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
```
+  Consulte detalhes da API em [UpdateItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/UpdateItem) na *Referência da API AWS SDK para Ruby*. 

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

**SDK para SAP ABAP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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.
```
+  Para obter os detalhes da API, consulte [UpdateItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html) na *Referência da API AWS SDK para SAP ABAP*. 

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

**SDK para Swift**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
        }
    }
```
+  Para obter detalhes da API, consulte [UpdateItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/updateitem(input:)) na *Referência de API do AWS SDK para Swift*. 

------

Para obter mais exemplos do DynamoDB, consulte [Exemplos de código do DynamoDB usando AWS SDKs](service_code_examples.md).

Para consultar os dados na tabela `Music`, acesse [Etapa 5: consulte os dados de uma tabela do DynamoDB](getting-started-step-5.md).

# Etapa 5: consulte os dados de uma tabela do DynamoDB
<a name="getting-started-step-5"></a>

Nesta etapa, você consulta dados que gravou na tabela `Music` em [Etapa 2: grave dados em uma tabela do DynamoDB](getting-started-step-2.md) especificando `Artist`. Isso exibirá todas as músicas associadas à chave de partição: `Artist`.

Para obter mais informações sobre as operações de consulta, consulte [Consultar tabelas no DynamoDB](Query.md). 

## Console de gerenciamento da AWS
<a name="getting-started-step-5-Console"></a>

Siga estas etapas para usar o console do DynamoDB para consultar dados em uma tabela `Music`.

1. Abra o console do DynamoDB em [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/).

1. No painel de navegação à esquerda, selecione **Tables (Tabelas)**.

1. Escolha a tabela **Music** (Música) na lista de tabelas.

1. Escolha **Explore table items** (Explorar itens da tabela).

1. Em **Verificar ou consultar itens**, verifique se a opção **Consultar** está selecionada.

1. Em **Partition key** (Chave de partição), insira **Acme Band** e escolha **Run** (Executar).

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

O exemplo da AWS CLI a seguir consulta um item da tabela `Music`. É possível fazer isso com a API do DynamoDB ou [PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html), uma linguagem de consulta compatível com SQL para o DynamoDB.

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

Consulte um item por meio da API do DynamoDB usando `query` e informando a chave de partição.

**Linux**

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

**CMD do Windows**

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

Usar `query` retornará todas as músicas associadas a este `Artist` específico.

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

Consulte um item com PartiQL usando a instrução `Select` e informando a chave de partição.

**Linux**

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

**CMD do Windows**

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

Usar a instrução `Select` desse modo retornará todas as músicas associadas a este `Artist` específico.

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

Para obter mais informações sobre consulta de dados com PartiQL, consulte [Instruções Select em PartiQL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.select.html).

------

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

Os exemplos de código a seguir mostram como consultar uma tabela do DynamoDB usando um AWS SDK.

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

**SDK para .NET (v4)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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;
        }
    }
```
+  Consulte detalhes da API em [Query](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/Query) na *Referência da API AWS SDK para .NET*. 

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

**AWS CLI com script Bash**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
}
```
As funções utilitárias usadas neste exemplo.  

```
###############################################################################
# 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
}
```
+  Consulte detalhes da API em [Query](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/Query) na *Referência de comandos da AWS CLI*. 

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

**SDK para C\$1\$1**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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;
}
```
+  Consulte detalhes da API em [Query](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/Query) na *Referência da API AWS SDK para C\$1\$1*. 

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

**AWS CLI**  
**Exemplo 1: como consultar uma tabela**  
O exemplo da `query` a seguir consulta itens da tabela `MusicCollection`. A tabela tem uma chave primária de hash e intervalo (`Artist` e `SongTitle`), mas essa consulta especifica apenas o valor da chave de hash. Ela retorna nomes de músicas do 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
```
Conteúdo de `expression-attributes.json`:  

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

```
{
    "Items": [
        {
            "SongTitle": {
                "S": "Call Me Today"
            },
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5
    }
}
```
Para obter mais informações, consulte [Operações de consulta no DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 2: como consultar uma tabela usando leituras altamente consistentes e percorrer o índice em ordem decrescente**  
O exemplo a seguir executa a mesma consulta do primeiro exemplo, mas retorna os resultados na ordem inversa e usa leituras altamente consistentes.  

```
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
```
Conteúdo de `expression-attributes.json`:  

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

```
{
    "Items": [
        {
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        },
        {
            "SongTitle": {
                "S": "Call Me Today"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    }
}
```
Para obter mais informações, consulte [Operações de consulta no DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 3: como filtrar resultados específicos**  
O exemplo a seguir consulta o `MusicCollection`, mas exclui os resultados com valores específicos no atributo `AlbumTitle`. Observe que isso não afeta `ScannedCount` ou `ConsumedCapacity` já que o filtro é aplicado após a leitura dos itens.  

```
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
```
Conteúdo de `values.json`:  

```
{
    ":v1": {"S": "No One You Know"},
    ":v2": {"S": "Blue Sky Blues"},
    ":v3": {"S": "Greatest Hits"}
}
```
Conteúdo de `names.json`:  

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

```
{
    "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
    }
}
```
Para obter mais informações, consulte [Operações de consulta no DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 4: como recuperar somente uma contagem de itens**  
O exemplo a seguir recupera uma contagem de itens que correspondem à consulta, mas não recupera os itens em si.  

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

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

```
{
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": null
}
```
Para obter mais informações, consulte [Operações de consulta no DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
**Exemplo 5: como consultar um índice**  
O exemplo a seguir consulta o índice secundário local `AlbumTitleIndex`. A consulta retorna todos os atributos da tabela base projetados no índice secundário local. Ao consultar um índice secundário local ou global, você deve fornecer o nome da tabela base usando o parâmetro `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
```
Conteúdo de `expression-attributes.json`:  

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

```
{
    "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
            }
        }
    }
}
```
Para obter mais informações, consulte [Operações de consulta no DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html) no *Guia do desenvolvedor do Amazon DynamoDB*.  
+  Consulte detalhes da API em [Query](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/query.html) na *Referência de comandos da AWS CLI*. 

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

**SDK para Go V2**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
}
```
Defina uma estrutura de filme usada neste exemplo.  

```
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"])
}
```
+  Consulte detalhes da API em [Query](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.Query) na *Referência da API do AWS SDK para Go*. 

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

**SDK para Java 2.x**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples). 
Consulta uma tabela usando o [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;
    }
}
```
Consulta uma tabela usando o `DynamoDbClient` e um índice secundário.  

```
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);
        }
    }
}
```
+  Consulte detalhes da API em [Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query) na *Referência da API AWS SDK for Java 2.x*. 

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

**SDK para JavaScript (v3)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
Neste exemplo, é usado o cliente de documentos para simplificar o trabalho com itens no DynamoDB. Para obter detalhes da API, consulte [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;
};
```
+  Para obter mais informações, consulte o [Guia do desenvolvedor do AWS SDK para JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying). 
+  Consulte detalhes da API em [Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand) na *Referência da API AWS SDK para JavaScript*. 

**SDK para JavaScript (v2)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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);
  }
});
```
+  Para obter mais informações, consulte o [Guia do desenvolvedor do AWS SDK para JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying). 
+  Consulte detalhes da API em [Query](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/Query) na *Referência da API AWS SDK para JavaScript*. 

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

**SDK para Kotlin**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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
    }
}
```
+  Consulte detalhes da API em [Query](https://sdk.amazonaws.com/kotlin/api/latest/index.html) na *Referência da API AWS SDK para Kotlin*. 

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

**SDK para PHP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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);
    }
```
+  Consulte detalhes da API em [Query](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/Query) na *Referência da API AWS SDK para PHP*. 

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

**Ferramentas para PowerShell V4**  
**Exemplo 1: invoca uma consulta que exibe itens do DynamoDB com SongTitle e Artist especificados.**  

```
$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
```
**Saída:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  Para ver detalhes da API, consulte [Query](https://docs.aws.amazon.com/powershell/v4/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V4)*. 

**Ferramentas para PowerShell V5**  
**Exemplo 1: invoca uma consulta que exibe itens do DynamoDB com SongTitle e Artist especificados.**  

```
$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
```
**Saída:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  Para ver detalhes da API, consulte [Query](https://docs.aws.amazon.com/powershell/v5/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V5)*. 

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

**SDK para Python (Boto3).**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples). 
Consulte itens usando uma expressão de condição de chave.  

```
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"]
```
Consulte itens e projete-os para retornar um subconjunto de dados.  

```
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"]
```
+  Consulte detalhes da API em [Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query) na *Referência da API AWS SDK para Python (Boto3)*. 

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

**SDK para Ruby**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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
```
+  Consulte detalhes da API em [Query](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/Query) na *Referência da API AWS SDK para Ruby*. 

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

**SDK para Rust**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples). 
Encontre os filmes feitos no ano especificado.  

```
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![])
    }
}
```
+  Consulte detalhes da API em [Query](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.query) na *Referência da API AWS SDK para Rust*. 

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

**SDK para SAP ABAP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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.
```
+  Para obter os detalhes da API, consulte [Query](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html) na *Referência da API AWS SDK para SAP ABAP*. 

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

**SDK para Swift**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
        }
    }
```
+  Para obter detalhes da API, consulte [Query](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/query(input:)) na *Referência de API do AWS SDK para Swift*. 

------

Para obter mais exemplos do DynamoDB, consulte [Exemplos de código do DynamoDB usando AWS SDKs](service_code_examples.md).

Para criar um índice secundário global para sua tabela, acesse [Etapa 6: (Opcional) exclua uma tabela do DynamoDB para limpar os recursos](getting-started-step-6.md).

# Etapa 6: (Opcional) exclua uma tabela do DynamoDB para limpar os recursos
<a name="getting-started-step-6"></a>

Se a tabela do Amazon DynamoDB criada durante o tutorial não for mais necessária, você poderá excluí-la. Esta etapa ajuda a garantir que você não será cobrado pelos recursos que não está utilizando. Use o console do DynamoDB ou a AWS CLI para excluir a tabela `Music` que você criou em [Etapa 1: crie uma tabela no DynamoDB](getting-started-step-1.md).

Para ver mais informações sobre as operações de tabelas no DynamoDB, consulte [Trabalhar com tabelas e dados no DynamoDB](WorkingWithTables.md). 

## Console de gerenciamento da AWS
<a name="getting-started-step-8-Console"></a>

Para excluir uma tabela `Music` usando o console:

1. Abra o console do DynamoDB em [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/).

1. No painel de navegação à esquerda, selecione **Tables (Tabelas)**.

1. Marque a caixa de seleção ao lado da tabela **Música** na lista de tabelas.

1. Escolha **Excluir**.

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

O exemplo da AWS CLI a seguir exclui a tabela `Music` usando `delete-table`.

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

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

Os exemplos de código a seguir mostram como excluir uma tabela do DynamoDB usando um SDK da AWS.

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

**SDK para .NET (v4)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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;
        }
    }
```
+  Consulte detalhes da API em [DeleteTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/DeleteTable) na *Referência da API AWS SDK para .NET*. 

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

**AWS CLI com script Bash**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
}
```
As funções utilitárias usadas neste exemplo.  

```
###############################################################################
# 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
}
```
+  Consulte detalhes da API em [DeleteTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteTable) na *Referência de comandos da AWS CLI*. 

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

**SDK para C\$1\$1**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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();
}
```
+  Consulte detalhes da API em [DeleteTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/DeleteTable) na *Referência da API AWS SDK para C\$1\$1*. 

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

**AWS CLI**  
**Como excluir uma tabela**  
O exemplo de `delete-table` a seguir exclui a tabela `MusicCollection`.  

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

```
{
    "TableDescription": {
        "TableStatus": "DELETING",
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableName": "MusicCollection",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "WriteCapacityUnits": 5,
            "ReadCapacityUnits": 5
        }
    }
}
```
Para obter mais informações, consulte [Excluir uma tabela](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeleteTable) no *Guia do desenvolvedor do Amazon DynamoDB*.  
+  Consulte detalhes da API em [DeleteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/delete-table.html) na *Referência de comandos da AWS CLI*. 

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

**SDK para Go V2**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
}
```
+  Consulte detalhes da API em [DeleteTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.DeleteTable) na *Referência da API AWS SDK para Go*. 

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

**SDK para Java 2.x**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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!");
    }
}
```
+  Consulte detalhes da API em [DeleteTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DeleteTable) na *Referência da API AWS SDK for Java 2.x*. 

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

**SDK para JavaScript (v3)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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;
};
```
+  Consulte detalhes da API em [DeleteTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DeleteTableCommand) na *Referência da API AWS SDK para JavaScript*. 

**SDK para JavaScript (v2)**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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);
  }
});
```
+  Para obter mais informações, consulte o [Guia do desenvolvedor do AWS SDK para JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-deleting-a-table). 
+  Consulte detalhes da API em [DeleteTable](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/DeleteTable) na *Referência da API AWS SDK para JavaScript*. 

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

**SDK para Kotlin**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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")
    }
}
```
+  Consulte detalhes da API em [DeleteTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html) na *Referência da API AWS SDK para Kotlin*. 

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

**SDK para PHP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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,
            ]);
        });
    }
```
+  Consulte detalhes da API em [DeleteTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/DeleteTable) na *Referência da API AWS SDK para PHP*. 

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

**Ferramentas para PowerShell V4**  
**Exemplo 1: exclui a tabela especificada. A confirmação será solicitada antes que a operação continue.**  

```
Remove-DDBTable -TableName "myTable"
```
**Exemplo 2: exclui a tabela especificada. A confirmação não será solicitada antes que a operação continue.**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  Para ver detalhes da API, consulte [DeleteTable](https://docs.aws.amazon.com/powershell/v4/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V4)*. 

**Ferramentas para PowerShell V5**  
**Exemplo 1: exclui a tabela especificada. A confirmação será solicitada antes que a operação continue.**  

```
Remove-DDBTable -TableName "myTable"
```
**Exemplo 2: exclui a tabela especificada. A confirmação não será solicitada antes que a operação continue.**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  Para ver detalhes da API, consulte [DeleteTable](https://docs.aws.amazon.com/powershell/v5/reference) na *Ferramentas da AWS para PowerShell Cmdlet Reference (V5)*. 

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

**SDK para Python (Boto3).**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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
```
+  Consulte detalhes da API em [DeleteTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DeleteTable) na *Referência da API AWS SDK para Python (Boto3)*. 

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

**SDK para Ruby**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
```
+  Consulte detalhes da API em [DeleteTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/DeleteTable) na *Referência da API AWS SDK para Ruby*. 

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

**SDK para Rust**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [Repositório de exemplos de código da 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())),
    }
}
```
+  Consulte detalhes da API em [DeleteTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.delete_table) na *Referência da API AWS SDK para Rust*. 

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

**SDK para SAP ABAP**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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.
```
+  Consulte detalhes da API em [DeleteTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html) na *Referência da API AWS SDK para SAP ABAP*. 

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

**SDK para Swift**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](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
        }
    }
```
+  Consulte detalhes da API em [DeleteTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/deletetable(input:)) na *Referência da API AWS SDK para Swift*. 

------

Para obter mais exemplos do DynamoDB, consulte [Exemplos de código do DynamoDB usando AWS SDKs](service_code_examples.md).

# Aprender mais sobre o DynamoDB
<a name="getting-started-NextSteps"></a>

Para obter mais informações sobre o uso do Amazon DynamoDB consulte os seguintes tópicos:
+ [Trabalhar com tabelas e dados no DynamoDB](WorkingWithTables.md)
+ [Trabalhar com itens e atributos no DynamoDB](WorkingWithItems.md)
+ [Consultar tabelas no DynamoDB](Query.md)
+ [Como usar índices secundários globais no DynamoDB](GSI.md)
+ [Trabalhar com transaçõesCódigo de exemplo](transactions.md)
+ [Aceleração em memória com o DynamoDB Accelerator (DAX)](DAX.md)
+ [Programação com o DynamoDB e os AWS SDKs](Programming.md)

# Gerar código de infraestrutura para o Amazon DynamoDB usando o Console-to-Code.
<a name="console-to-code"></a>

O recurso Console-to-Code do Amazon Q Developer simplifica o gerenciamento da infraestrutura do Amazon DynamoDB ao transformar as etapas de criação manual de tabelas em código de automação reproduzível. Esse recurso ajuda os desenvolvedores a escalar com eficiência a configuração dos recursos do banco de dados em seus ambientes. Para acessar mais informações, consulte [Automatizar Serviços da AWS com o Console-to-Code do Amazon Q Developer](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/console-to-code.html).

O Console-to-Code captura configurações detalhadas da tabela do DynamoDB, incluindo chaves de partição, chaves de classificação, configurações de throughput provisionado e índices secundários, e as converte em modelos precisos de infraestrutura como código. Usando IA generativa, a ferramenta garante que o código gerado mantenha a compatibilidade de parâmetros estabelecida durante o fluxo de trabalho do console.

Os desenvolvedores podem gerar código de infraestrutura do DynamoDB em vários formatos, como:
+ AWSCloud Development Kit (AWS CDK) em TypeScript, Python e Java
+ CloudFormation em YAML ou JSON

Essa abordagem permite que as equipes:
+ Padronizar o gerenciamento de recursos do banco de dados
+ Implementar uma infraestrutura controlada por versão
+ Reduzir os erros na configuração manual

O Console-to-Code do Amazon DynamoDB está disponível em todas as regiões da AWS comerciais, fornecendo uma solução poderosa para transformar configurações manuais em código de infraestrutura automatizado e reproduzível.

## Como funciona
<a name="how-it-works"></a>

Ao usar o Console-to-Code com o DynamoDB, o processo normalmente envolve:

1. **Prototipagem no console**: use o console do DynamoDB para criar e configurar recursos, como tabelas. Para ter mais informações, consulte [Conectar ao Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStartedDynamoDB.html).

1. **Ações de gravação**: o Console-to-Code registra essas ações à medida que você as executa.

1. **Geração de código**: o recurso usa os recursos de IA generativa do Amazon Q Developer para transformar as ações do console em código reutilizável no formato de sua preferência.

1. **Personalização do código**: você pode então copiar ou baixar esse código e personalizá-lo ainda mais para suas workloads de produção.

## Benefícios de usar o Console-to-Code com o DynamoDB
<a name="benefits"></a>

**Automatização simplificada**  
Converta a criação e a configuração manuais de tabelas do DynamoDB em código reutilizável com um único clique.

**Práticas recomendadas**  
O código gerado segue as práticas recomendadas pela AWS para implantações confiáveis.

**Ponte entre console e código**  
Você não precisa escolher entre usar o Console de gerenciamento da AWS ou a infraestrutura como código (IaC). Você pode usar as duas abordagens em conjunto.

**Desenvolvimento acelerado**  
Comece a usar rapidamente o código de automação que pode ser ainda mais personalizado para uso em produção.

## Exemplo de casos de uso
<a name="example-use-cases"></a>
+ Criar tabelas do DynamoDB com atributos, chaves e configurações de capacidade específicos
+ Configurar Índices Secundários Globais e índices secundários locais
+ Configurar políticas de ajuste de escala automático para tabelas do DynamoDB
+ Estabelecer configurações de backup e restauração
+ Criar e gerenciar o DynamoDB Streams

## Introdução
<a name="getting-started"></a>

Para começar a usar o Console-to-Code com o DynamoDB:

1. Faça login no Console de gerenciamento da AWS e abra o console do DynamoDB em [https://console.aws.amazon.com/dynamodbv2/](https://console.aws.amazon.com/dynamodbv2/).

1. Comece a criar ou modificar recursos do DynamoDB por meio da interface do console.

1. Use o recurso Console-to-Code para gerar código para as suas ações no formato de sua preferência.

1. Copie ou baixe o código gerado e personalize-o conforme necessário para seus requisitos específicos.

Para acessar mais informações e instruções detalhadas sobre como usar o Console-to-Code, consulte [Automatizar Serviços da AWS com o Console-to-Code do Amazon Q Developer](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/console-to-code.html) no *Guia do usuário do Amazon Q Developer*.