

# DynamoDB 入门
<a name="GettingStartedDynamoDB"></a>

您将在以下各节中学习如何连接、创建和管理 DynamoDB 表。

开始前，您应该熟悉 Amazon DynamoDB 的基本概念。您可以在 [Amazon DynamoDB 的核心组件](HowItWorks.CoreComponents.md) 中快速了解这些概念并在 [什么是 Amazon DynamoDB？](Introduction.md) 中更深入地了解。然后，继续了解[先决条件](#GettingStarted.SettingUp.DynamoWebService)。

**注意**  
注册 Amazon 后，您可以通过 [Amazon Free Tier](https://www.amazonaws.cn/free/) 开始使用 DynamoDB。如果您还没有享受完 Amazon DynamoDB 免费套餐的各项权益，那么完成本节中的示例不会花费任何费用。否则，从创建表到删除表，将会向您收取标准 DynamoDB 使用费。  
如果您不想注册免费套餐账户，可以在您的计算机上设置 [DynamoDB Local（可下载版本）](DynamoDBLocal.md)。利用此可下载版本，您可以在不注册 Amazon 账户或访问 DynamoDB Web 服务的情况下，在本地开发和测试应用程序。

**Topics**
+ [

# 面向首次用户的 Amazon DynamoDB 资源
](dynamodb-resources-first-time-users.md)
+ [

# 访问 DynamoDB
](AccessingDynamoDB.md)
+ [

## 先决条件
](#GettingStarted.SettingUp.DynamoWebService)
+ [

# 设置 DynamoDB
](SettingUp.md)
+ [

# 第 1 步：在 DynamoDB 中创建表
](getting-started-step-1.md)
+ [

# 第 2 步：将数据写入 DynamoDB 表
](getting-started-step-2.md)
+ [

# 第 3 步：从 DynamoDB 表中读取数据
](getting-started-step-3.md)
+ [

# 第 4 步：更新 DynamoDB 表中的数据
](getting-started-step-4.md)
+ [

# 第 5 步：查询 DynamoDB 表中的数据
](getting-started-step-5.md)
+ [

# 第 6 步：（可选）删除 DynamoDB 表以清理资源
](getting-started-step-6.md)
+ [

# 继续了解 DynamoDB
](getting-started-NextSteps.md)
+ [

# 使用 Console-to-Code 为 Amazon DynamoDB 生成基础设施代码
](console-to-code.md)

# 面向首次用户的 Amazon DynamoDB 资源
<a name="dynamodb-resources-first-time-users"></a>

我们建议新用户先阅读以下章节，并在需要时加以参考。


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

**Example**  
**[服务亮点和定价](https://www.amazonaws.cn/dynamodb/)**  
提供涵盖 DynamoDB、常见使用案例、服务亮点和定价的一般产品概览。  |  

**Example**  
**[DynamoDB 资源](https://www.amazonaws.cn/dynamodb/resources/)**  
视频、教程和规范性指南，向您介绍该服务、数据建模概念以及核心特性和功能。  | 
|  

**Example**  
**[开始使用](GettingStartedDynamoDB.md)**  
有关设置 DynamoDB、创建示例表和上传数据的信息。  |  

**Example**  
**[DynamoDB 基础课程](https://explore.skillbuilder.aws/learn/course/external/view/elearning/16104/amazon-dynamodb-basics)**  
免费的数字课程，讲授 DynamoDB 的基础知识，包括表设计、数据类型和基本操作。  | 
|  

**Example**  
**[DynamoDB Nuggets](https://www.youtube.com/playlist?list=PLhr1KZpdzukemNOO71Hca0GpjG0QmXwEd)**  
一系列简短而有针对性的视频教程，解释了 DynamoDB 的关键概念和功能。  |  

**Example**  
**[DynamoDB 代码示例存储库](https://github.com/aws-samples/aws-dynamodb-examples)**  
各种编程语言的实用 DynamoDB 代码示例。  | 
|  

**Example**  
**[免费 DynamoDB 培训](https://skillbuilder.aws/learn/WC3K4Y4S5N/amazon-dynamodb-getting-started/)**  
Amazon 提供涵盖了 DynamoDB 概念、功能和最佳实践的免费数字培训课程。  |  

**Example**  
**[NoSQL Workbench for DynamoDB](https://youtu.be/p5va6ZX9_o0)**  
统一的可视化工具，提供数据建模、数据可视化和查询开发功能。  | 
|  

**Example**  
**[DynamoDB 设计模式](best-practices.md)**  
针对不同使用案例的最佳实践和数据建模示例，以及实用的代码示例。  |  

**Example**  
**[动手实践教程](https://www.amazonaws.cn/tutorials/create-nosql-table/)**  
Amazon Web Services 管理控制台中的分步教程，可指导您完成常见的 DynamoDB 任务。  | 
|  

**Example**  
**[迁移到 DynamoDB](migration-guide.md)**  
将数据库迁移到 DynamoDB 的过程、工具和策略的概述。  |  

**Example**  
**[适用于 DynamoDB 的 Amazon Well-Architected Lens](bp-wal.md)**  
有关使用 DynamoDB 设计和运行可靠、安全、高效且经济有效的应用程序的架构最佳实践。  | 

## 面向首次用户的 Amazon DynamoDB 其它最佳实践
<a name="additional-reading"></a>

完成以上部分后，请阅读以下部分：
+  **[DynamoDB 吞吐能力](capacity-mode.md)** 

  概述可用于 DynamoDB 的两种吞吐量模式，以及为应用程序选择合适的容量模式时的注意事项。按需模式是大多数 DynamoDB 工作负载的默认吞吐量选项，也是建议采用的吞吐量选项。
+  **[使用 DynamoDB 进行设计和架构的最佳实践](best-practices.md)** 

  发现和解决问题，以便在使用 DynamoDB 时最大限度地提高性能和降低成本。

## Amazon CLI 资源
<a name="new-users-aws-cli-resources"></a>

如果要使用 Amazon 命令行界面（Amazon CLI），可以利用以下文档协助您开始使用：
+  **[Amazon CLI 文档](https://docs.amazonaws.cn/cli/)** 

   此部分提供有关下载 Amazon CLI、使 Amazon CLI 在系统上工作以及提供 Amazon 凭证的信息。
+  **[适用于 DynamoDB 的 Amazon CLI 文档](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/index.html)** 

   此单独文档的内容涵盖所有适用于 DynamoDB 的 Amazon CLI 命令（包括语法和示例）。

## 编程资源
<a name="new-user-programming-resources"></a>

可以使用各种常用的编程语言编写应用程序，以利用 DynamoDB API。下面是一些资源：
+  **[用于 Amazon Web Services 的工具](https://www.amazonaws.cn/developer/tools/)** 

   Amazon 提供了许多支持 DynamoDB 的软件开发工具包（SDK）。您可以使用 Java、.NET、PHP、Ruby 和其它语言为 DynamoDB 编写代码。这些 SDK 可通过格式化面向 DynamoDB 的请求、分析响应并提供重试逻辑和错误处理，极大地简化应用程序开发。
+  **[DynamoDB API 参考](https://docs.amazonaws.cn/amazondynamodb/latest/APIReference/Welcome.html)**

   如果您不想使用 Amazon SDK，可以直接使用 DynamoDB API 与 DynamoDB 交互。本文档涵盖了所有 DynamoDB API 操作，包括语法和示例。您可以在此部分中查找有关创建请求和验证请求身份以及处理响应的问题排查提示和信息。

# 访问 DynamoDB
<a name="AccessingDynamoDB"></a>

 您可以使用 Amazon Web Services 管理控制台、Amazon Command Line Interface (Amazon CLI) 或 DynamoDB API 访问 Amazon DynamoDB。

**Topics**
+ [

## 使用控制台
](#ConsoleDynamoDB)
+ [

## 使用 Amazon CLI
](#Tools.CLI)
+ [

## 使用 API
](#Using.API)
+ [

## 使用 NoSQL Workbench for DynamoDB
](#Using.Workbench)
+ [

## IP 地址范围
](#Using.IPRanges)

## 使用控制台
<a name="ConsoleDynamoDB"></a>

您可以访问 Amazon Web Services 管理控制台了解 Amazon DynamoDB，地址为 [https://console.aws.amazon.com/dynamodb/home](https://console.amazonaws.cn/dynamodb/home)。

以下是您可以在 DynamoDB 控制台中执行的一些操作：
+ **管理表**：创建、更新和删除表。容量计算器可以帮助估算容量需求。
+ **与数据交互**：查看、添加、更新和删除表中的项目。管理生存时间（TTL）设置。
+ **监控和分析**：查看仪表板、监控和设置警报，以及分析 DynamoDB 表的指标和警报。
+ **优化和扩展**：管理二级索引、流、触发器、预留容量和其他高级功能，以提高 DynamoDB 的使用率。

DynamoDB 控制台提供一个用于管理 DynamoDB 资源的综合界面。我们鼓励您访问该控制台并与之互动，以了解更多信息。

## 使用 Amazon CLI
<a name="Tools.CLI"></a>

 您可以使用 Amazon Command Line Interface (Amazon CLI) 从命令行管理多个 Amazon 服务并通过脚本自动执行这些服务。您可以使用 Amazon CLI 执行临时操作，如创建表。您还可以使用它在实用工具脚本中嵌入 Amazon DynamoDB 操作。

 您必须先获取访问密钥 ID 和秘密访问密钥，然后才能将 Amazon CLI 与 DynamoDB 结合使用。有关更多信息，请参阅 [授权以编程方式访问](SettingUp.DynamoWebService.md#SettingUp.DynamoWebService.GetCredentials)。

有关 Amazon CLI 中 DynamoDB 所有可用命令的完整列表，请参阅 [Amazon CLI 命令参考](https://docs.amazonaws.cn/cli/latest/reference/dynamodb/index.html)。

**Topics**

### 下载和配置 Amazon CLI
<a name="Tools.CLI.DownloadingAndRunning"></a>

[http://aws.amazon.com/cli](https://www.amazonaws.cn/cli) 提供 Amazon CLI。它在 Windows、macOS 或 Linux 上运行。下载 Amazon CLI 后，可执行以下步骤安装和配置：

1. 转到 [Amazon Command Line Interface 用户指南](https://docs.amazonaws.cn/cli/latest/userguide/)。

1. 按照[安装 Amazon CLI](https://docs.amazonaws.cn/cli/latest/userguide/installing.html) 和[配置 Amazon CLI](https://docs.amazonaws.cn/cli/latest/userguide/cli-chap-getting-started.html) 的说明操作。

### 将 Amazon CLI 与 DynamoDB 结合使用
<a name="Tools.CLI.UsingWithDDB"></a>

命令行格式包含 DynamoDB 操作名称，后跟该操作的参数。Amazon CLI 支持参数值的速记语法以及 JSON。

例如，以下命令可创建一个名为 *Music* 的表。分区键为 *Artist*，排序键为 *SongTitle*。（为便于阅读，本部分中的长命令分行显示。）

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

以下命令可将新项目添加到表。这些示例使用速记语法和 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
```

在命令行上，难以编写有效的 JSON。然而，Amazon CLI 可以读取 JSON 文件。例如，请考虑以下 JSON 代码段，它存储在一个名为 *key-conditions.json* 的文件中。

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

您现在可以使用 Amazon CLI 发出 `Query` 请求。在该示例中，*key-conditions.json* 文件的内容用于 `--key-conditions` 参数。

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

### 将 Amazon CLI 与 DynamoDB local 结合使用
<a name="Tools.CLI.UsingWithDDBLocal"></a>

Amazon CLI 也可与在您的计算机上运行的 DynamoDB local（可下载版本）交互。要启用此功能，请向每个命令添加以下参数：

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

下面的示例使用 Amazon CLI 列出本地数据库中的表。

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

如果 DynamoDB 使用的端口号不是默认值 (8000)，请相应修改 `--endpoint-url` 值。

**注意**  
Amazon CLI 无法将可下载版本的 DynamoDB local 作为默认端点。因此，您必须对每个命令指定 `--endpoint-url`。

## 使用 API
<a name="Using.API"></a>

 您可以使用 Amazon Web Services 管理控制台 和 Amazon Command Line Interface 以便与 Amazon DynamoDB 交互式协作。但是，要充分利用 DynamoDB，您可以使用 Amazon SDK 编写应用程序代码。

Amazon SDK 采用 [Java](https://www.amazonaws.cn/sdk-for-java)、[浏览器 JavaScript](https://www.amazonaws.cn/sdk-for-browser)、[.NET](https://www.amazonaws.cn/sdk-for-net)、[Node.js](https://www.amazonaws.cn/sdk-for-node-js)、[PHP](https://www.amazonaws.cn/sdk-for-php)、[Python](https://www.amazonaws.cn/sdk-for-python)、[Ruby](https://www.amazonaws.cn/sdk-for-ruby)、[C\$1\$1](https://www.amazonaws.cn/sdk-for-cpp)、[Go](https://www.amazonaws.cn/sdk-for-go)、[Android](https://www.amazonaws.cn/mobile/sdk/) 和 [iOS](https://www.amazonaws.cn/mobile/sdk/) 语言，为 DynamoDB 提供广泛支持。

您必须先获取 Amazon 访问密钥 ID 和秘密访问密钥，然后才能将 Amazon SDK 与 DynamoDB 结合使用。有关更多信息，请参阅 [设置 DynamoDB（Web 服务）](SettingUp.DynamoWebService.md)。

 有关使用 Amazon SDK 进行 DynamoDB 应用程序编程的高度概述，请参阅 [使用 DynamoDB 和 Amazon SDK 编程](Programming.md)。

## 使用 NoSQL Workbench for DynamoDB
<a name="Using.Workbench"></a>

您也可以通过下载和使用 [NoSQL Workbench for DynamoDB](workbench.md) 访问 DynamoDB。

NoSQL Workbench for Amazon DynamoDB 是一个跨平台的客户端 GUI 应用程序，可用于现代数据库开发和运营。它适用于 Windows、macOS 和 Linux 系统。NoSQL Workbench 是一个可视化开发工具，提供数据建模、数据可视化和查询开发功能，可帮助您设计、创建、查询和管理 DynamoDB 表。NoSQL Workbench 现在将 DynamoDB local 作为安装过程的一个可选部分，这使得在 DynamoDB local 中进行数据建模更容易。要了解 DynamoDB local 及其要求的更多信息，请参阅[设置 DynamoDB local（可下载版本）](DynamoDBLocal.md)。

**注意**  
适用于 DynamoDB 的 NoSQL Workbench 目前不支持使用双重身份验证（2FA）配置的 Amazon 登录名。

**数据建模**  
通过 NoSQL Workbench for DynamoDB，您可以构建新数据模型，或根据现有模型设计符合应用程序数据访问模式的模型。您还可以在过程结束时导入和导出设计的数据模型。有关更多信息，请参阅 [使用 NoSQL Workbench 构建数据模型](workbench.Modeler.md)。

**操作生成**  
NoSQL Workbench 为开发和测试查询提供了一个丰富的图形用户界面。您可以使用*操作生成器*来查看、浏览和查询实时数据集。此外，还可以使用结构化操作生成器生成和执行数据层面操作。它支持投影和条件表达式，并允许您使用多种语言生成示例代码。有关更多信息，请参阅 [使用 NoSQL Workbench 浏览数据集和生成操作](workbench.querybuilder.md)。

## IP 地址范围
<a name="Using.IPRanges"></a>

Amazon Web Services (Amazon) 以 JSON 格式发布其当前 IP 地址范围。要查看当前范围，请下载 [ip-ranges.json](https://ip-ranges.amazonaws.com/ip-ranges.json)。有关更多信息，请参阅《Amazon Web Services 一般参考》中的 [Amazon IP 地址范围](https://docs.amazonaws.cn/general/latest/gr/aws-ip-ranges.html)。

要查找可用于[访问 DynamoDB 表和索引](https://docs.amazonaws.cn/amazondynamodb/latest/APIReference/API_Operations_Amazon_DynamoDB.html)的 IP 地址范围，请在 ip-ranges.json 文件中搜索以下字符串：`"service": "DYNAMODB"`。

**注意**  
IP 地址范围不适用于 DynamoDB Streams 或 DynamoDB Accelerator (DAX)。

## 先决条件
<a name="GettingStarted.SettingUp.DynamoWebService"></a>

在开始学习 Amazon DynamoDB 教程之前，先通过 [访问 DynamoDB](AccessingDynamoDB.md) 了解一下访问 DynamoDB 的方法。然后，在 [设置 DynamoDB](SettingUp.md) 中，通过 Web 服务或本地下载版本设置 DynamoDB。然后，继续执行[第 1 步：在 DynamoDB 中创建表](getting-started-step-1.md)。

**注意**  
如果您计划仅通过 Amazon Web Services 管理控制台 与 DynamoDB 交互，则不需要 Amazon 访问密钥。完成[注册 Amazon](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html#SettingUp.DynamoWebService.SignUpForAWS) 中的步骤，然后继续执行[第 1 步：在 DynamoDB 中创建表](getting-started-step-1.md)。
如果您不想注册免费套餐账户，可以设置 [DynamoDB local（可下载版本）](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocal.html)。然后，继续执行[第 1 步：在 DynamoDB 中创建表](getting-started-step-1.md)。
在 Linux 和 Windows 上的终端中使用 CLI 命令存在差异。以下指南介绍了针对 Linux 终端（包括 macOS）格式化的命令和针对 Windows CMD 格式化的命令。选择最适合您所用的终端应用程序的命令。

# 设置 DynamoDB
<a name="SettingUp"></a>

 除了 Amazon DynamoDB Web 服务之外，Amazon 还提供可在计算机上运行的 DynamoDB 的可下载版本。可下载的版本有助于开发和测试您的代码。此版本可让您在不访问 DynamoDB Web 服务的情况下在本地编写和测试应用程序。

 本部分中的主题描述如何设置 DynamoDB（可下载版本）和 DynamoDB Web 服务。

**Topics**
+ [

# 设置 DynamoDB（Web 服务）
](SettingUp.DynamoWebService.md)
+ [

# 设置 DynamoDB local（可下载版本）
](DynamoDBLocal.md)

# 设置 DynamoDB（Web 服务）
<a name="SettingUp.DynamoWebService"></a>

 使用 Amazon DynamoDB Web 服务：

1.  [注册 Amazon。](#SettingUp.DynamoWebService.SignUpForAWS)

1.  [获取 Amazon 访问密钥](#SettingUp.DynamoWebService.GetCredentials)（用于以编程方式访问 DynamoDB）。
**注意**  
 如果您计划仅通过 Amazon Web Services 管理控制台 与 DynamoDB 交互，则不需要 Amazon 访问密钥，并且您可以跳至 [使用控制台](AccessingDynamoDB.md#ConsoleDynamoDB)。

1.  [配置您的凭证](#SettingUp.DynamoWebService.ConfigureCredentials)（用于以编程方式访问 DynamoDB）。

## 注册 Amazon
<a name="SettingUp.DynamoWebService.SignUpForAWS"></a>

 要使用 DynamoDB 服务，您必须拥有 Amazon 账户。如果您还没有账户，系统会在您注册时提示您创建一个。如果您没有使用注册的任何 Amazon 产品，系统将不会针对它们向您收费。

**注册 Amazon**

1. 打开 [https://portal.aws.amazon.com/billing/signup](https://portal.amazonaws.cn/billing/signup)。

1. 按照屏幕上的说明操作。

   在注册时，将接到电话或收到短信，要求使用电话键盘输入一个验证码。

   当您注册 Amazon Web Services 账户 时，系统将会创建一个。*Amazon Web Services 账户根用户*根用户有权访问该账户中的所有 Amazon Web Services 服务 和资源。作为最佳安全实践，请为用户分配管理访问权限，并且只使用根用户来执行[需要根用户访问权限的任务](https://docs.amazonaws.cn/IAM/latest/UserGuide/id_root-user.html#root-user-tasks)。

## 授权以编程方式访问
<a name="SettingUp.DynamoWebService.GetCredentials"></a>

 您必须先具有编程访问权限，然后才能以编程方式或通过 Amazon Command Line Interface（Amazon CLI）访问 DynamoDB。如果您计划仅使用 DynamoDB 控制台，则无需编程访问权限。

如果用户需要在 Amazon Web Services 管理控制台之外与 Amazon 交互，则需要编程式访问权限。Amazon API 和 Amazon Command Line Interface 需要访问密钥。可能的话，创建临时凭证，该凭证由一个访问密钥 ID、一个秘密访问密钥和一个指示凭证何时到期的安全令牌组成。

要向用户授予编程式访问权限，请选择以下选项之一。


****  

| 哪个用户需要编程式访问权限？ | 目的 | 方式 | 
| --- | --- | --- | 
| IAM | 使用短期凭证签署对 Amazon CLI 或 Amazon API 的编程式请求（直接或使用 Amazon SDK）。 | 按照《IAM 用户指南》中[将临时凭证用于 Amazon 资源](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_credentials_temp_use-resources.html)中的说明进行操作。 | 
| IAM | （不推荐使用）使用长期凭证签署对 Amazon CLI 或 Amazon API 的编程式请求（直接或使用 Amazon SDK）。 | 按照《IAM 用户指南》中[管理 IAM 用户的访问密钥](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_credentials_access-keys.html)中的说明进行操作。 | 

## 配置凭证
<a name="SettingUp.DynamoWebService.ConfigureCredentials"></a>

 您必须先配置凭证以便为您的应用程序启用授权，然后才能以编程方式或通过 Amazon CLI 访问 DynamoDB。

 我们可以通过多种方式来实现这一目的。例如，您可以手动创建凭证文件以存储您的访问密钥 ID 和秘密访问密钥。您还可以使用 Amazon CLI 命令 `aws configure` 自动创建文件。或者，您也可以使用环境变量。有关配置您的凭证的更多信息，请参阅特定于编程的 Amazon SDK 开发人员指南。

 要安装和配置 Amazon CLI，请参阅 [使用 Amazon CLI](AccessingDynamoDB.md#Tools.CLI)。

## 与其它 DynamoDB 服务集成
<a name="w2aab9c17b9c13"></a>

您可以将 DynamoDB 与许多其它 Amazon 服务集成。有关更多信息，请参阅下列内容：
+ [将 DynamoDB 与其它 Amazon 服务一起使用](OtherServices.md)
+ [Amazon CloudFormation适用于 DynamoDB 的](https://docs.amazonaws.cn//AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html) 
+ [将 Amazon Backup 与 DynamoDB 结合使用](backuprestore_HowItWorksAWS.md)
+ [Amazon Identity and Access Management（IAM）和 DynamoDB](identity-and-access-mgmt.md)
+ [将 Amazon Lambda 与 Amazon DynamoDB 结合使用](https://docs.amazonaws.cn/lambda/latest/dg/with-ddb.html)

# 设置 DynamoDB local（可下载版本）
<a name="DynamoDBLocal"></a>

 利用 Amazon DynamoDB 的可下载版本，您可以在不访问 DynamoDB Web 服务的情况下开发和测试应用程序。相反，数据库可在计算机上独立使用。当您准备好在生产中部署应用程序时，可以在代码中删除本地端点，然后它将指向 DynamoDB Web 服务。

 拥有此本地版本将帮助您节省吞吐量、数据存储和数据传输费用。此外，您在开发应用程序时无需 Internet 连接。

 DynamoDB local 作为[下载](DynamoDBLocal.DownloadingAndRunning.md#DynamoDBLocal.DownloadingAndRunning.title)版本（需要 JRE）、作为 [Apache Maven 依赖项](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html#apache-maven)或作为 [Docker 映像](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html#docker)提供。

 如果您希望改用 Amazon DynamoDB Web 服务，请参阅 [设置 DynamoDB（Web 服务）](SettingUp.DynamoWebService.md)。

**Topics**
+ [

# 在计算机上本地部署 DynamoDB
](DynamoDBLocal.DownloadingAndRunning.md)
+ [

# DynamoDB local 使用说明
](DynamoDBLocal.UsageNotes.md)
+ [

# DynamoDB local 的发布历史记录
](DynamoDBLocalHistory.md)
+ [

# DynamoDB local 中的遥测
](DynamoDBLocalTelemetry.md)

# 在计算机上本地部署 DynamoDB
<a name="DynamoDBLocal.DownloadingAndRunning"></a>

**注意**  
DynamoDB local 有三个版本可用：v3.x（当前版）、v2.x（旧版）和 v1.x（已弃用）。
建议将 DynamoDB v3.x 用于本地测试和开发用途。
从 DynamoDB local V2.x 迁移到 V3.x 要求将导入语句从 `com.amazonaws.services.dynamodbv2` 更新为 `software.amazon.dynamodb` 并更新 Maven 用户的 Maven 依赖关系。
如果您要将使用适用于 Java 的 SDK v1.x 的应用程序迁移到适用于 Java 的 SDK 2.x，请按照 [Amazon SDK for Java 2.x](https://docs.amazonaws.cn/sdk-for-java/latest/developer-guide/migration.html) 的步骤进行操作。

## 下载 DynamoDB local
<a name="DynamoDBLocal.DownloadingAndRunning.V2"></a>

按照以下步骤操作，在您的计算机上设置并运行 DynamoDB。

**在您的计算机上设置 DynamoDB**

1. 从以下位置之一免费下载 DynamoDB local。  
****    
[\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html)
**重要**  
 要在您的计算机上运行 DynamoDB v2.6.0 或更高版本，您必须具有 Java 运行时环境（JRE）17.x 或更高版本。此应用程序无法在早期的 JRE 版本上运行。

1.  下载存档后，提取内容，并将提取的目录复制到您选择的某个位置。

1.  要在计算机上启动 DynamoDB，请打开命令提示符窗口，导航到您提取 `DynamoDBLocal.jar` 的目录，并输入以下命令。

   ```
   java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb
   ```
**注意**  
 如果您使用的是 Windows PowerShell，请务必将参数名称或整个名称和值括起，如下所示：  
 ` java -D"java.library.path=./DynamoDBLocal_lib" -jar DynamoDBLocal.jar `   
 DynamoDB 将处理传入请求，直到您将其停止为止。要停止 DynamoDB，请在命令提示符处按 Ctrl\$1C。  
 默认情况下，DynamoDB 使用端口 8000。如果端口 8000 不可用，此命令将引发异常。有关 DynamoDB 运行时选项的完整列表（包括 `-port`），请输入此命令。  
 ` java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -help ` 

1. 您必须先配置凭证以便为您的应用程序启用授权，然后才能以编程方式或通过 Amazon Command Line Interface（Amazon CLI）访问 DynamoDB。可下载的 DynamoDB 需要具有任何凭证才能工作，如以下示例所示。

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

    您可以使用 `aws configure` 的 Amazon CLI 命令设置凭证。有关更多信息，请参阅 [使用 Amazon CLI](AccessingDynamoDB.md#Tools.CLI)。

1.  开始编写应用程序。要使用 Amazon CLI 访问本地运行的 DynamoDB，请使用 `--endpoint-url ` 参数。例如，使用以下命令列出 DynamoDB 表。

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

## 以 Docker 映像的形式运行 DynamoDB local
<a name="DynamoDBLocal.DownloadingAndRunning.Docker"></a>

 Amazon DynamoDB 的可下载版本作为 Docker 映像的一部分提供。有关更多信息，请参阅 [dynamodb-local](https://hub.docker.com/r/amazon/dynamodb-local)。要检查 DynamoDB local 的当前版本，请输入以下命令：

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

 有关使用作为 Amazon Serverless Application Model (Amazon SAM) 上构建的 REST 应用程序的一部分的 DynamoDB Local 的示例，请参阅[用于管理订单的 SAM DynamoDB 应用程序](https://github.com/aws-samples/aws-sam-java-rest)。此样本应用程序演示如何使用 DynamoDB Local 进行测试。

 如果要运行也是使用 DynamoDB 本地容器的多容器应用程序，请使用 Docker Compose 来定义和运行应用程序中的所有服务，包括 DynamoDB Local。

**使用 Docker compose 安装和运行 DynamoDB local：**

1.  下载并安装 [Docker desktop](https://www.docker.com/products/docker-desktop)。

1.  将以下代码复制到文件中并将其保存为 `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
   ```

    如果您希望应用程序和 DynamoDB Local 位于单独的容器中，请使用以下 yaml 文件。

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

    此 docker-compose.yml 脚本将创建一个 `app-node` 容器和一个 `dynamodb-local` 容器。此脚本会在 `app-node` 容器中运行一个命令，该命令使用 Amazon CLI 连接到 `dynamodb-local` 容器，并描述账户和表限制。

    要与您自己的应用程序映像一起使用，请将以下示例中的 `image` 值替换为应用程序的相应值：

   ```
   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'
   ```
**注意**  
 YAML 脚本要求您指定 Amazon 访问密钥和 Amazon 私有密钥，但它们不一定是您访问 DynamoDB local 的有效 Amazon 密钥。

1.  运行以下命令行命令：

   ```
   docker-compose up
   ```

## 将 DynamoDB local 作为 Apache Maven 依赖项运行
<a name="DynamoDBLocal.DownloadingAndRunning.Maven.v2"></a>

**注意**  
如果您要将使用适用于 Java 的 SDK v1.x 的应用程序迁移到适用于 Java 的 SDK 2.x，请按照 [Amazon SDK for Java 2.x](https://docs.amazonaws.cn/sdk-for-java/latest/developer-guide/migration.html) 的步骤进行操作。

 按照以下步骤操作，在应用程序中将 Amazon DynamoDB 用作依赖项。

**将 DynamoDB 部署为 Apache Maven 存储库**

1.  下载并安装 Apache Maven。有关更多信息，请参见[下载 Apache Maven](https://maven.apache.org/download.cgi) 和[安装 Apache Maven](https://maven.apache.org/install.html)。

1.  将 DynamoDB Maven 存储库添加到您的应用程序的项目对象模型 (POM) 文件。

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

    用于 Spring Boot 3 和/或 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>
   ```
**注意**  
 您也可以使用 [Maven Central 存储库](https://mvnrepository.com/artifact/com.amazonaws/DynamoDBLocal?repo=dynamodb-local-release) URL。

## 在 Amazon CloudShell 中运行 DynamoDB local
<a name="DynamoDBLocal.DynamoDB.Local.CloudShell"></a>

Amazon CloudShell 是一个已经事先完成身份验证的浏览器式 Shell，您可以直接从 Amazon Web Services 管理控制台启动它。可以通过几种不同的方式从 Amazon Web Services 管理控制台导航到 Amazon CloudShell。有关更多信息，请参阅[开始使用 Amazon CloudShell](https://docs.amazonaws.cn/cloudshell/latest/userguide/getting-started.html)。

按照以下步骤从 Amazon Web Services 管理控制台中的任何位置在 Amazon CloudShell 中运行 DynamoDB local。

**通过 Amazon Web Services 管理控制台在 Amazon CloudShell 中运行 DynamoDB local**

1. 从控制台界面启动 Amazon CloudShell，选择可用的 Amazon Web Services 区域，然后切换到您的首选 Shell，例如 Bash、PowerShell 或 Z Shell。

1. 要选择 Amazon Web Services 区域，请转至**选择区域**菜单，然后选择[支持的 Amazon Web Services 区域](https://docs.amazonaws.cn/cloudshell/latest/userguide/supported-aws-regions.html)。（可用区域突出显示。）

1. 从 Amazon Web Services 管理控制台中，通过选择以下选项之一来启动 Amazon CloudShell：

   1. 在导航栏上选择 **Amazon CloudShell** 图标。

   1. 在**搜索**框中，键入单词 CloudShell，然后选择 **CloudShell**。

   1. 在**最新访问**小部件中，选择 **CloudShell**。

   1. 从控制台工具栏中选择 **CloudShell**。

1. 要在 Amazon CloudShell 中运行 DynamoDB local，可以使用 `dynamodb-local` 别名。您可以指定其它命令行选项来更改 DynamoDB local 设置。有关可用的选项，请参阅 [DynamoDB local 使用说明](DynamoDBLocal.UsageNotes.md)。
**注意**  
要在后台运行 DynamoDB local，请在 Amazon CloudShell 中使用 `dynamodb-local &` 运行 DynamoDB local。

1. 要使用 Amazon CLI 在 Amazon CloudShell 中访问本地运行的 DynamoDB，请使用 `--endpoint-url` 参数。例如，使用以下命令来列出 DynamoDB 表：

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

有关展示多种设置和使用 DynamoDB local 的方法（包括下载 JAR 文件、将其作为 Docker 映像运行以及将其用作 Maven 依赖项）的示例项目，请参阅 [DynamoDB Local 示例 Java 项目](https://github.com/awslabs/amazon-dynamodb-local-samples/tree/main)。

# DynamoDB local 使用说明
<a name="DynamoDBLocal.UsageNotes"></a>

 除了端点之外，使用 Amazon DynamoDB 可下载版本运行的应用程序还应能使用 DynamoDB Web 服务运行。但是，在本地使用 DynamoDB 时，您应了解以下事项：
+  如果您使用 `-sharedDb` 选项，则 DynamoDB 将创建一个名为 *shared-local-instance.db* 的数据库文件。连接到 DynamoDB 的每个程序都将访问此文件。如果删除此文件，则将丢失存储在此文件中的所有数据。
+  如果省略 `-sharedDb`，则数据库文件出现在应用程序配置中时，将命名为 *myaccesskeyid\$1region.db*（包含 Amazon 访问密钥 ID 和 Amazon 区域）。如果删除此文件，则将丢失存储在此文件中的所有数据。
+  如果使用 `-inMemory` 选项，则 DynamoDB 完全不会编写任何数据库文件。相反，所有数据将被写入内存中，并且在您终止 DynamoDB 时不会保存这些数据。
+  如果您使用 `-inMemory` 选项，则 `-sharedDb` 选项也是必需的。
+  如果使用 `-optimizeDbBeforeStartup` 选项，则还必须指定 `-dbPath` 参数，以便 DynamoDB 可找到其数据库文件。
+  Amazon SDK for DynamoDB 要求您的应用程序配置指定访问密钥值和 Amazon 区域值。除非您使用的是 `-sharedDb` 或 `-inMemory` 选项，否则 DynamoDB 将使用这些值来命名本地数据库文件。这些值不必是有效的 Amazon 值也能在本地运行。但是，您可能发现使用有效值非常方便，因为您以后可通过更改当前使用的端点来在云中运行您的代码。
+  DynamoDB local 始终为 `billingModeSummary.` 返回 null。
+  DynamoDB local `AWS_ACCESS_KEY_ID` 只能包含字母（A–Z，a–z）和数字 (0–9)。
+ DynamoDB Local 不支持[时间点故障恢复（PITR）](Point-in-time-recovery.md)。

**Topics**
+ [

## 命令行选项
](#DynamoDBLocal.CommandLineOptions)
+ [

## 设置本地端点
](#DynamoDBLocal.Endpoint)
+ [

## 可下载的 DynamoDB 和 DynamoDB Web 服务之间的差异
](#DynamoDBLocal.Differences)

## 命令行选项
<a name="DynamoDBLocal.CommandLineOptions"></a>

 您可将下列命令行选项用于 DynamoDB 的下载版本：
+  `-cors` `value` — 实现对适用于 JavaScript 的跨源资源共享 (CORS) 的支持。您必须提供特定域的逗号分隔“允许”列表。`-cors` 的默认设置是星号 (\$1)，这将允许公开访问。
+  `-dbPath` `value` — DynamoDB 写入数据库文件的目录。如果您未指定此选项，则文件将写入到当前目录。您不能同时指定 `-dbPath` 和 `-inMemory`。
+  `-delayTransientStatuses` — 导致 DynamoDB 为某些操作引入延迟。DynamoDB（可下载版本）几乎可以即时执行某些任务，如针对表和索引的创建/更新/删除操作。但是，DynamoDB 服务需要更多时间才能完成这些任务。设置此参数可帮助在您的计算机上运行的 DynamoDB 更逼真地模拟 DynamoDB Web 服务的行为。（目前，此参数仅为处于 *CREATING* 或 *DELETING* 状态的全局二级索引引入延迟。） 
+  `-help` — 打印使用摘要和选项。
+  `-inMemory` — DynamoDB 将在内存中运行，而不使用数据库文件。停止 DynamoDB 时，不会保存任何数据。您不能同时指定 `-dbPath` 和 `-inMemory`。
+  `-optimizeDbBeforeStartup` — 在计算机上启动 DynamoDB 之前优化底层数据库表。使用此参数时，您还必须指定 `-dbPath`。
+  `-port` `value` — DynamoDB 用于与您的应用程序进行通信的端口号。如果您未指定此选项，则默认端口是 `8000`。
**注意**  
 默认情况下，DynamoDB 使用端口 8000。如果端口 8000 不可用，此命令将引发异常。您可以使用 `-port` 选项指定其他端口号。有关 DynamoDB 运行时选项的完整列表（包括 `-port`），请键入此命令：  
 `java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -help` 
+  `-sharedDb` — 如果您指定 `-sharedDb`，则 DynamoDB 将使用单个数据库文件，而不是针对每个凭证和区域使用不同的文件。
+  `-disableTelemetry` — 指定后，DynamoDB local 将不发送任何遥测信息。
+ `-version` — 显示 DynamoDB local 的版本。

## 设置本地端点
<a name="DynamoDBLocal.Endpoint"></a>

 默认情况下，Amazon SDK 和工具使用 Amazon DynamoDB Web 服务的端点。要将 SDK 和工具用于 DynamoDB 下载版本，您必须指定本地端点：

 `http://localhost:8000` 

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

 您可使用 Amazon Command Line Interface (Amazon CLI) 与可下载的 DynamoDB 交互。

 要访问本地运行的 DynamoDB，请使用 `--endpoint-url` 参数。以下是使用 Amazon CLI 列出计算机上的 DynamoDB 中的表的示例。

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

**注意**  
 Amazon CLI 不能使用 DynamoDB 的可下载版本作为默认端点。因此，您必须对每个`--endpoint-url` 命令指定 Amazon CLI。

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

 指定端点的方法取决于要使用的编程语言和 Amazon SDK。下面几节介绍如何执行此操作：
+  [Java：设置 Amazon 区域和端点](CodeSamples.Java.md#CodeSamples.Java.RegionAndEndpoint)（DynamoDB local 支持适用于 Java 的 Amazon SDK V1 和 V2） 
+ CodeSamples.Java.RegionAndEndpoint [.NET：设置 Amazon 区域和端点](CodeSamples.DotNet.md#CodeSamples.DotNet.RegionAndEndpoint) 

## 可下载的 DynamoDB 和 DynamoDB Web 服务之间的差异
<a name="DynamoDBLocal.Differences"></a>

 DynamoDB 下载版本仅适合用于开发和测试。相比而言，DynamoDB Web 服务是一项具备可扩展性、可用性和持久性特点的托管服务，非常适合在生产中使用。

 DynamoDB 下载版本与该 Web 服务的差别如下：
+ 在客户端层面上不支持 Amazon Web Services 区域和不同的 Amazon Web Services 账户。
+  可下载的 DynamoDB 中会忽略预置的吞吐量设置，即使 `CreateTable` 操作需要这些设置也是如此。对于 `CreateTable`，您可以为预置读取和写入吞吐量指定任何数字，即使不使用这些数字也是如此。您每天可以按需调用 `UpdateTable` 任意次数。但是，对预置吞吐量值的任何更改都会忽略。
+  `Scan` 操作将按顺序执行。不支持并行扫描。`Segment` 操作的 `TotalSegments` 和 `Scan` 参数将被忽略。
+  对表数据的读取和写入操作的速度仅受计算机速度的限制。`CreateTable`、`UpdateTable` 和 `DeleteTable` 操作立即发生，表状态始终为“ACTIVE”。仅更改表或全局二级索引的预置吞吐量设置的 `UpdateTable` 操作将立即执行。如果 `UpdateTable` 操作创建或删除任何全局二级索引，则这些索引在常规状态（如，分别为 CREATING 和 DELETING）之后变为 ACTIVE 状态。在此期间，表保持为 ACTIVE 状态。
+  读取操作具有最终一致性。但是，由于 DynamoDB 在计算机上的本地运行速度，大多数读取操作会表现为强一致性。
+  将不跟踪项目集合指标和项目集合大小。在操作响应中返回 Null，而不是项目集合指标。
+  在 DynamoDB 中，每个结果集返回的数据有 1 MB 的限制。DynamoDB Web 服务和下载版本均将强制执行此限制。但是，在查询索引时，DynamoDB 服务将仅计算投影键和属性的大小。而 DynamoDB 的可下载版本则会计算整个项目的大小。
+  如果使用的是 DynamoDB Streams，则创建分片的速率可能不同。在 DynamoDB Web 服务中，分片创建行为部分受表分片活动的影响。在本地运行 DynamoDB 时，不存在表分区活动。在任一情况下，分区都是临时的，因此您的应用程序不应依赖分区行为。
+  可下载 DynamoDB 不会为事务 API 引发 `TransactionConflictExceptions`。我们建议您使用 Java 模拟框架来模拟 DynamoDB 处理程序中的 `TransactionConflictExceptions`，以测试您的应用程序如何响应冲突的事务。
+  在 DynamoDB Web 服务中，无论是通过控制台还是 Amazon CLI 进行访问，表名称都区分大小写。名为 `Authors` 和名为 `authors` 的表可同时作为不同的表存在。在可下载的版本中，表名称不区分大小写，尝试创建这两个表将导致错误。
+ DynamoDB 的可下载版本不支持标记。
+ DynamoDB 的可下载版本会忽略 [ExecuteStatement](https://docs.amazonaws.cn/amazondynamodb/latest/APIReference/API_ExecuteStatement.html) 中的 [Limit](https://docs.amazonaws.cn/amazondynamodb/latest/APIReference/API_ExecuteStatement.html#DDB-ExecuteStatement-request-Limit) 参数。

# DynamoDB local 的发布历史记录
<a name="DynamoDBLocalHistory"></a>

下表介绍每一版的 *DynamoDB local* 中的重大更改。


****  

| 版本 | 更改 | 描述 | 日期 | 
| --- | --- | --- | --- | 
| 3.3.0 |  为全局二级索引添加多属性键支持  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2026 年 1 月 19 日  | 
| 3.2.0 |  修复了多个 Kotlin 版本的兼容性问题  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2026 年 1 月 9 日  | 
| 3.1.0 |  改善了 PartiQL 查询的性能，包括 Joda-time 依赖关系  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2025 年 9 月 14 日  | 
| 3.0.0 |  从 Amazon SDK Java V1 迁移到 V2  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2025 年 7 月 17 日  | 
| 2.6.0 |  在 DynamoDB API 中支持表 ARN 作为表名称 性能修复和安全更新  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2025 年 3 月 13 日  | 
| 2.5.4 |  对 Jetty 依赖项的升级  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2024 年 12 月 12 日  | 
| 2.5.3 |  在 Log4j Core 中将 Jackson 依赖项升级到 2.17.x（解决 CVE-2022-1471）  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2024 年 11 月 6 日  | 
| 2.5.2 | 更新表工作流的错误修复 | [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  | 2024 年 6 月 20 日 | 
| 2.5.1 | 针对 OndemandThroughPut 功能中引入错误的补丁  | [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html) | 2024 年 6 月 5 日 | 
| 2.5.0 |  支持按需表、`ReturnValuesOnConditionCheckFailure`、`BatchExecuteStatement` 和 `ExecuteTransactionRequest` 的可配置最大吞吐量  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2024 年 5 月 28 日  | 
| 2.4.0 |  支持 `ReturnValuesOnConditionCheckFailure` – 嵌入式模式  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2024 年 4 月 17 日  | 
| 2.3.0 |  Jetty 和 JDK 升级  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2024 年 3 月 14 日  | 
| 2.2.0 |  增加了对表删除保护和 `ReturnValuesOnConditionCheckFailure` 参数的支持  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 12 月 14 日  | 
| 2.1.0 |  支持 Maven 项目的 SQLLite 原生库并添加遥测功能  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 10 月 23 日  | 
| 2.0.0 |  从 javax 迁移到 jakarta 命名空间和 JDK11 支持  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 7 月 5 日  | 
| 1.25.1 |  在 Log4j Core 中将 Jackson 依赖项升级到 2.17.x（解决 CVE-2022-1471）  |  在 Log4j Core 中将 Jackson 依赖项升级到 2.17.x（解决 CVE-2022-1471），以解决 SnakeYAML 库（这是一个传递依赖项）中的一个严重安全漏洞  |  2024 年 11 月 6 日  | 
| 1.25.0 |  增加了对表删除保护和 `ReturnValuesOnConditionCheckFailure` 参数的支持  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 12 月 18 日  | 
| 1.24.0 |  支持 Maven 项目的 SQLLite 原生库并添加遥测功能  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 10 月 23 日  | 
| 1.23.0 |  处理服务器启动时的无效访问和私密密钥  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 6 月 28 日  | 
| 1.22.0 |  支持 PartiQL 的限制操作  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 6 月 8 日  | 
| 1.21.0 |  每个事务支持 100 个操作  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 1 月 26 日  | 
| 1.20.0 |  增加了对 M1 Mac 的支持  |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2022 年 9 月 12 日  | 
| 1.19.0 |  升级了 PartiQL 解析器  |  升级了 PartiQL 解析器和其他相关库  |  2022 年 7 月 27 日  | 
| 1.18.0 | 升级了 log4j-core 和 Jackson-core | 将 log4j-core 升级到 2.17.1，将 Jackson-core 2.10.x 升级到 2.12.0 | 2022 年 1 月 10 日 | 
| 1.17.2 | 升级了 log4j-core | 将 log4j-core 依赖项升级到版本 2.16 | 2021 年 1 月 16 日 | 
| 1.17.1 | 升级了 log4j-core | 更新了 log4j-core 依赖项，以修补零日漏洞来防止远程代码执行 – Log4Shel | 2021 年 1 月 10 日 | 
| 1.17.0 | 已弃用 Javascript Web Shell |  [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  | 2021 年 1 月 8 日 | 

# DynamoDB local 中的遥测
<a name="DynamoDBLocalTelemetry"></a>

 在 Amazon，我们根据从与客户互动中学到的知识开发和推出服务，并使用客户反馈来迭代我们的产品。遥测是附加信息，可帮助我们更好地了解客户需求、诊断问题并提供特征，以改善客户体验。

 DynamoDB local 收集遥测数据，例如一般使用指标、系统和环境信息以及错误。有关收集的遥测类型的详细信息，请参阅[收集的信息类型](#DynamoDBLocalTelemetry.TypesOfInformationCollected)。

 DynamoDB local 不收集诸如用户名或电子邮件地址等个人信息。它也不会提取敏感的项目级信息。

 作为客户，您控制着是否开启遥测功能，并且可以随时更改设置。如果遥测保持开启状态，DynamoDB local 将在后台发送遥测数据，无需任何额外的客户互动。

## 使用命令行选项关闭遥测功能
<a name="DynamoDBLocalTelemetry.cli"></a>

 启动 DynamoDB local 时，您可以使用命令行选项 `-disableTelemetry` 关闭遥测功能。有关更多信息，请参阅 [命令行选项](DynamoDBLocal.UsageNotes.md#DynamoDBLocal.CommandLineOptions)。

## 关闭单个会话的遥测功能
<a name="DynamoDBLocalTelemetry.TurnOffTelemetrySingleSession"></a>

 在 macOS 和 Linux 操作系统中，您可以关闭单个会话的遥测功能。要关闭当前会话的遥测功能，请运行以下命令将环境变量 `DDB_LOCAL_TELEMETRY` 设置为 `false`。对每个新终端或会话重复此命令。

```
export DDB_LOCAL_TELEMETRY=0
```

## 在所有会话中关闭配置文件的遥测功能
<a name="DynamoDBLocalTelemetry.TurnOffTelemetryForAllSessions"></a>

 当您在操作系统上运行 DynamoDB local 时，运行以下命令以关闭所有会话的遥测功能。

**在 Linux 中关闭遥测功能**

1.  运行：

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

1.  运行：

   ```
   source ~/.profile
   ```

**在 macOS 中关闭遥测功能**

1.  运行：

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

1.  运行：

   ```
   source ~/.profile
   ```

**在 Windows 中关闭遥测功能**

1.  运行：

   ```
   setx DDB_LOCAL_TELEMETRY 0
   ```

1.  运行：

   ```
   refreshenv
   ```

## 使用嵌入 Maven 项目的 DynamoDB local 关闭遥测
<a name="DynamoDBLocalTelemetry.maven"></a>

 可以使用嵌入 Maven 项目的 DynamoDB local 关闭遥测功能。

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

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

## 收集的信息类型
<a name="DynamoDBLocalTelemetry.TypesOfInformationCollected"></a>
+  **使用信息** — 通用遥测信息，例如服务器启动/停止以及调用的 API 或操作。
+  **系统和环境信息** — Java 版本、操作系统（Windows、Linux 或 macOS）、DynamoDB local 运行的环境（例如，独立 JAR、Docker 容器或作为 Maven 依赖项）以及使用情况属性的哈希值。

## 了解更多
<a name="DynamoDBLocalTelemetry.LearnMore"></a>

 DynamoDB local 收集的遥测数据符合 Amazon 数据隐私策略。有关更多信息，请参阅下列内容：
+  [Amazon 服务条款](https://www.amazonaws.cn/service-terms/) 
+  [数据隐私常见问题解答](https://www.amazonaws.cn/compliance/data-privacy-faq/) 

# 第 1 步：在 DynamoDB 中创建表
<a name="getting-started-step-1"></a>

在这一步中，您将在 Amazon DynamoDB 中创建一个 `Music` 表。该表具有以下详细信息：
+ 分区键 — `Artist`
+ 排序键 — `SongTitle`

有关表操作的更多信息，请参阅 [使用 DynamoDB 中的表和数据](WorkingWithTables.md)。

**注意**  
开始之前，请确保您已完成 [先决条件](GettingStartedDynamoDB.md#GettingStarted.SettingUp.DynamoWebService) 中的步骤。

## Amazon Web Services 管理控制台
<a name="getting-started-step-1-Console"></a>

要使用 DynamoDB 控制台创建新的 `Music` 表：

1. 登录 Amazon Web Services 管理控制台，打开 DynamoDB 控制台：[https://console.aws.amazon.com/dynamodb/](https://console.amazonaws.cn/dynamodb/)。

1. 在左侧导航窗格中，选择 **表**。

1. 选择**创建表**。

1. 按以下所示输入**表详细信息**：

   1. 对于**表名称**，输入 **Music**。

   1. 对于**分区键**，输入 **Artist**。

   1. 对于**排序键**，输入 **SongTitle**。

1. 对于**表设置**，保留**默认设置**中的默认选择内容。

1. 选择**创建表**以创建表。  
![\[“创建表”页面，其中已填写表详细信息。\]](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/images/GettingStarted/CreateTableMusic.png)

1. 在表处于 `ACTIVE` 状态后，建议您按照以下步骤在表上启用 [DynamoDB 的时间点备份](Point-in-time-recovery.md)。

   1. 选择表名以打开表。

   1. 选择**备份**。

   1. 在**时间点故障恢复（PITR）**部分中选择**编辑**。

   1. 在**编辑时间点故障恢复设置**页面上，选择**开启时间点故障恢复**。

   1. 选择**保存更改**。

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

以下 Amazon CLI 示例使用 `create-table` 创建一个新的 `Music` 表。

**Linux**

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

**Windows CMD**

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

使用 `create-table` 返回以下示例结果。

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

请注意，`TableStatus` 字段的值设置为 `CREATING`。

要验证 DynamoDB 是否已完成创建 `Music` 表，请使用 `describe-table` 命令。

**Linux**

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

**Windows CMD**

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

此命令将返回以下结果。在 DynamoDB 创建完表后，`TableStatus` 字段的值将设置为 `ACTIVE`。

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

表处于 `ACTIVE` 状态后，通过运行以下命令在表上启用 [DynamoDB 的时间点备份](Point-in-time-recovery.md)就被认为是最佳实践：

**Linux**

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

**Windows CMD**

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

此命令将返回以下结果。

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

**注意**  
使用时间点故障恢复实现连续备份会带来成本影响。有关定价的更多信息，请参阅 [Amazon DynamoDB 定价](https://www.amazonaws.cn/dynamodb/pricing)。

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

以下代码示例显示如何使用 Amazon SDK 创建 DynamoDB 表。

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

**适用于 .NET 的 Amazon SDK (v4)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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;
        }
    }
```
+  有关 API 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [CreateTable](https://docs.amazonaws.cn/goto/DotNetSDKV4/dynamodb-2012-08-10/CreateTable)。

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

**Amazon CLI 及 Bash 脚本**  
 查看 GitHub，了解更多信息。查找完整示例，了解如何在 [Amazon 代码示例存储库](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
}
```
本示例中使用的实用程序函数。  

```
###############################################################################
# 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
}
```
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [CreateTable](https://docs.amazonaws.cn/goto/aws-cli/dynamodb-2012-08-10/CreateTable)。

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

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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);
}
```
等待表变为活动状态的代码。  

```
//! 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;
}
```
+  有关 API 详细信息，请参阅《适用于 C\$1\$1 的 Amazon SDK API Reference》**中的 [CreateTable](https://docs.amazonaws.cn/goto/SdkForCpp/dynamodb-2012-08-10/CreateTable)。

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

**Amazon CLI**  
**示例 1：创建带标签的表**  
以下 `create-table` 示例使用指定的属性和键架构创建名为 `MusicCollection` 的表。此表使用预调配的吞吐量，并使用 Amazon 默认拥有的 CMK 进行静态加密。该命令还将标签应用于该表，其键为 `Owner`，值为 `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
```
输出：  

```
{
    "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"
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[表的基本操作](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)。  
**示例 2：在按需模式下创建表**  
以下示例使用按需模式（而不是预调配吞吐量模式）创建名为 `MusicCollection` 的表。这对于工作负载不可预测的表很有用。  

```
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
```
输出：  

```
{
    "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"
        }
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[表的基本操作](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)。  
**示例 3：创建表并使用客户托管的 CMK 对其进行加密**  
以下示例创建一个名为 `MusicCollection` 的表并使用客户托管的 CMK 对其进行加密。  

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

```
{
    "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"
        }
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[表的基本操作](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)。  
**示例 4：创建具有本地二级索引的表**  
以下示例使用指定的属性和键架构来创建名为 `MusicCollection` 且其本地二级索引名为 `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\"]
                }
            }
        ]"
```
输出：  

```
{
    "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"
            }
        ]
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[表的基本操作](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)。  
**示例 5：创建具有全局二级索引的表**  
以下示例创建一个名为 `GameScores` 且其全局二级索引名为 `GameTitleIndex` 的表。基表的分区键为 `UserId`，排序键为 `GameTitle`，可以有效地找到特定游戏的单个用户的最佳分数，而 GSI 则具有分区键 `GameTitle` 和排序键 `TopScore`，允许您快速找到特定游戏的总体最高分。  

```
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
                }
            }
        ]"
```
输出：  

```
{
    "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"
            }
        ]
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[表的基本操作](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)。  
**示例 6：一次创建一个具有多个全局二级索引的表**  
以下示例创建一个名为 `GameScores` 且具有两个全局二级索引的表。GSI 架构通过文件传递，而不是通过命令行传递。  

```
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
```
 的内容`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
        }
    }
]
```
输出：  

```
{
    "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"
            }
        ]
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[表的基本操作](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)。  
**示例 7：创建启用了 Streams 的表**  
以下示例创建一个名为 `GameScores` 且启用了 DynamoDB Streams 的表。每个项的新旧映像都将写入流中。  

```
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
```
输出：  

```
{
    "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"
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[表的基本操作](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)。  
**示例 8：创建启用了 Keys-Only Stream 的表**  
以下示例将创建一个名为 `GameScores` 且启用了 DynamoDB Streams 的表。仅将所修改项的键属性写入流中。  

```
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
```
输出：  

```
{
    "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
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[更改 DynamoDB Streams 的数据捕获](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/Streams.html)。  
**示例 9：使用 Standard Infrequent Access 类创建表**  
以下示例创建名为 `GameScores` 的表并分配 Standard-Infrequent Access（DynamoDB 标准-IA）表类。此表类针对主要的存储成本进行了优化。  

```
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
```
输出：  

```
{
    "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
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[表类](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/HowItWorks.TableClasses.html)。  
**示例 10：创建启用了删除保护功能的表**  
以下示例创建一个名为 `GameScores` 的表并启用删除保护。  

```
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
```
输出：  

```
{
    "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
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[使用删除保护](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeletionProtection)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [CreateTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/create-table.html)。

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

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
}
```
+  有关 API 详细信息，请参阅《适用于 Go 的 Amazon SDK API Reference》**中的 [CreateTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.CreateTable)。

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

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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 "";
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [CreateTable](https://docs.amazonaws.cn/goto/SdkForJavaV2/dynamodb-2012-08-10/CreateTable)。

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

**SDK for JavaScript (v3)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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;
};
```
+  有关更多信息，请参阅《适用于 JavaScript 的 Amazon SDK 开发人员指南》[https://docs.amazonaws.cn/sdk-for-javascript/v3/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table](https://docs.amazonaws.cn/sdk-for-javascript/v3/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table)。
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [CreateTable](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/CreateTableCommand)。

**SDK for JavaScript (v2)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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);
  }
});
```
+  有关更多信息，请参阅《适用于 JavaScript 的 Amazon SDK 开发人员指南》[https://docs.amazonaws.cn/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table](https://docs.amazonaws.cn/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table)。
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [CreateTable](https://docs.amazonaws.cn/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/CreateTable)。

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

**SDK for Kotlin**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Kotlin API Reference》**中的 [CreateTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

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

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples) 中查找完整示例，了解如何进行设置和运行。
创建表。  

```
        $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],
        ]);
    }
```
+  有关 API 详细信息，请参阅《适用于 PHP 的 Amazon SDK API Reference》**中的 [CreateTable](https://docs.amazonaws.cn/goto/SdkForPHPV3/dynamodb-2012-08-10/CreateTable)。

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

**适用于 PowerShell V4 的工具**  
**示例 1：此示例创建一个名为 Thread 的表，该表的主键由“ForumName”（键类型哈希）和“Subject”（键类型范围）组成。用于构造表的架构可以通过管道传输到所示的每个 cmdlet 中，也可以使用 -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
```
**输出：**  

```
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  : {}
```
**示例 2：此示例创建一个名为 Thread 的表，该表的主键由“ForumName”（键类型哈希）和“Subject”（键类型范围）组成。还定义了本地二级索引。本地二级索引的键将根据表上的主哈希键（ForumName）自动设置。用于构造表的架构可以通过管道传输到所示的每个 cmdlet 中，也可以使用 -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
```
**输出：**  

```
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}
```
**示例 3：此示例展示了如何使用单个管道创建一个名为 Thread 的表，该表的主键由“ForumName”（键类型哈希）和“Subject”（键类型范围）以及本地二级索引组成。如果管道或 -Schema 参数中未提供 TableSchema 对象，则 Add-DDBKeySchema 和 Add-DDBIndexSchema 会为您创建一个新的 TableSchema 对象。**  

```
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
```
**输出：**  

```
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}
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V4)》**中的 [CreateTable](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建一个名为 Thread 的表，该表的主键由“ForumName”（键类型哈希）和“Subject”（键类型范围）组成。用于构造表的架构可以通过管道传输到所示的每个 cmdlet 中，也可以使用 -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
```
**输出：**  

```
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  : {}
```
**示例 2：此示例创建一个名为 Thread 的表，该表的主键由“ForumName”（键类型哈希）和“Subject”（键类型范围）组成。还定义了本地二级索引。本地二级索引的键将根据表上的主哈希键（ForumName）自动设置。用于构造表的架构可以通过管道传输到所示的每个 cmdlet 中，也可以使用 -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
```
**输出：**  

```
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}
```
**示例 3：此示例展示了如何使用单个管道创建一个名为 Thread 的表，该表的主键由“ForumName”（键类型哈希）和“Subject”（键类型范围）以及本地二级索引组成。如果管道或 -Schema 参数中未提供 TableSchema 对象，则 Add-DDBKeySchema 和 Add-DDBIndexSchema 会为您创建一个新的 TableSchema 对象。**  

```
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
```
**输出：**  

```
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}
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V5)》**中的 [CreateTable](https://docs.amazonaws.cn/powershell/v5/reference)。

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

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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 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
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [CreateTable](https://docs.amazonaws.cn/goto/boto3/dynamodb-2012-08-10/CreateTable)。

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

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
```
+  有关 API 详细信息，请参阅《适用于 Ruby 的 Amazon SDK API Reference》**中的 [CreateTable](https://docs.amazonaws.cn/goto/SdkForRubyV3/dynamodb-2012-08-10/CreateTable)。

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

**适用于 Rust 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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))
        }
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Rust API Reference》**中的 [CreateTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.create_table)。

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

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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.
```
+  有关 API 详细信息，请参阅《Amazon SDK for SAP ABAP API Reference》**中的 [CreateTable](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

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

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
        }
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Swift API 参考》**中的 [CreateTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/createtable(input:))。

------

有关更多 DynamoDB 示例，请参阅[适用于使用 Amazon SDK 的 DynamoDB 的代码示例](service_code_examples.md)。

创建新表后，继续完成 [第 2 步：将数据写入 DynamoDB 表](getting-started-step-2.md)。

# 第 2 步：将数据写入 DynamoDB 表
<a name="getting-started-step-2"></a>

在此步骤中，您将多个项目插入到在 [第 1 步：在 DynamoDB 中创建表](getting-started-step-1.md) 中创建的 `Music` 表。

有关写入操作的更多信息，请参阅 [写入项目](WorkingWithItems.md#WorkingWithItems.WritingData)。

## Amazon Web Services 管理控制台
<a name="getting-started-step-2-Console"></a>

按照这些步骤使用 DynamoDB 控制台向 `Music` 表写入数据。

1. 打开 DynamoDB 控制台：[https://console.aws.amazon.com/dynamodb/](https://console.amazonaws.cn/dynamodb/)。

1. 在左侧导航窗格中，选择 **表**。

1. 在**表**页面上，选择 **Music** 表。

1. 选择 **Explore table items**（浏览表项目）。

1. 在**返回的项目**部分中，选择**创建项目**。

1. 在**创建项目**页面上，执行以下操作，将项目添加到表中：

   1. 选择 **Add new attribute (添加新属性)**，然后选择 **Number (数字)**。

   1. 对于“属性名称”，输入 **Awards**。

   1. 重复此过程来创建 **String** 类型的 **AlbumTitle**。

   1. 为项目输入以下值：

      1. 对于 **Artist**，输入 **No One You Know**。

      1. 对于 **SongTitle**，输入 **Call Me Today**。

      1. 对于 **AlbumTitle**，输入 **Somewhat Famous**。

      1. 对于 **Awards**，输入 **1**。

1. 选择 **Create Item (创建项目)**。

1. 重复此过程并使用以下值创建另一个项目：

   1. 对于 **Artist**，输入 **Acme Band**。

   1. 对于 **SongTitle**，输入 **Happy Day**。

   1. 对于 **AlbumTitle**，输入 **Songs About Life**。

   1. 对于 **Awards**，输入 **10**。

1. 再次执行此操作以创建另一个具有与上一步相同的**艺术家**但其他属性值不同的项目：

   1. 对于 **Artist**，输入 **Acme Band**。

   1. 对于 **SongTitle**，输入 **PartiQL Rocks**。

   1. 对于 **AlbumTitle**，输入 **Another Album Title**。

   1. 对于 **Awards**，输入 **8**。

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

下面的 Amazon CLI 示例在 `Music` 表中创建多个新项目。您可以通过 DynamoDB API 或 [PartiQL](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/ql-reference.html)（一种适用于 DynamoDB 的 SQL 兼容查询语言）执行此操作。

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

**Linux**

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

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

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

**Windows CMD**

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

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

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

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

**Linux**

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

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

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

**Windows CMD**

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

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

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

有关使用 PartiQL 写入数据的更多信息，请参阅 [PartiQL 插入语句](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/ql-reference.insert.html)。

------

要详细了解 DynamoDB 中支持的数据类型，请参阅[数据类型](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes)。

要详细了解如何在 JSON 中表示 DynamoDB 数据类型，请参阅[属性值](https://docs.amazonaws.cn/amazondynamodb/latest/APIReference/API_AttributeValue.html)。

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

以下代码示例显示如何使用 Amazon SDK 向 DynamoDB 表中写入项目。

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

**适用于 .NET 的 Amazon SDK (v4)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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;
        }
    }
```
+  有关 API 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [PutItem](https://docs.amazonaws.cn/goto/DotNetSDKV4/dynamodb-2012-08-10/PutItem)。

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

**Amazon CLI 及 Bash 脚本**  
 查看 GitHub，了解更多信息。查找完整示例，了解如何在 [Amazon 代码示例存储库](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

}
```
本示例中使用的实用程序函数。  

```
###############################################################################
# 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
}
```
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [PutItem](https://docs.amazonaws.cn/goto/aws-cli/dynamodb-2012-08-10/PutItem)。

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

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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);
}
```
等待表变为活动状态的代码。  

```
//! 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;
}
```
+  有关 API 详细信息，请参阅《适用于 C\$1\$1 的 Amazon SDK API Reference》**中的 [PutItem](https://docs.amazonaws.cn/goto/SdkForCpp/dynamodb-2012-08-10/PutItem)。

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

**Amazon CLI**  
**示例 1：向表中添加项**  
以下 `put-item` 示例将新项添加到 *MusicCollection* 表中。  

```
aws dynamodb put-item \
    --table-name MusicCollection \
    --item file://item.json \
    --return-consumed-capacity TOTAL \
    --return-item-collection-metrics SIZE
```
 的内容`item.json`：  

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

```
{
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    },
    "ItemCollectionMetrics": {
        "ItemCollectionKey": {
            "Artist": {
                "S": "No One You Know"
            }
        },
        "SizeEstimateRangeGB": [
            0.0,
            1.0
        ]
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[写入项](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)。  
**示例 2：有条件地覆盖表中的项**  
仅当 `MusicCollection` 表中的现有项具有值为 `Greatest Hits` 的 `AlbumTitle` 属性时，以下 `put-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
```
 的内容`item.json`：  

```
{
    "Artist": {"S": "No One You Know"},
    "SongTitle": {"S": "Call Me Today"},
    "AlbumTitle": {"S": "Somewhat Famous"}
}
```
 的内容`names.json`：  

```
{
    "#A": "AlbumTitle"
}
```
 的内容`values.json`：  

```
{
    ":A": {"S": "Greatest Hits"}
}
```
输出：  

```
{
    "Attributes": {
        "AlbumTitle": {
            "S": "Greatest Hits"
        },
        "Artist": {
            "S": "No One You Know"
        },
        "SongTitle": {
            "S": "Call Me Today"
        }
    }
}
```
如果键已存在，您应看到以下输出：  

```
A client error (ConditionalCheckFailedException) occurred when calling the PutItem operation: The conditional request failed.
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[写入项](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [PutItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/put-item.html)。

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

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
}
```
定义本示例中使用的 Movie 结构。  

```
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"])
}
```
+  有关 API 详细信息，请参阅《适用于 Go 的 Amazon SDK API Reference》**中的 [PutItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.PutItem)。

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

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)中查找完整示例，了解如何进行设置和运行。
使用 [DynamoDbClient](https://docs.amazonaws.cn/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);
        }
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [PutItem](https://docs.amazonaws.cn/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem)。

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

**SDK for JavaScript (v3)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)中查找完整示例，了解如何进行设置和运行。
此示例使用文档客户端来简化在 DynamoDB 中处理项目的过程。有关 API 详细信息，请参阅 [PutCommand](https://docs.amazonaws.cn/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;
};
```
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [PutItem](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/PutItemCommand)。

**SDK for JavaScript (v2)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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: "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);
  }
});
```
使用 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);
  }
});
```
+  有关更多信息，请参阅《适用于 JavaScript 的 Amazon SDK 开发人员指南》[https://docs.amazonaws.cn/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write.html#dynamodb-example-table-read-write-writing-an-item](https://docs.amazonaws.cn/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write.html#dynamodb-example-table-read-write-writing-an-item)。
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [PutItem](https://docs.amazonaws.cn/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/PutItem)。

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

**SDK for Kotlin**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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.")
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Kotlin API Reference》**中的 [PutItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

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

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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);
    }
```
+  有关 API 详细信息，请参阅《适用于 PHP 的 Amazon SDK API Reference》**中的 [PutItem](https://docs.amazonaws.cn/goto/SdkForPHPV3/dynamodb-2012-08-10/PutItem)。

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

**适用于 PowerShell V4 的工具**  
**示例 1：创建一个新项目，或将现有项目替换为新项目。**  

```
$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
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V4)》**中的 [PutItem](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：创建一个新项目，或将现有项目替换为新项目。**  

```
$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
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V5)》**中的 [PutItem](https://docs.amazonaws.cn/powershell/v5/reference)。

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

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [PutItem](https://docs.amazonaws.cn/goto/boto3/dynamodb-2012-08-10/PutItem)。

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

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
```
+  有关 API 详细信息，请参阅《适用于 Ruby 的 Amazon SDK API Reference》**中的 [PutItem](https://docs.amazonaws.cn/goto/SdkForRubyV3/dynamodb-2012-08-10/PutItem)。

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

**适用于 Rust 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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,
    })
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Rust API Reference》**中的 [PutItem](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.put_item)。

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

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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.
```
+  有关 API 详细信息，请参阅《Amazon SDK for SAP ABAP API Reference》**中的 [PutItem](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

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

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Swift API 参考》**中的 [PutItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/putitem(input:))。

------

有关更多 DynamoDB 示例，请参阅[适用于使用 Amazon SDK 的 DynamoDB 的代码示例](service_code_examples.md)。

将数据写入表后，继续转到 [第 3 步：从 DynamoDB 表中读取数据](getting-started-step-3.md)。

# 第 3 步：从 DynamoDB 表中读取数据
<a name="getting-started-step-3"></a>

在此步骤中，您将读取在[第 2 步：将数据写入 DynamoDB 表](getting-started-step-2.md)中创建的一个项目。可以通过指定 `Artist` 和 `SongTitle`，使用 DynamoDB 控制台或 Amazon CLI 从 `Music` 表读取项目。

有关 DynamoDB 中的读取操作的更多信息，请参见 [读取项目](WorkingWithItems.md#WorkingWithItems.ReadingData)。

## Amazon Web Services 管理控制台
<a name="getting-started-step-3-Console"></a>

按照以下步骤，使用 DynamoDB 控制台从 `Music` 表读取数据。

1. 打开 DynamoDB 控制台：[https://console.aws.amazon.com/dynamodb/](https://console.amazonaws.cn/dynamodb/)。

1. 在左侧导航窗格中，选择 **表**。

1. 在**表**页面上，选择 **Music** 表。

1. 选择**浏览表项目**。

1. 在**返回的项目**部分中，查看存储在表中的项目列表，这些项目按 `Artist` 和 `SongTitle` 排序。列表中的第一项是名为 **Acme Band** 的 **Artist**，其 **SongTitle** 为 **PartiQL Rocks**。

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

下面的 Amazon CLI 示例更新 `Music` 表的项目。您可以通过 DynamoDB API 或 [PartiQL](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/ql-reference.html)（一种适用于 DynamoDB 的 SQL 兼容查询语言）执行此操作。

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

**注意**  
DynamoDB 的默认行为是最终一致性读取。下面用 `consistent-read` 参数演示较强的一致性读取。

**Linux**

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

**Windows CMD**

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

使用 `get-item` 返回以下示例结果。

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

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

**Linux**

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

**Windows CMD**

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

使用 PartiQL `Select` 语句返回以下示例结果。

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

有关使用 PartiQL 读取数据的更多信息，请参阅 [PartiQL 选择语句](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/ql-reference.SELECT.html)。

------

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

以下代码示例显示如何使用 Amazon SDK 读取 DynamoDB 表中的项目。

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

**适用于 .NET 的 Amazon SDK (v4)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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;
        }
    }
```
+  有关 API 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [GetItem](https://docs.amazonaws.cn/goto/DotNetSDKV4/dynamodb-2012-08-10/GetItem)。

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

**Amazon CLI 及 Bash 脚本**  
 查看 GitHub，了解更多信息。查找完整示例，了解如何在 [Amazon 代码示例存储库](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
}
```
本示例中使用的实用程序函数。  

```
###############################################################################
# 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
}
```
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [GetItem](https://docs.amazonaws.cn/goto/aws-cli/dynamodb-2012-08-10/GetItem)。

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

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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();
}
```
+  有关 API 详细信息，请参阅《适用于 C\$1\$1 的 Amazon SDK API Reference》**中的 [GetItem](https://docs.amazonaws.cn/goto/SdkForCpp/dynamodb-2012-08-10/GetItem)。

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

**Amazon CLI**  
**示例 1：读取表中的项**  
以下 `get-item` 示例将从 `MusicCollection` 表中检索项。该表具有 hash-and-range 主键（`Artist` 和 `SongTitle`），因此，您必须指定这两个属性。该命令还请求有关操作所用的读取容量的信息。  

```
aws dynamodb get-item \
    --table-name MusicCollection \
    --key file://key.json \
    --return-consumed-capacity TOTAL
```
 的内容`key.json`：  

```
{
    "Artist": {"S": "Acme Band"},
    "SongTitle": {"S": "Happy Day"}
}
```
输出：  

```
{
    "Item": {
        "AlbumTitle": {
            "S": "Songs About Life"
        },
        "SongTitle": {
            "S": "Happy Day"
        },
        "Artist": {
            "S": "Acme Band"
        }
    },
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[读取项](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData)。  
**示例 2：使用一致性读取来读取项**  
以下示例使用强一致性读取从 `MusicCollection` 表中检索项。  

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

```
{
    "Artist": {"S": "Acme Band"},
    "SongTitle": {"S": "Happy Day"}
}
```
输出：  

```
{
    "Item": {
        "AlbumTitle": {
            "S": "Songs About Life"
        },
        "SongTitle": {
            "S": "Happy Day"
        },
        "Artist": {
            "S": "Acme Band"
        }
    },
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[读取项](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData)。  
**示例 3：检索项的特定属性**  
以下示例使用投影表达式仅检索所需项的三个属性。  

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

```
{
    "#T": "Title",
    "#C": "ProductCategory",
    "#P": "Price"
}
```
输出：  

```
{
    "Item": {
        "Price": {
            "N": "20"
        },
        "Title": {
            "S": "Book 102 Title"
        },
        "ProductCategory": {
            "S": "Book"
        }
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[读取项](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [GetItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/get-item.html)。

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

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
}
```
定义本示例中使用的 Movie 结构。  

```
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"])
}
```
+  有关 API 详细信息，请参阅《适用于 Go 的 Amazon SDK API Reference》**中的 [GetItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.GetItem)。

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

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)中查找完整示例，了解如何进行设置和运行。
使用 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);
        }
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [GetItem](https://docs.amazonaws.cn/goto/SdkForJavaV2/dynamodb-2012-08-10/GetItem)。

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

**SDK for JavaScript (v3)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)中查找完整示例，了解如何进行设置和运行。
此示例使用文档客户端来简化在 DynamoDB 中处理项目的过程。有关 API 详细信息，请参阅 [GetCommand](https://docs.amazonaws.cn/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;
};
```
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [GetItem](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/GetItemCommand)。

**SDK for JavaScript (v2)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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: "TABLE",
  Key: {
    KEY_NAME: { N: "001" },
  },
  ProjectionExpression: "ATTRIBUTE_NAME",
};

// Call DynamoDB to read the item from the table
ddb.getItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Item);
  }
});
```
使用 DynamoDB 文档客户端从表中获取项目。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB document client
var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

var params = {
  TableName: "EPISODES_TABLE",
  Key: { KEY_NAME: VALUE },
};

docClient.get(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Item);
  }
});
```
+  有关更多信息，请参阅《适用于 JavaScript 的 Amazon SDK 开发人员指南》[https://docs.amazonaws.cn/sdk-for-javascript/v2/developer-guide/dynamodb-example-dynamodb-utilities.html#dynamodb-example-document-client-get](https://docs.amazonaws.cn/sdk-for-javascript/v2/developer-guide/dynamodb-example-dynamodb-utilities.html#dynamodb-example-document-client-get)。
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [GetItem](https://docs.amazonaws.cn/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/GetItem)。

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

**SDK for Kotlin**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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)
        }
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Kotlin API Reference》**中的 [GetItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

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

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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,
        ]);
    }
```
+  有关 API 详细信息，请参阅《适用于 PHP 的 Amazon SDK API Reference》**中的 [GetItem](https://docs.amazonaws.cn/goto/SdkForPHPV3/dynamodb-2012-08-10/GetItem)。

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

**适用于 PowerShell V4 的工具**  
**示例 1：返回带有分区键 SongTitle 和排序键 Artist 的 DynamoDB 项目。**  

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

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**输出：**  

```
Name                           Value
----                           -----
Genre                          Country
SongTitle                      Somewhere Down The Road
Price                          1.94
Artist                         No One You Know
CriticRating                   9
AlbumTitle                     Somewhat Famous
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V4)》**中的 [GetItem](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：返回带有分区键 SongTitle 和排序键 Artist 的 DynamoDB 项目。**  

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

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**输出：**  

```
Name                           Value
----                           -----
Genre                          Country
SongTitle                      Somewhere Down The Road
Price                          1.94
Artist                         No One You Know
CriticRating                   9
AlbumTitle                     Somewhat Famous
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V5)》**中的 [GetItem](https://docs.amazonaws.cn/powershell/v5/reference)。

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

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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"]
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [GetItem](https://docs.amazonaws.cn/goto/boto3/dynamodb-2012-08-10/GetItem)。

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

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
```
+  有关 API 详细信息，请参阅《适用于 Ruby 的 Amazon SDK API Reference》**中的 [GetItem](https://docs.amazonaws.cn/goto/SdkForRubyV3/dynamodb-2012-08-10/GetItem)。

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

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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.
```
+  有关 API 详细信息，请参阅《Amazon SDK for SAP ABAP API Reference》**中的 [GetItem](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

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

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
        }
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Swift API 参考》**中的 [GetItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/getitem(input:))。

------

有关更多 DynamoDB 示例，请参阅[适用于使用 Amazon SDK 的 DynamoDB 的代码示例](service_code_examples.md)。

要更新表中的数据，请继续 [第 4 步：更新 DynamoDB 表中的数据](getting-started-step-4.md)。

# 第 4 步：更新 DynamoDB 表中的数据
<a name="getting-started-step-4"></a>

在这一步中，更新在 [第 2 步：将数据写入 DynamoDB 表](getting-started-step-2.md) 中创建的项目。可以使用 DynamoDB 控制台或 Amazon CLI，指定 `Artist`、`SongTitle` 和更新的 `AlbumTitle`，更新 `Music` 表的 `AlbumTitle` 项目。

有关写入操作的更多信息，请参阅 [写入项目](WorkingWithItems.md#WorkingWithItems.WritingData)。

## Amazon Web Services 管理控制台
<a name="getting-started-step-4-Console"></a>

您可以使用 DynamoDB 控制台更新 `Music` 表的数据。

1. 打开 DynamoDB 控制台：[https://console.aws.amazon.com/dynamodb/](https://console.amazonaws.cn/dynamodb/)。

1. 在左侧导航窗格中，选择 **表**。

1. 从表列表中选择 **Music** 表。

1. 选择**浏览表项目**。

1. 在**返回的项目**中，对于 **Artist** 为 **Acme Band** 并且 **SongTitle** 为 **Happy Day** 的项目行，执行以下操作：

   1. 将光标放在名为 **Songs About Life** 的 **AlbumTitle** 上。

   1. 选择“编辑”图标。

   1. 在**编辑字符串**弹出窗口中，输入 **Songs of Twilight**。

   1. 选择**保存**。
**提示**  
或者，要更新项目，请在**返回的项目**部分中执行以下操作：  
选择名为 **Acme Band** 的 **Artist** 并且 **SongTitle** 为 **Happy Day** 的项目行。
从**操作**下拉列表中，选择**编辑项目**。
对于 **AlbumTitle**，输入 **Songs of Twilight**。
选择**保存并关闭**。

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

下面的 Amazon CLI 示例更新 `Music` 表的项目。您可以通过 DynamoDB API 或 [PartiQL](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/ql-reference.html)（一种适用于 DynamoDB 的 SQL 兼容查询语言）执行此操作。

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

**Linux**

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

**Windows CMD**

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

使用 `update-item` 将返回以下示例结果，因为已指定 `return-values ALL_NEW`。

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

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

**Linux**

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

**Windows CMD**

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

使用 `Update` 语句将返回以下示例结果，因为已指定 `RETURNING ALL NEW *`。

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

有关使用 PartiQL 更新数据的更多信息，请参阅 [PartiQL 更新语句](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/ql-reference.update.html)。

------

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

以下代码示例显示如何使用 Amazon SDK 更新 DynamoDB 表中的项目。

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

**适用于 .NET 的 Amazon SDK (v4)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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;
        }
    }
```
+  有关 API 详细信息，请参阅 *适用于 .NET 的 Amazon SDK API 参考*中的 [UpdateItem](https://docs.amazonaws.cn/goto/DotNetSDKV4/dynamodb-2012-08-10/UpdateItem)。

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

**Amazon CLI 及 Bash 脚本**  
 查看 GitHub，了解更多信息。查找完整示例，了解如何在 [Amazon 代码示例存储库](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

}
```
本示例中使用的实用程序函数。  

```
###############################################################################
# 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
}
```
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [UpdateItem](https://docs.amazonaws.cn/goto/aws-cli/dynamodb-2012-08-10/UpdateItem)。

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

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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);
}
```
等待表变为活动状态的代码。  

```
//! 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;
}
```
+  有关 API 详细信息，请参阅 *适用于 C\$1\$1 的 Amazon SDK API 参考*中的 [UpdateItem](https://docs.amazonaws.cn/goto/SdkForCpp/dynamodb-2012-08-10/UpdateItem)。

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

**Amazon CLI**  
**示例 1：更新表中的项**  
下面的 `update-item` 示例更新 `MusicCollection` 表的项目。它会添加一个新属性（`Year`）并修改 `AlbumTitle` 属性。响应中会返回更新后显示的项中的所有属性。  

```
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
```
 的内容`key.json`：  

```
{
    "Artist": {"S": "Acme Band"},
    "SongTitle": {"S": "Happy Day"}
}
```
 的内容`expression-attribute-names.json`：  

```
{
    "#Y":"Year", "#AT":"AlbumTitle"
}
```
 的内容`expression-attribute-values.json`：  

```
{
    ":y":{"N": "2015"},
    ":t":{"S": "Louder Than Ever"}
}
```
输出：  

```
{
    "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
        ]
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[写入项](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)。  
**示例 2：有条件地更新项**  
以下示例将更新 `MusicCollection` 表中的项，但前提是现有项还没有 `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)"
```
 的内容`key.json`：  

```
{
    "Artist": {"S": "Acme Band"},
    "SongTitle": {"S": "Happy Day"}
}
```
 的内容`expression-attribute-names.json`：  

```
{
    "#Y":"Year",
    "#AT":"AlbumTitle"
}
```
 的内容`expression-attribute-values.json`：  

```
{
    ":y":{"N": "2015"},
    ":t":{"S": "Louder Than Ever"}
}
```
如果该项已有 `Year` 属性，DynamoDB 会返回以下输出。  

```
An error occurred (ConditionalCheckFailedException) when calling the UpdateItem operation: The conditional request failed
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[写入项](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [UpdateItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-item.html)。

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

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
}
```
定义本示例中使用的 Movie 结构。  

```
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"])
}
```
+  有关 API 详细信息，请参阅 *适用于 Go 的 Amazon SDK API 参考*中的 [UpdateItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.UpdateItem)。

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

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)中查找完整示例，了解如何进行设置和运行。
使用 [DynamoDbClient](https://docs.amazonaws.cn/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!");
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [UpdateItem](https://docs.amazonaws.cn/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)。

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

**SDK for JavaScript (v3)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)中查找完整示例，了解如何进行设置和运行。
此示例使用文档客户端来简化在 DynamoDB 中处理项目的过程。有关 API 详细信息，请参阅 [UpdateCommand](https://docs.amazonaws.cn/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;
};
```
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [UpdateItem](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)。

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

**SDK for Kotlin**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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")
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Kotlin API Reference》**中的 [UpdateItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

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

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
                ]
            ],
        ]);
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 Amazon SDK API 参考*中的 [UpdateItem](https://docs.amazonaws.cn/goto/SdkForPHPV3/dynamodb-2012-08-10/UpdateItem)。

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

**适用于 PowerShell V4 的工具**  
**示例 1：在带有分区键 SongTitle 和排序键 Artist 的 DynamoDB 项目上将流派属性设置为“Rap”**。  

```
$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
```
**输出：**  

```
Name                           Value
----                           -----
Genre                          Rap
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V4)》**中的 [UpdateItem](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：在带有分区键 SongTitle 和排序键 Artist 的 DynamoDB 项目上将流派属性设置为“Rap”**。  

```
$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
```
**输出：**  

```
Name                           Value
----                           -----
Genre                          Rap
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V5)》**中的 [UpdateItem](https://docs.amazonaws.cn/powershell/v5/reference)。

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

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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 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"]
```
使用包含算术运算的更新表达式更新项目。  

```
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"]
```
只有在项目满足特定条件时才更新项目。  

```
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"]
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python（Boto3）API Reference》**中的 [UpdateItem](https://docs.amazonaws.cn/goto/boto3/dynamodb-2012-08-10/UpdateItem)。

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

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
```
+  有关 API 详细信息，请参阅 *适用于 Ruby 的 Amazon SDK API 参考*中的 [UpdateItem](https://docs.amazonaws.cn/goto/SdkForRubyV3/dynamodb-2012-08-10/UpdateItem)。

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

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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.
```
+  有关 API 详细信息，请参阅《Amazon SDK for SAP ABAP API Reference》**中的 [UpdateItem](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

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

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
        }
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Swift API 参考》**中的 [UpdateItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/updateitem(input:))。

------

有关更多 DynamoDB 示例，请参阅[适用于使用 Amazon SDK 的 DynamoDB 的代码示例](service_code_examples.md)。

要查询 `Music` 表的数据，继续 [第 5 步：查询 DynamoDB 表中的数据](getting-started-step-5.md)。

# 第 5 步：查询 DynamoDB 表中的数据
<a name="getting-started-step-5"></a>

在此步骤中，通过指定 `Artist` 查询写入到 [第 2 步：将数据写入 DynamoDB 表](getting-started-step-2.md) 的 `Music` 表的数据。这将显示与分区键关联的所有歌曲：`Artist`。

有关写入操作的更多信息，请参阅 [在 DynamoDB 中查询表](Query.md)。

## Amazon Web Services 管理控制台
<a name="getting-started-step-5-Console"></a>

按照这些步骤使用 DynamoDB 控制台查询 `Music` 表中的数据。

1. 打开 DynamoDB 控制台：[https://console.aws.amazon.com/dynamodb/](https://console.amazonaws.cn/dynamodb/)。

1. 在左侧导航窗格中，选择 **表**。

1. 从表列表中选择 **Music** 表。

1. 选择**浏览表项目**。

1. 在**扫描或查询项目**中，确保已选择**查询**。

1. 对于 **Partition key (分区键)**，输入 **Acme Band**，然后选择 **Run (运行)**。

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

下面的 Amazon CLI 示例将查询 `Music` 表中的项目。您可以通过 DynamoDB API 或 [PartiQL](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/ql-reference.html)（一种适用于 DynamoDB 的 SQL 兼容查询语言）执行此操作。

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

您可以使用 `query` 并提供分区键来通过 DynamoDB API 查询项目。

**Linux**

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

**Windows CMD**

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

使用 `query` 将返回与此特定 `Artist` 关联的所有歌曲。

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

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

您可以使用 `Select` 语句并提供分区键来通过 PartiQL 查询项目。

**Linux**

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

**Windows CMD**

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

通过此方式使用 `Select` 语句将返回与此特定 `Artist` 关联的所有歌曲。

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

有关使用 PartiQL 查询数据的更多信息，请参阅 [PartiQL 选择语句](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/ql-reference.select.html)。

------

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

以下代码示例显示如何使用 Amazon SDK 查询 DynamoDB 表。

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

**适用于 .NET 的 Amazon SDK (v4)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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;
        }
    }
```
+  有关 API 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [Query](https://docs.amazonaws.cn/goto/DotNetSDKV4/dynamodb-2012-08-10/Query)。

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

**Amazon CLI 及 Bash 脚本**  
 查看 GitHub，了解更多信息。查找完整示例，了解如何在 [Amazon 代码示例存储库](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
}
```
本示例中使用的实用程序函数。  

```
###############################################################################
# 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
}
```
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [Query](https://docs.amazonaws.cn/goto/aws-cli/dynamodb-2012-08-10/Query)。

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

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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;
}
```
+  有关 API 详细信息，请参阅 *适用于 C\$1\$1 的 Amazon SDK API 参考*中的 [Query](https://docs.amazonaws.cn/goto/SdkForCpp/dynamodb-2012-08-10/Query)。

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

**Amazon CLI**  
**示例 1：查询表**  
以下 `query` 示例查询 `MusicCollection` 表中的项。该表具有 hash-and-range 主键（`Artist` 和 `SongTitle`），但此查询仅指定哈希键值。它返回名为“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
```
 的内容`expression-attributes.json`：  

```
{
    ":v1": {"S": "No One You Know"}
}
```
输出：  

```
{
    "Items": [
        {
            "SongTitle": {
                "S": "Call Me Today"
            },
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[使用 DynamoDB 中的查询](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/Query.html)。  
**示例 2：使用强一致性读取查询表并按降序遍历索引**  
以下示例执行与第一个示例相同的查询，但返回结果的顺序相反，并且使用强一致性读取。  

```
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
```
 的内容`expression-attributes.json`：  

```
{
    ":v1": {"S": "No One You Know"}
}
```
输出：  

```
{
    "Items": [
        {
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        },
        {
            "SongTitle": {
                "S": "Call Me Today"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[使用 DynamoDB 中的查询](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/Query.html)。  
**示例 3：筛选出特定结果**  
以下示例查询 `MusicCollection`，但不包括 `AlbumTitle` 属性中含特定值的结果。请注意，这不会影响 `ScannedCount` 或 `ConsumedCapacity`，因为筛选器在读取项之后应用。  

```
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
```
 的内容`values.json`：  

```
{
    ":v1": {"S": "No One You Know"},
    ":v2": {"S": "Blue Sky Blues"},
    ":v3": {"S": "Greatest Hits"}
}
```
 的内容`names.json`：  

```
{
    "#n1": "Artist",
    "#n2": "AlbumTitle"
}
```
输出：  

```
{
    "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
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[使用 DynamoDB 中的查询](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/Query.html)。  
**示例 4：仅检索项计数**  
以下示例检索与查询匹配的项计数，但不检索任何项本身。  

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

```
{
    ":v1": {"S": "No One You Know"}
}
```
输出：  

```
{
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": null
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[使用 DynamoDB 中的查询](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/Query.html)。  
**示例 5：查询索引**  
以下示例查询本地二级索引 `AlbumTitleIndex`。该查询返回基表中已投影到本地二级索引的所有属性。请注意，查询本地二级索引或全局二级索引时，您还必须使用 `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
```
 的内容`expression-attributes.json`：  

```
{
    ":v1": {"S": "No One You Know"}
}
```
输出：  

```
{
    "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
            }
        }
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[使用 DynamoDB 中的查询](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/Query.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [Query](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/query.html)。

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

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
}
```
定义本示例中使用的 Movie 结构。  

```
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"])
}
```
+  有关 API 详细信息，请参阅《适用于 Go 的 Amazon SDK API Reference》**中的 [Query](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.Query)。

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

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)中查找完整示例，了解如何进行设置和运行。
使用 [DynamoDbClient](https://docs.amazonaws.cn/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;
    }
}
```
使用 `DynamoDbClient` 和二级索引查询表。  

```
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);
        }
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [Query](https://docs.amazonaws.cn/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)。

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

**SDK for JavaScript (v3)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)中查找完整示例，了解如何进行设置和运行。
此示例使用文档客户端来简化在 DynamoDB 中处理项目的过程。有关 API 详细信息，请参阅 [QueryCommand](https://docs.amazonaws.cn/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;
};
```
+  有关更多信息，请参阅《适用于 JavaScript 的 Amazon SDK 开发人员指南》[https://docs.amazonaws.cn/sdk-for-javascript/v3/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying](https://docs.amazonaws.cn/sdk-for-javascript/v3/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying)。
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [Query](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)。

**SDK for JavaScript (v2)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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);
  }
});
```
+  有关更多信息，请参阅《适用于 JavaScript 的 Amazon SDK 开发人员指南》[https://docs.amazonaws.cn/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying](https://docs.amazonaws.cn/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying)。
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [Query](https://docs.amazonaws.cn/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/Query)。

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

**SDK for Kotlin**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Kotlin API Reference》**中的 [Query](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

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

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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);
    }
```
+  有关 API 详细信息，请参阅《适用于 PHP 的 Amazon SDK API Reference》**中的 [Query](https://docs.amazonaws.cn/goto/SdkForPHPV3/dynamodb-2012-08-10/Query)。

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

**适用于 PowerShell V4 的工具**  
**示例 1：调用一个查询，该查询返回具有指定 SongTitle 和 Artist 的 DynamoDB 项目。**  

```
$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
```
**输出：**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V4)》**中的 [Query](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：调用一个查询，该查询返回具有指定 SongTitle 和 Artist 的 DynamoDB 项目。**  

```
$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
```
**输出：**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V5)》**中的 [Query](https://docs.amazonaws.cn/powershell/v5/reference)。

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

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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 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"]
```
查询项目并将其投影以返回数据的子集。  

```
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"]
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [Query](https://docs.amazonaws.cn/goto/boto3/dynamodb-2012-08-10/Query)。

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

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
```
+  有关 API 详细信息，请参阅《适用于 Ruby 的 Amazon SDK API Reference》**中的 [Query](https://docs.amazonaws.cn/goto/SdkForRubyV3/dynamodb-2012-08-10/Query)。

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

**适用于 Rust 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)中查找完整示例，了解如何进行设置和运行。
查找指定年份制作的电影。  

```
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![])
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Rust API Reference》**中的 [Query](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.query)。

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

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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.
```
+  有关 API 详细信息，请参阅《Amazon SDK for SAP ABAP API Reference》**中的 [Query](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

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

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
        }
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Swift API 参考》**中的 [Query](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/query(input:))。

------

有关更多 DynamoDB 示例，请参阅[适用于使用 Amazon SDK 的 DynamoDB 的代码示例](service_code_examples.md)。

要为表创建全局二级索引，请继续 [第 6 步：（可选）删除 DynamoDB 表以清理资源](getting-started-step-6.md)。

# 第 6 步：（可选）删除 DynamoDB 表以清理资源
<a name="getting-started-step-6"></a>

如果不再需要为本教程创建的 Amazon DynamoDB 表，可以删除。此步骤有助于确保不会为未使用的资源付费。可以使用 DynamoDB 控制台或 Amazon CLI 删除 [第 1 步：在 DynamoDB 中创建表](getting-started-step-1.md) 中创建的 `Music` 表。

有关 DynamoDB 中表操作的更多信息，请参阅 [使用 DynamoDB 中的表和数据](WorkingWithTables.md)。

## Amazon Web Services 管理控制台
<a name="getting-started-step-8-Console"></a>

使用控制台删除 `Music` 表：

1. 打开 DynamoDB 控制台：[https://console.aws.amazon.com/dynamodb/](https://console.amazonaws.cn/dynamodb/)。

1. 在左侧导航窗格中，选择 **表**。

1. 在表列表中，选中 **Music** 表旁边的复选框。

1. 选择**删除**。

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

下面的 Amazon CLI 示例使用 `delete-table` 删除 `Music` 表。

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

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

以下代码示例演示如何使用 Amazon SDK 删除 DynamoDB 表。

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

**适用于 .NET 的 Amazon SDK (v4)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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;
        }
    }
```
+  有关 API 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [DeleteTable](https://docs.amazonaws.cn/goto/DotNetSDKV4/dynamodb-2012-08-10/DeleteTable)。

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

**Amazon CLI 及 Bash 脚本**  
 查看 GitHub，了解更多信息。查找完整示例，了解如何在 [Amazon 代码示例存储库](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
}
```
本示例中使用的实用程序函数。  

```
###############################################################################
# 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
}
```
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [DeleteTable](https://docs.amazonaws.cn/goto/aws-cli/dynamodb-2012-08-10/DeleteTable)。

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

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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();
}
```
+  有关 API 详细信息，请参阅《适用于 C\$1\$1 的 Amazon SDK API Reference》**中的 [DeleteTable](https://docs.amazonaws.cn/goto/SdkForCpp/dynamodb-2012-08-10/DeleteTable)。

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

**Amazon CLI**  
**删除表**  
以下 `delete-table` 示例将删除 `MusicCollection` 表。  

```
aws dynamodb delete-table \
    --table-name MusicCollection
```
输出：  

```
{
    "TableDescription": {
        "TableStatus": "DELETING",
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableName": "MusicCollection",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "WriteCapacityUnits": 5,
            "ReadCapacityUnits": 5
        }
    }
}
```
有关更多信息，请参阅《Amazon DynamoDB 开发人员指南》**中的[删除表](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeleteTable)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [DeleteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/delete-table.html)。

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

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
}
```
+  有关 API 详细信息，请参阅《适用于 Go 的 Amazon SDK API Reference》**中的 [DeleteTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.DeleteTable)。

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

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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!");
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [DeleteTable](https://docs.amazonaws.cn/goto/SdkForJavaV2/dynamodb-2012-08-10/DeleteTable)。

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

**SDK for JavaScript (v3)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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;
};
```
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [DeleteTable](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DeleteTableCommand)。

**SDK for JavaScript (v2)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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);
  }
});
```
+  有关更多信息，请参阅《适用于 JavaScript 的 Amazon SDK 开发人员指南》[https://docs.amazonaws.cn/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-deleting-a-table](https://docs.amazonaws.cn/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-deleting-a-table)。
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [DeleteTable](https://docs.amazonaws.cn/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/DeleteTable)。

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

**SDK for Kotlin**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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")
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Kotlin API Reference》**中的 [DeleteTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

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

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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,
            ]);
        });
    }
```
+  有关 API 详细信息，请参阅《适用于 PHP 的 Amazon SDK API Reference》**中的 [DeleteTable](https://docs.amazonaws.cn/goto/SdkForPHPV3/dynamodb-2012-08-10/DeleteTable)。

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

**适用于 PowerShell V4 的工具**  
**示例 1：删除指定的表。在操作继续之前，系统会提示您进行确认。**  

```
Remove-DDBTable -TableName "myTable"
```
**示例 2：删除指定的表。在操作继续之前，系统不会提示您进行确认。**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V4)》**中的 [DeleteTable](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：删除指定的表。在操作继续之前，系统会提示您进行确认。**  

```
Remove-DDBTable -TableName "myTable"
```
**示例 2：删除指定的表。在操作继续之前，系统不会提示您进行确认。**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  有关 API 详细信息，请参阅《Amazon Tools for PowerShell Cmdlet Reference (V5)》**中的 [DeleteTable](https://docs.amazonaws.cn/powershell/v5/reference)。

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

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [DeleteTable](https://docs.amazonaws.cn/goto/boto3/dynamodb-2012-08-10/DeleteTable)。

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

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
```
+  有关 API 详细信息，请参阅《适用于 Ruby 的 Amazon SDK API Reference》**中的 [DeleteTable](https://docs.amazonaws.cn/goto/SdkForRubyV3/dynamodb-2012-08-10/DeleteTable)。

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

**适用于 Rust 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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())),
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Rust API Reference》**中的 [DeleteTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.delete_table)。

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

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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.
```
+  有关 API 详细信息，请参阅《Amazon SDK for SAP ABAP API Reference》**中的 [DeleteTable](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

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

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](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
        }
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Swift API Reference》**中的 [DeleteTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/deletetable(input:))。

------

有关更多 DynamoDB 示例，请参阅[适用于使用 Amazon SDK 的 DynamoDB 的代码示例](service_code_examples.md)。

# 继续了解 DynamoDB
<a name="getting-started-NextSteps"></a>

有关 Amazon DynamoDB 的更多信息，请参见以下主题：
+ [使用 DynamoDB 中的表和数据](WorkingWithTables.md)
+ [使用 DynamoDB 中的项目和属性](WorkingWithItems.md)
+ [在 DynamoDB 中查询表](Query.md)
+ [在 DynamoDB 中使用全局二级索引](GSI.md)
+ [使用事务代码示例](transactions.md)
+ [利用 DynamoDB Accelerator（DAX）实现内存中加速](DAX.md)
+ [使用 DynamoDB 和 Amazon SDK 编程](Programming.md)

# 使用 Console-to-Code 为 Amazon DynamoDB 生成基础设施代码
<a name="console-to-code"></a>

Amazon Q 开发者版的 Console-to-Code 功能可将手动创建表的步骤转换为可重用的自动化代码，从而简化 Amazon DynamoDB 的基础设施管理。此功能可帮助开发人员在其环境中高效地扩展数据库资源配置。要了解更多信息，请参阅[使用 Amazon Q 开发者版 Console-to-Code 实现 Amazon Web Services 服务自动化](https://docs.amazonaws.cn/amazonq/latest/qdeveloper-ug/console-to-code.html)。

Console-to-Code 采集详细的 DynamoDB 表配置，包括分区键、排序键、预调配吞吐量设置和二级索引，并将它们转换为精确的基础设施即代码模板。该工具使用生成式人工智能，可确保生成的代码保持在控制台工作流中建立的参数兼容性。

开发人员可以生成多种格式的 DynamoDB 基础设施代码，例如：
+ Amazon 云开发工具包（Amazon CDK），使用 TypeScript、Python 和 Java 格式
+ Amazon CloudFormation，使用 YAML 或 JSON 格式

这种方法使团队能够：
+ 标准化数据库资源管理
+ 实施版本控制的基础设施
+ 减少手动配置错误

适用于 Amazon DynamoDB 的 Console-to-Code 在所有商业 Amazon 区域中可用，为将手动配置过程转换为自动化、可复制的基础设施代码提供了强大的解决方案。

## 工作原理
<a name="how-it-works"></a>

在 DynamoDB 中使用 Console-to-Code 时，该过程通常涉及：

1. **在控制台中创建原型**：使用 DynamoDB 控制台创建和配置资源，例如表。有关更多信息，请参阅[连接到 Amazon DynamoDB](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/GettingStartedDynamoDB.html)。

1. **记录操作**：Console-to-Code 会在您执行操作时记录这些操作。

1. **代码生成**：该功能使用 Amazon Q 开发者版的生成式人工智能功能，使用您的首选格式，将控制台中的操作转换为可重复使用的代码。

1. **代码自定义**：然后，您可以复制或下载此代码，并针对您的生产工作负载对其进行进一步自定义。

## 在 DynamoDB 中使用 Console-to-Code 的好处
<a name="benefits"></a>

**简化自动化过程**  
只需一次单击，即可将 DynamoDB 表的手动创建和配置过程转换为可重复使用的代码。

**最佳实践**  
生成的代码遵循 Amazon 指导性最佳实践，实现可靠部署。

**控制台和代码之间的桥梁**  
您不必在使用 Amazon Web Services 管理控制台或基础设施即代码（IaC）之间做出选择。而是可以同时使用这两种方法。

**加速开发过程**  
使用自动化代码快速上手，这些代码可以进一步定制来供生产使用。

## 使用案例示例
<a name="example-use-cases"></a>
+ 使用特定属性、键和容量设置创建 DynamoDB 表
+ 设置全局二级索引和本地二级索引
+ 为 DynamoDB 表配置自动扩缩策略
+ 建立备份和还原配置
+ 创建和管理 DynamoDB Streams

## 开始使用
<a name="getting-started"></a>

要开始在 DynamoDB 中使用 Console-to-Code，请执行以下操作：

1. 登录 Amazon Web Services 管理控制台，打开 DynamoDB 控制台：[https://console.aws.amazon.com/dynamodbv2/](https://console.amazonaws.cn/dynamodbv2/)。

1. 通过控制台界面开始创建或修改 DynamoDB 资源。

1. 使用 Console-to-Code 功能，按照您的首选格式为操作生成代码。

1. 复制或下载生成的代码，并根据您的具体需求对其进行自定义。

有关如何使用 Console-to-Code 的更多信息和详细说明，请参阅《Amazon Q 开发者版用户指南》**中的[使用 Amazon Q 开发者版 Console-to-Code 实现 Amazon Web Services 服务自动化](https://docs.amazonaws.cn/amazonq/latest/qdeveloper-ug/console-to-code.html)。