

# DynamoDB の使用開始
<a name="GettingStartedDynamoDB"></a>

DynamoDB テーブルの接続、作成、管理の方法について、以下のセクションで説明します。

開始する前に、Amazon DynamoDB の基本概念を理解する必要があります。[Amazon DynamoDB とは](Introduction.md) の簡単な概要と、[Amazon DynamoDB のコアコンポーネント](HowItWorks.CoreComponents.md) のより詳細な説明を確認できます。次に、「[前提条件](#GettingStarted.SettingUp.DynamoWebService)」に進みます。

**注記**  
AWS にサインアップすると、[AWS 無料利用枠](https://aws.amazon.com/free/)を利用して、DynamoDB の使用を開始できます。Amazon DynamoDB の無料利用枠の特典をまだ超えていない場合、このセクションの例を完了しても料金は発生しません。それ以外の場合は、テーブルを作成した時点からテーブルを削除するまで、標準の DynamoDB 使用料が発生します。  
無料利用枠アカウントにサインアップしない場合は、[DynamoDB local (ダウンロード可能バージョン)](DynamoDBLocal.md) をコンピュータでセットアップできます。ダウンロード可能なバージョンでは、AWS アカウントにサインアップしたり、DynamoDB ウェブサービスにアクセスしたりせずに、ローカルでアプリケーションを開発およびテストできます。

**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://aws.amazon.com/dynamodb/)**  
DynamoDB の一般的な製品概要、一般的なユースケース、主なサービス、料金について説明します。  |  

**Example**  
**[DynamoDB リソース](https://aws.amazon.com/dynamodb/resources/)**  
サービス、データモデリングの概念、主要な特徴と機能を紹介する動画、チュートリアル、規範ガイダンスがあります。  | 
|  

**Example**  
**[開始方法](GettingStartedDynamoDB.md)**  
DynamoDB のセットアップ、サンプルテーブルの作成、データのアップロードに関する情報が記載されています。  |  

**Example**  
**[DynamoDB 基本コース](https://explore.skillbuilder.aws/learn/course/external/view/elearning/16104/amazon-dynamodb-basics)**  
テーブル設計、データ型、基本オペレーションなど、DynamoDB の基本を学習する無料のデジタルコース。  | 
|  

**Example**  
**[DynamoDB ナゲット](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/)**  
AWS は、DynamoDB の概念、機能、ベストプラクティスを対象とした無料のデジタルトレーニングコースを提供します。  |  

**Example**  
**[DynamoDB 用の NoSQL Workbench](https://youtu.be/p5va6ZX9_o0)**  
データモデリング、データの視覚化、クエリ開発機能を提供する統合ビジュアルツール。  | 
|  

**Example**  
**[DynamoDB 設計パターン](best-practices.md)**  
実用的なコードサンプルを使用した、さまざまなユースケースのベストプラクティスとデータモデリングの例。  |  

**Example**  
**[実践的なチュートリアル](https://aws.amazon.com/tutorials/create-nosql-table/)**  
一般的な DynamoDB タスクについて説明するAWS マネジメントコンソールにおけるステップバイステップのチュートリアル。  | 
|  

**Example**  
**[DynamoDB への移行](migration-guide.md)**  
データベースを DynamoDB に移行するためのプロセス、ツール、戦略の概要。  |  

**Example**  
**[DynamoDB 用の AWS Well-Architected レンズ](bp-wal.md)**  
DynamoDB を使用して信頼性、安全性、効率性、費用対効果の高いアプリケーションを設計および運用するためのアーキテクチャのベストプラクティスを提供します。  | 

## Amazon DynamoDB の初回ユーザー向けの追加のベストプラクティス
<a name="additional-reading"></a>

前述のセクションを完了したら、これらのセクションを参照してください。
+  **[DynamoDB のスループットキャパシティ](capacity-mode.md)** 

  DynamoDB テーブルで使用できる 2 つのスループットモードの概要と、アプリケーションに適したキャパシティモードを選択する際の考慮事項について説明します。オンデマンドモードは、ほとんどの DynamoDB ワークロードで推奨されるデフォルトのスループットオプションです。
+  **[DynamoDB を使用した設計とアーキテクチャの設計に関するベストプラクティス](best-practices.md)** 

  問題を特定して対処し、DynamoDB を使用する際のパフォーマンスを最大化し、コストを最小限に抑えます。

## AWS CLI リソース
<a name="new-users-aws-cli-resources"></a>

AWS コマンドラインインターフェイス (AWS CLI) を使用する場合は、これらのドキュメントが使用開始に役立ちます。
+  **[AWS CLI ドキュメント](https://docs.aws.amazon.com/cli/)** 

   このセクションには、AWS CLI のダウンロード、システムでの AWS CLI の実行、AWS 認証情報の指定に関する情報が記載されています。
+  **[DynamoDB 向けの AWS CLI ドキュメント](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/index.html)** 

   この別個のドキュメントでは、DynamoDB 用のすべての AWS CLI コマンド (構文と例を含む) について説明します。

## プログラミングリソース
<a name="new-user-programming-resources"></a>

さまざまな一般的プログラミング言語を使用して、DynamoDB API を使用するアプリケーションプログラムを記述できます。次にいくつかのリソースを示します。
+  **[Amazon Web Services のツール](https://aws.amazon.com/developer/tools/)** 

   AWS には、DynamoDB をサポートする多数の Software Development Kit (SDK) が用意されています。DynamoDB のコードは、Java、.NET、PHP、Ruby、その他の言語で作成できます。これらの SDK は、DynamoDB へのリクエストのフォーマット、レスポンスの解析、再試行ロジックとエラー処理の提供により、アプリケーション開発を大幅に簡素化します。
+  ** [DynamoDB API リファレンス](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/Welcome.html)**

   AWS SDK を使用しない場合は、DynamoDB API を使用して DynamoDB を直接操作できます。このドキュメントでは、DynamoDB のすべての API オペレーション (構文と例を含む) について説明します。リクエストを作成および認証してレスポンスを処理する際のトラブルシューティングのヒントと情報をこのセクションで確認できます。

# DynamoDB にアクセスする
<a name="AccessingDynamoDB"></a>

 Amazon DynamoDB には、AWS マネジメントコンソール、AWS Command Line Interface (AWS CLI)、または DynamoDB API を使用してアクセスできます。

**Topics**
+ [コンソールを使用する](#ConsoleDynamoDB)
+ [の使用AWS CLI](#Tools.CLI)
+ [API の使用](#Using.API)
+ [DynamoDB 用の NoSQL Workbench の使用](#Using.Workbench)
+ [IP アドレスの範囲](#Using.IPRanges)
+ [インターネットプロトコルバージョン 6 (IPv6) のデュアルスタックエンドポイント](#dual-stackipv4-6)

## コンソールを使用する
<a name="ConsoleDynamoDB"></a>

Amazon DynamoDB の AWS マネジメントコンソール、[https://console.aws.amazon.com/dynamodb/home](https://console.aws.amazon.com/dynamodb/home) からアクセスできます。

DynamoDB コンソールで実行できるアクションの一部を以下に示します。
+ **テーブルの管理**: テーブルを作成、更新、削除する。キャパシティ計算ツールは、キャパシティ要件の見積もりに役立ちます。
+ **データの操作**: テーブル内の項目を表示、追加、更新、削除する。Time to Live (TTL) 設定を管理する。
+ **モニタリングと分析**: ダッシュボードの表示、アラームのモニタリングと設定、DynamoDB テーブルのメトリクスとアラートの分析を行う。
+ **最適化と拡張**: セカンダリインデックス、ストリーム、トリガー、リザーブドキャパシティ、その他の高度な機能を管理し、DynamoDB の使用を強化する。

DynamoDB コンソールは、DynamoDB リソースを管理するための包括的なインターフェイスを提供します。詳細については、コンソールにアクセスして操作することをお勧めします。

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

 AWS Command Line Interface (AWS CLI) を使用すると、複数の AWS のサービスをコマンドラインから制御したり、スクリプトで自動化したりできます。テーブルの作成など、その場限りのオペレーションに AWS CLI を使用できます。また、ユーティリティスクリプト内に Amazon DynamoDB オペレーションを埋め込むときにも使用できます。

 DynamoDB で AWS CLI を使用するには、事前にアクセスキー ID とシークレットアクセスキーを取得する必要があります。詳細については、「[プログラムによるアクセス権を付与する](SettingUp.DynamoWebService.md#SettingUp.DynamoWebService.GetCredentials)」を参照してください。

AWS CLI で DynamoDB 向けに使用できるすべてのコマンドの完全な一覧については、「[AWS CLI コマンドリファレンス](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/index.html)」を参照してください。

**Topics**

### AWS CLI のダウンロードと設定
<a name="Tools.CLI.DownloadingAndRunning"></a>

AWS CLI は、[http://aws.amazon.com/cli](https://aws.amazon.com/cli) で入手できます。Windows、macOS、または Linux 上で実行できます。AWS CLI をダウンロードしたら、以下の手順に従って、インストールと設定を行います。

1. [AWS Command Line Interface ユーザーガイド](https://docs.aws.amazon.com/cli/latest/userguide/)に移動します。

1. [AWS CLI のインストール](https://docs.aws.amazon.com/cli/latest/userguide/installing.html)、[AWS CLI の設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)の手順に従います。

### DynamoDB での AWS CLI の使用
<a name="Tools.CLI.UsingWithDDB"></a>

コマンドラインの形式は、DynamoDB オペレーション名と、それに続くそのオペレーションのパラメータで構成されます。AWS 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 を作成するのは難しい場合があります。ただし、AWS CLI で JSON ファイルを読み込むことができます。例えば、*key-conditions.json* という名前のファイルに格納されている次の JSON コードスニペットがあるとします。

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

次のように、`Query` を使用して、AWS CLI リクエストを発行できます。この例では、*key-conditions.json* ファイルの内容は、`--key-conditions` パラメータに使用されます。

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

### DynamoDB Local での AWS CLI の使用
<a name="Tools.CLI.UsingWithDDBLocal"></a>

AWS CLI を使用して、コンピュータで実行されている DynamoDB Local (ダウンロード可能なバージョン) を操作することもできます。これを有効にするには、各コマンドに次のパラメータを追加します。

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

次の例では、AWS CLI を使用して、ローカルデータベースのテーブルを一覧表示します。

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

DynamoDB がデフォルト (8000) 以外のポート番号を使用している場合は、それに応じて `--endpoint-url` 値を変更する必要があります。

**注記**  
AWS CLI では、DynamoDB Local (ダウンロード可能なバージョン) をデフォルトのエンドポイントとして使用することはできません。そのため、各コマンドで `--endpoint-url` を指定する必要があります。

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

 AWS マネジメントコンソール と AWS Command Line Interface を使用して、Amazon DynamoDB とインタラクティブに作業できます。ただし、DynamoDB を最大限に活用するためには、AWS SDK を使用してアプリケーションコードを記述できます。

AWS SDK は、DynamoDB の広範なサポート ([Java](https://aws.amazon.com/sdk-for-java)、[ブラウザの JavaScript](https://aws.amazon.com/sdk-for-browser)、[.NET](https://aws.amazon.com/sdk-for-net)、[Node.js](https://aws.amazon.com/sdk-for-node-js)、[PHP](https://aws.amazon.com/sdk-for-php)、[Python](https://aws.amazon.com/sdk-for-python)、[Ruby](https://aws.amazon.com/sdk-for-ruby)、[C\$1\$1](https://aws.amazon.com/sdk-for-cpp)、[Go](https://aws.amazon.com/sdk-for-go)、[Android](https://aws.amazon.com/mobile/sdk/)、[iOS](https://aws.amazon.com/mobile/sdk/)) を提供します。

DynamoDB を使用して AWS を使用するには、AWS アクセスキー ID とシークレットアクセスキーを取得する必要があります。詳細については、「[DynamoDB (ウェブサービス) の設定](SettingUp.DynamoWebService.md)」を参照してください。

 AWS SDK を使用した DynamoDB アプリケーションのプログラミングに関する概要については、「[DynamoDB と AWS SDK を使用したプログラミング](Programming.md)」を参照してください。

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

また、DynamoDB には、[DynamoDB 用の NoSQL Workbench](workbench.md) をダウンロードして使用することによってアクセスできます。

Amazon DynamoDB 用の NoSQL Workbench は、最新のデータベース開発および運用向けのクロスプラットフォームのクライアント側 GUI アプリケーションです。Windows、macOS、Linux で使用できます。NoSQL Workbench は、DynamoDB テーブルの設計、作成、クエリ、管理に役立つデータモデリング、データ可視化、クエリ開発といった特徴を提供する視覚的開発ツールです。NoSQL Workbench に、インストールプロセスのオプションとして DynamoDB local が含まれるようになったため、DynamoDB local でデータを簡単にモデル化できます。DynamoDB local とその要件の詳細については、「[DynamoDB local (ダウンロード可能バージョン) のセットアップ](DynamoDBLocal.md)」を参照してください。

**注記**  
NoSQL Workbench for DynamoDB は、現在、2 要素認証 (2FA) で構成されている AWS ログインをサポートしていません。

**データモデリング**  
DynamoDB 用の NoSQL Workbench を使用すると、アプリケーションのデータアクセスパターンを満たす既存のデータモデルから新しいデータモデルを構築したり、既存のデータモデルに基づいてモデルを設計したりできます。プロセスの最後に、設計されたデータモデルをインポートおよびエクスポートすることもできます。詳細については、「[NoSQL Workbench を使用したデータモデルの構築](workbench.Modeler.md)」を参照してください。

**オペレーション構築**  
NoSQL Workbench は、クエリを開発およびテストするための豊富なグラフィカルユーザーインターフェイスを提供します。*オペレーションビルダー*を使用して、データセットを表示、探索、およびクエリできます。構造化オペレーションビルダーを使用して、データプレーンオペレーションを構築および実行することもできます。プロジェクションと条件式をサポートし、複数の言語でサンプルコードを生成できます。詳細については、「[NoSQL Workbench を使用したデータセットの探索とオペレーションの構築](workbench.querybuilder.md)」を参照してください。

## IP アドレスの範囲
<a name="Using.IPRanges"></a>

Amazon Web Services (AWS) は、その現在の IP アドレス範囲を JSON 形式で公開します。現在の範囲を表示するには、「[ip-ranges.json](https://ip-ranges.amazonaws.com/ip-ranges.json)」ファイルをダウンロードします。詳細については、AWS 全般のリファレンス の [AWS IP アドレスの範囲](https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html)をご参照ください。

[DynamoDB テーブルおよびインデックスへのアクセス](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Operations_Amazon_DynamoDB.html)に使用できる IP アドレス範囲を見つけるには、ip-ranges.json で文字列 `"service": "DYNAMODB"` を検索します。

**注記**  
この IP アドレス範囲は、DynamoDB Streams および DynamoDB Accelerator (DAX) には適用されません。

## インターネットプロトコルバージョン 6 (IPv6) のデュアルスタックエンドポイント
<a name="dual-stackipv4-6"></a>

DynamoDB は、IPv4 と IPv6 の両方と互換性のあるデュアルスタックエンドポイントを提供します。エンドポイントの命名規則は次のとおりです。
+ `dynamodb.<region>.api.aws`
+ `<account-id>.ddb.<region>.api.aws`
+ `streams-dynamodb.<region>.api.aws`
+ `dax.<region>.api.aws`
+ `dynamodb-fips.<region>.api.aws`

DynamoDB エンドポイントとリージョンの可用性の完全なリストについては、「*AWS 全般のリファレンスガイド*」の「[Amazon DynamoDB エンドポイントとクォータ](https://docs.aws.amazon.com/general/latest/gr/ddb.html)」のトピックを参照してください。

デュアルスタックエンドポイントを使用するように AWS CLI を設定する方法の詳細については、「*AWS コマンドラインインターフェイスガイド*」の「[すべての AWS のサービスでデュアルスタックのエンドポイントを使用するように設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-endpoints.html#endpoints-dual-stack)」のセクションを参照してください。

デュアルスタックエンドポイントを使用するように SDK クライアントを設定する方法の詳細については、「*AWS SDK とツールガイド*」の「[デュアルスタックと FIPS エンドポイント](https://docs.aws.amazon.com/sdkref/latest/guide/feature-endpoints.html)」のトピックを参照してください。

IPv6 で DynamoDB を使用する前に、IPv6 アドレスの範囲を含めるために IP アドレスフィルタリングに使用する IAM ユーザーロールまたはリソースベースのポリシーを更新する必要があります。IPv6 アドレスを考慮しない IP アドレスフィルタリングポリシーは、アクセスの問題を引き起こす可能性があります。詳細については、「*AWS Identity and Access Management ガイド*」の「[IP アドレス条件演算子](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_IPAddress)」のセクションを参照してください。

## 前提条件
<a name="GettingStarted.SettingUp.DynamoWebService"></a>

Amazon DynamoDB チュートリアルを開始する前に、[DynamoDB にアクセスする](AccessingDynamoDB.md) で DynamoDB にアクセスする方法について説明します。次に、ウェブサービスを使用するか、[DynamoDB のセットアップ](SettingUp.md) でローカルにダウンロードしたバージョンを使用して DynamoDB を設定します。その後、「[ステップ 1: DynamoDB にテーブルを作成する](getting-started-step-1.md)」に進みます。

**注記**  
AWS マネジメントコンソール のみを使用して DynamoDB とやり取りする場合、AWS アクセスキーは必要ありません。「[AWS にサインアップする](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html#SettingUp.DynamoWebService.SignUpForAWS)」のステップを完了し、「[ステップ 1: DynamoDB にテーブルを作成する](getting-started-step-1.md)」に進んでください。
無料利用枠アカウントにサインアップしない場合は、[DynamoDB local (ダウンロード可能バージョン)](https://docs.aws.amazon.com/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 ウェブサービスに加えて、AWS はコンピュータで実行できる DynamoDB のダウンロード可能バージョンを提供します。ダウンロード可能なバージョンは、コードの開発とテストに役立ちます。これを使用することで、DynamoDB ウェブサービスにアクセスせずに、ローカルでアプリケーションを書き込んでテストすることができます。

 このセクションのトピックでは、DynamoDB (ダウンロード可能バージョン) と DynamoDB ウェブサービスをセットアップする方法について説明します。

**Topics**
+ [DynamoDB (ウェブサービス) の設定](SettingUp.DynamoWebService.md)
+ [DynamoDB local (ダウンロード可能バージョン) のセットアップ](DynamoDBLocal.md)

# DynamoDB (ウェブサービス) の設定
<a name="SettingUp.DynamoWebService"></a>

 Amazon DynamoDB ウェブサービスを使用するには: 

1.  [ にサインアップする。AWS](#SettingUp.DynamoWebService.SignUpForAWS)

1.  [AWS アクセスキーの取得](#SettingUp.DynamoWebService.GetCredentials) (プログラムで DynamoDB にアクセスするために使用)。
**注記**  
 DynamoDB のみを使用して AWS マネジメントコンソール とやり取りする場合、AWS アクセスキーは必要ないため、「[コンソールを使用する](AccessingDynamoDB.md#ConsoleDynamoDB)」に進むことができます。

1.  [認証情報の設定](#SettingUp.DynamoWebService.ConfigureCredentials) (プログラムで DynamoDB にアクセスするために使用)。

## へのサインアップAWS
<a name="SettingUp.DynamoWebService.SignUpForAWS"></a>

 DynamoDB サービスを使用するには、AWS アカウントが必要です。アカウントをまだお持ちでない場合は、サインアップ時に画面の指示に従って作成してください。サインアップした AWS サービスの料金は、そのサービスを使用しない限り発生することはありません。

**AWS にサインアップするには**

1. [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup) を開きます。

1. オンラインの手順に従います。

   サインアップ手順の一環として、電話またはテキストメッセージを受け取り、電話キーパッドで検証コードを入力します。

   AWS アカウントにサインアップすると、*AWS アカウントのルートユーザー*が作成されます。ルートユーザーには、アカウントのすべての AWS のサービス とリソースへのアクセス権があります。セキュリティベストプラクティスとして、ユーザーに管理アクセス権を割り当て、[ルートユーザーアクセスが必要なタスク](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks)の実行にはルートユーザーのみを使用するようにしてください。

## プログラムによるアクセス権を付与する
<a name="SettingUp.DynamoWebService.GetCredentials"></a>

 プログラムまたは AWS Command Line Interface (AWS CLI) を介して DynamoDB にアクセスするには、プログラムによるアクセス権が必要です。DynamoDB コンソールのみを使用する場合、プログラムによるアクセス権は不要です。

AWS マネジメントコンソール の外部で AWS を操作するには、プログラマチックアクセス権が必要です。プログラムによるアクセス権を付与する方法は、AWS にアクセスしているユーザーのタイプによって異なります。

ユーザーにプログラムによるアクセス権を付与するには、以下のいずれかのオプションを選択します。


****  

| プログラムによるアクセス権を必要とするユーザー | 目的 | 方法 | 
| --- | --- | --- | 
| IAM | (推奨) 一時的な認証情報としてコンソール認証情報を使用して、AWS CLI、AWS SDK、または AWS API へのプログラマチックリクエストに署名します。 |  使用するインターフェイスの指示に従ってください。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 
|  ワークフォースアイデンティティ (IAM アイデンティティセンターで管理されているユーザー)  | 一時的な認証情報を使用して、AWS CLI、AWS SDK、または AWS API へのプログラムによるリクエストに署名します。 |  使用するインターフェイスの指示に従ってください。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 
| IAM | 一時的な認証情報を使用して、AWS CLI、AWS SDK、または AWS API へのプログラムによるリクエストに署名します。 | IAM ユーザーガイドの「[AWS リソースでの一時的な認証情報の使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html)」の指示に従ってください。 | 
| IAM | (非推奨)長期的な認証情報を使用して、AWS CLI、AWS SDK、または AWS API へのプログラムによるリクエストに署名します。 |  使用するインターフェイスの指示に従ってください。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/SettingUp.DynamoWebService.html)  | 

## 認証情報の設定
<a name="SettingUp.DynamoWebService.ConfigureCredentials"></a>

 プログラムまたは AWS CLI を介して DynamoDB にアクセスする前に、アプリケーションの認可が有効になるように認証情報を設定する必要があります。

 この方法には、いくつかあります。たとえば、認証情報ファイルを手動で作成して、お客様のアクセスキー ID とシークレットアクセスキーを格納します。また、このファイルは、AWS CLI コマンド `aws configure` を使用して自動的に作成することもできます。または、環境変数を使用できます。認証情報の設定に関する詳細については、プログラム固有の AWS SDK デベロッパーガイドを参照してください。

 AWS CLI をインストールして設定する方法については、「[の使用AWS CLI](AccessingDynamoDB.md#Tools.CLI)」を参照してください。

## DynamoDB の他のサービスとの統合
<a name="w2aab9c17b9c13"></a>

DynamoDB AWS は他の多くのサービスと統合できます。詳細については次を参照してください: 
+ [DynamoDB を他の AWS サービスで使用する](OtherServices.md)
+ [CloudFormationDynamoDB の](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html)
+ [DynamoDB での AWS Backup の使用](backuprestore_HowItWorksAWS.md)
+ [AWS Identity and Access Management (IAM) と DynamoDB](identity-and-access-mgmt.md)
+ [Amazon DynamoDB で AWS Lambda を使用する](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html)

# DynamoDB local (ダウンロード可能バージョン) のセットアップ
<a name="DynamoDBLocal"></a>

 ダウンロード可能なバージョンの Amazon DynamoDB では、DynamoDB ウェブサービスにアクセスせずに、アプリケーションを開発してテストすることができます。代わりに、データベースはコンピュータ上で自己完結型となります。アプリケーションを本番稼働環境にデプロイする準備ができたら、コード内のローカルエンドポイントを削除します。その後、これは DynamoDB ウェブサービスを指します。

 このローカルバージョンを使用することで、スループットやデータストレージ、データ転送料金を節約しやすくなります。また、アプリケーションを開発している間インターネットに接続しておく必要はありません。

 DynamoDB local は、[ダウンロード](DynamoDBLocal.DownloadingAndRunning.md#DynamoDBLocal.DownloadingAndRunning.title) (JRE が必要)、[Apache Maven 依存関係](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html#apache-maven)、または [Docker イメージ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html#docker)として使用できます。

 Amazon DynamoDB ウェブサービスを代わりに使用する場合は、「[DynamoDB (ウェブサービス) の設定](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 (廃止) の 3 つのバージョンで利用できます。
DynamoDB v3.x は、ローカルでのテストと開発での使用に推奨されます。
DynamoDB local V2.x から V3.x に移行するには、インポートステートメントを `com.amazonaws.services.dynamodbv2` から `software.amazon.dynamodb` に更新し、Maven ユーザーは Maven 依存関係を更新する必要があります。
SDK for Java v1.x を使用するアプリケーションを SDK for Java 2.x に移行する場合は、[AWS SDK for Java 2.x](https://docs.aws.amazon.com/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.aws.amazon.com/ja_jp/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. プログラムまたは AWS Command Line Interface (AWS CLI) を介して DynamoDB にアクセスする前に、アプリケーションで認可が有効になるように認証情報を設定する必要があります。以下の例に示されているように、ダウンロード可能な DynamoDB には、認証情報が必要です。

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

    `aws configure` の AWS CLI コマンドを使用して、認証情報を設定できます。詳細については、「」を参照してください[の使用AWS CLI](AccessingDynamoDB.md#Tools.CLI) 

1.  アプリケーションの書き込みを開始します。AWS CLI を使用してローカルで実行中の DynamoDB にアクセスするには、`--endpoint-url ` パラメータを使用します。たとえば、次のコマンドを使用して、DynamoDB テーブルを一覧表示します。

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

## DynamoDB Local を Docker イメージとして実行する
<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
```

 AWS Serverless Application Model (AWS SAM) で構築した REST アプリケーションの一部として DynamoDB local を使用する例については、「[注文を管理するための SAM DynamoDB アプリケーション](https://github.com/aws-samples/aws-sam-java-rest)」を参照してください。このサンプルアプリケーションは、DynamoDB local をテストで使用する方法を示しています。

 DynamoDB local のコンテナも使用するマルチコンテナアプリケーションを実行する場合は、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` コンテナを作成します。スクリプトは、AWS CLI を使用して `app-node` コンテナに接続し、アカウントとテーブルの制限を記述するコマンドを `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 スクリプトでは、AWS アクセスキーと AWS シークレットキーを指定する必要がありますが、DynamoDB local にアクセスするための有効な AWS キーである必要はありません。

1.  次のコマンドラインのコマンドを実行します。

   ```
   docker-compose up
   ```

## DynamoDB Local を Apache Maven 依存関係として実行する
<a name="DynamoDBLocal.DownloadingAndRunning.Maven.v2"></a>

**注記**  
SDK for Java v1.x を使用するアプリケーションを SDK for Java 2.x に移行する場合は、[AWS SDK for Java 2.x](https://docs.aws.amazon.com/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 中央リポジトリ](https://mvnrepository.com/artifact/com.amazonaws/DynamoDBLocal?repo=dynamodb-local-release)の URL を使用することもできます。

## DynamoDB local を AWS CloudShell で実行する
<a name="DynamoDBLocal.DynamoDB.Local.CloudShell"></a>

AWS CloudShell はブラウザベースの事前に認証されたシェルで、 から直接起動できます。AWS マネジメントコンソールAWS マネジメントコンソールから AWS CloudShell に移動するには、いくつかの方法があります。詳細については、「[AWS CloudShell の開始方法](https://docs.aws.amazon.com/cloudshell/latest/userguide/getting-started.html)」を参照してください。

AWS マネジメントコンソールのどこからでも AWS CloudShell で DynamoDB local を実行するには、次の手順に従います。

**AWS CloudShellから AWS マネジメントコンソール で DynamoDB local を実行するには**

1. コンソールインターフェースから AWS CloudShell を起動し、使用可能な AWS リージョンを選択して、希望するシェル (Bash、PowerShell、Z シェルなど) に切り替えます。

1. AWS リージョン を選択するには、**[リージョンを選択]** メニューに移動し、[[サポートされている AWS リージョン]](https://docs.aws.amazon.com/cloudshell/latest/userguide/supported-aws-regions.html) を選択します (使用可能なリージョンがハイライト表示されます)。

1. AWS マネジメントコンソールから、次のオプションのいずれかを選択して AWS CloudShellを起動します。

   1. ナビゲーションバーで、**AWS CloudShell** アイコンを選択します。

   1. **[検索]** ボックスに「CloudShell」と入力し、**[CloudShell]** を選択します。

   1. **最近アクセスした**ウィジェットで、[**CloudShell**] を選択します。

   1. コンソールのツールバーから **[CloudShell]** を選択します。

1. DynamoDB local を AWS CloudShell で実行するには、`dynamodb-local` エイリアスを使用できます。追加のコマンドラインオプションを指定して、DynamoDB local の設定を変更できます。使用可能なオプションについては、「[DynamoDB local の使用に関する注意事項](DynamoDBLocal.UsageNotes.md)」を参照してください。
**注記**  
DynamoDB local をバックグラウンドで 実行するには、`dynamodb-local &` を使用して AWS CloudShell で DynamoDB local を実行します。

1. AWS CLI を使用して AWS CloudShell でローカル実行中の DynamoDB にアクセスするには、`--endpoint-url` パラメータを使用します。例えば、次のコマンドを使用して DynamoDB テーブルを一覧表示します。

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

JAR ファイルのダウンロード、Docker イメージとしての実行、Maven 依存関係としての使用など、DynamoDB をローカルに設定して使用する複数の方法を紹介するサンプルプロジェクトの例については、「[DynamoDB Local Sample Java Project](https://github.com/awslabs/amazon-dynamodb-local-samples/tree/main)」を参照してください。

# DynamoDB local の使用に関する注意事項
<a name="DynamoDBLocal.UsageNotes"></a>

 エンドポイントを除き、ダウンロード可能なバージョンの Amazon DynamoDB で実行するアプリケーションは DynamoDB ウェブサービスでも動作します。ただし、DynamoDB をローカルで使用する場合は、以下に注意する必要があります。
+  `-sharedDb` オプションを使用すると、DynamoDB は *shared-local-instance.db* という名前の単一のデータベースファイルを作成します。DynamoDB に接続するプログラムはいずれも、このファイルにアクセスします。このファイルを削除すると、保存されたすべてのデータを失うことになります。
+  `-sharedDb` を省略する場合のデータベースファイルの名前は、*myaccesskeyid\$1region.db* で、アプリケーション設定に表示されるとおりの AWS アクセスキー ID と AWS リージョンが使用されます。このファイルを削除すると、保存されたすべてのデータを失うことになります。
+  `-inMemory` オプションを使用した場合、DynamoDB はデータベースファイルの書き込みをまったく行いません。代わりに、すべてのデータがメモリに書き込まれ、DynamoDB を終了するときにデータは保存されません。
+  `-inMemory` オプション使用する場合は、`-sharedDb` オプションも必要です。
+  `-optimizeDbBeforeStartup` オプションを使用した場合は、`-dbPath` パラメータも指定し、DynamoDB がそのデータベースファイルを見つけられるようにする必要があります。
+  DynamoDB 用 AWS SDK では、アプリケーション設定でアクセスキーバリューと AWS リージョンの値を指定する必要があります。`-sharedDb` または `-inMemory` オプションを使用している場合を除き、DynamoDB はこれらの値を使用してローカルデータベースファイルに名前を付けます。これらの値は、ローカルで動作する有効な AWS 値である必要はありません。ただし、使用しているエンドポイントを変更して、クラウドでもコードを実行できるように、有効な値を使用する方が便利な場合があります。
+  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 ウェブサービスの違い](#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 ウェブサービスの動作をより正確にシミュレートしやすくなります。(現在、このパラメータではステータスが *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>

 AWS SDK およびツールは、デフォルトで Amazon DynamoDB ウェブサービスのエンドポイントを使用します。ダウンロード可能なバージョンの DynamoDB を使用して SDK およびツールを使用するには、ローカルエンドポイントを指定する必要があります。

 `http://localhost:8000` 

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

 AWS Command Line Interface (AWS CLI) を使用して、ダウンロード可能な DynamoDB を操作できます。

 ローカルで実行中の DynamoDB にアクセスするには、`--endpoint-url` パラメータを使用します。AWS CLI を使用して、コンピュータにある DynamoDB のテーブルを一覧表示する例を次に示します。

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

**注記**  
 AWS CLI では、ダウンロード可能なバージョンの DynamoDB をデフォルトのエンドポイントとして使用することはできません。そのため、各 `--endpoint-url` コマンドで AWS CLI を指定する必要があります。

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

 エンドポイントを指定する方法は、使用しているプログラミング言語と AWS SDK によって異なります。以下のセクションでは、エンドポイントの指定方法について説明します。
+  [Java: AWS リージョンとエンドポイントの設定](CodeSamples.Java.md#CodeSamples.Java.RegionAndEndpoint) (DynamoDB local は、AWS SDK for Java V1 および V2 をサポートしています) 
+ CodeSamples.Java.RegionAndEndpoint [.NET: AWS リージョンとエンドポイントの設定](CodeSamples.DotNet.md#CodeSamples.DotNet.RegionAndEndpoint) 

## ダウンロード可能な DynamoDB と DynamoDB ウェブサービスの違い
<a name="DynamoDBLocal.Differences"></a>

 ダウンロード可能バージョンの DynamoDB は、開発とテストのみを目的としています。これに対して、DynamoDB ウェブサービスは、スケーラビリティ、可用性、耐久性を特徴とする本稼働環境用に最適なマネージドサービスです。

 ダウンロード可能なバージョンの DynamoDB とウェブサービスは、次の点で異なります。
+ AWS リージョンと個別の AWS アカウントは、クライアントレベルでサポートされません。
+  プロビジョンされたスループット設定は、ダウンロード可能な DynamoDB で無視されます。ただし、この設定は `CreateTable` オペレーションで必要です。`CreateTable` の場合、プロビジョニングされた読み込みおよび書き込みスループットに対して任意の数値を指定できます。ただし、この数値は使用されません。`UpdateTable` は 1 日に必要な回数呼び出すことができます。ただし、プロビジョニングされたスループット値に対する変更はいずれも無視されます。
+  `Scan` 操作が連続的に行われます。並列スキャンはサポートされていません。`Segment` と `TotalSegments` パラメータ (`Scan` オペレーション) は無視されます。
+  読み込みおよび書き込みオペレーションの速度は、コンピュータの速度によってのみ制限を受けます。`CreateTable`、 `UpdateTable`、および `DeleteTable` オペレーションはすぐに実行されます。テーブルの状態は常に ACTIVE です。テーブルやグローバルセカンダリインデックスでプロビジョニングされたスループット設定のみを変更する `UpdateTable` オペレーションは、すぐに実行されます。`UpdateTable` オペレーションがグローバルセカンダリインデックスを作成または削除する場合、それらのインデックスは、通常の状態 (CREATING や DELETING など) に移行してから ACTIVE 状態になります。この間、テーブルは ACTIVE のままになります。
+  読み込みオペレーションには結果整合性があります。ただし、コンピュータで実行されている DynamoDB の速度が原因で、ほとんどの読み取りには強力な整合性があるように見えます。
+  項目コレクションのメトリクスや項目コレクションのサイズは追跡されません。オペレーションレスポンスでは、項目コレクションのメトリクスの代わりに、null が返されます。
+  DynamoDB では、結果セットごとに、返されるデータに 1 MB の制限があります。DynamoDB ウェブサービスとダウンロード可能バージョンのいずれにもこの制限が適用されます。ただし、インデックスのクエリを実行しているとき、DynamoDB サービスは、射影されたキーと属性のサイズのみを計算します。一方で、ダウンロード可能バージョンの DynamoDB は、項目全体のサイズを計算します。
+  DynamoDB Streams を使用している場合、シャードが作成される速度が異なる可能性があります。DynamoDB ウェブサービスでは、シャードの作成動作は部分的にテーブルパーティションアクティビティの影響を受けます。ローカルで DynamoDB を実行している場合は、テーブルパーティションがありません。どちらの場合も、シャードはエフェメラルのため、アプリケーションがシャードの動作の影響を受けることはありません。
+  ダウンロード可能な DynamoDB では、`TransactionConflictExceptions` はトランザクション API に対してスローされません。Java モック作成フレームワークを使用して DynamoDB ハンドラで `TransactionConflictExceptions` をシミュレートし、競合するトランザクションに対するアプリケーションの応答をテストすることをお勧めします。
+  DynamoDB ウェブサービスでは、コンソールまたは AWS CLI のどちらからアクセスする場合でも、テーブル名の大文字と小文字は区別されます。`Authors` という名前のテーブルと `authors` という名前のテーブルが、別のテーブルとして両方存在できます。ダウンロード可能バージョンでは、テーブル名で大文字と小文字が区別されず、これら 2 つのテーブルを作成しようとすると、エラーが発生します。
+ ダウンロード可能なバージョンの DynamoDB で、タグ付けはサポートされていません。
+ ダウンロード可能なバージョンの DynamoDB では、[ExecuteStatement](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ExecuteStatement.html) の [Limit](https://docs.aws.amazon.com/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.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2026 年 1 月 19 日  | 
| 3.2.0 |  複数の Kotlin バージョンとの互換性の問題を修正  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2026 年 1 月 9 日  | 
| 3.1.0 |  Joda 時間の依存関係を含む PartiQL クエリのパフォーマンスの向上  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2025 年 9 月 14 日  | 
| 3.0.0 |  AWS SDK Java V1 から V2 への移行  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2025 年 7 月 17 日  | 
| 2.6.0 |  DynamoDB API でテーブル ARN をテーブル名としてサポート パフォーマンスの修正とセキュリティ更新  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2025 年 3 月 13 日  | 
| 2.5.4 |  Jetty の依存関係へのアップグレード  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2024 年 12 月 12 日  | 
| 2.5.3 |  Log4j Core の Jackson Dependencies を 2.17.x にアップグレード (CVE-2022-1471 を解決)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2024 年 11 月 6 日  | 
| 2.5.2 | テーブル更新ワークフローのバグ修正 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  | 2024 年 6 月 20 日 | 
| 2.5.1 | OndemandThroughPut 機能で導入されたバグのパッチ  | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html) | 2024 年 6 月 5 日 | 
| 2.5.0 |  オンデマンドテーブル用の設定可能な最大スループットのサポート：`ReturnValuesOnConditionCheckFailure`、`BatchExecuteStatement`、および `ExecuteTransactionRequest`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2024 年 5 月 28 日  | 
| 2.4.0 |  `ReturnValuesOnConditionCheckFailure` のサポート -埋め込みモード  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2024 年 4 月 17 日  | 
| 2.3.0 |  Jetty および JDK のアップグレード  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2024 年 3 月 14 日  | 
| 2.2.0 |  テーブル削除保護と `ReturnValuesOnConditionCheckFailure` パラメータのサポートが追加されました。  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 12 月 14 日  | 
| 2.1.0 |  Maven プロジェクト用の SQLLite ネイティブライブラリのサポートとテレメトリの追加  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 10 月 23 日  | 
| 2.0.0 |  javax から jakarta 名前空間への移行と JDK11 サポート  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 7 月 5 日  | 
| 1.25.1 |  Log4j Core の Jackson Dependencies を 2.17.x にアップグレード (CVE-2022-1471 を解決)  |  Log4j Core の Jackson Dependencies を 2.17.x にアップグレード (CVE-2022-1471 を解決) して、一時的な依存関係である SnakeYAML ライブラリの重要なセキュリティ脆弱性に対処  |  2024 年 11 月 6 日  | 
| 1.25.0 |  テーブル削除保護と `ReturnValuesOnConditionCheckFailure` パラメータのサポートが追加されました。  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 12 月 18 日  | 
| 1.24.0 |  Maven プロジェクト用の SQLLite ネイティブライブラリのサポートとテレメトリの追加  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 10 月 23 日  | 
| 1.23.0 |  サーバー起動時の無効なアクセスとシークレットキーに対処  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 6 月 28 日  | 
| 1.22.0 |  PartiQL のリミット操作のサポート  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 6 月 8 日  | 
| 1.21.0 |  トランザクションあたり 100 アクションをサポート  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2023 年 1 月 26 日  | 
| 1.20.0 |  M1 Mac のサポートを追加  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  |  2022 年 9 月 12 日  | 
| 1.19.0 |  PartiQL Parser をアップグレード  |  PartiQL Parser およびその他の関連ライブラリをアップグレード  |  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 の依存関係を更新し、リモートコード実行を防ぐためにゼロデイエクスプロイトにパッチを適用 - Log4Shell | 2021 年 1 月 10 日 | 
| 1.17.0 | JavaScript Web Shell を非推奨化 |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/DynamoDBLocalHistory.html)  | 2021 年 1 月 8 日 | 

# DynamoDB local のテレメトリ
<a name="DynamoDBLocalTelemetry"></a>

 AWS では、お客様とのやり取りから学んだことに基づいてサービスを開発して提供し、お客様からのフィードバックを使用して製品を練り直しています。テレメトリは、お客様のニーズをより深く理解して、問題を診断し、カスタマーエクスペリエンスを向上させる機能を提供するために役立つ追加情報です。

 DynamoDB local は、一般的な使用状況メトリクス、システムおよび環境の情報、エラーなどのテレメトリを収集します。収集されるテレメトリのタイプの詳細については、「[収集される情報のタイプ](#DynamoDBLocalTelemetry.TypesOfInformationCollected)」を参照してください。

 DynamoDB local は、ユーザー名や E メールアドレスなどの個人情報は収集しません。また、プロジェクトレベルの機密情報も抽出しません。

 お客様は、テレメトリを有効にするかどうかを制御し、いつでも設定を変更できます。テレメトリが有効化されたままの場合、DynamoDB local はテレメトリデータをバックグラウンドで送信します。この際、お客様との追加のやり取りは不要です。

## コマンドラインオプションを使用してテレメトリを無効にする
<a name="DynamoDBLocalTelemetry.cli"></a>

 オプション `-disableTelemetry` によって DynamoDB local を起動するときに、コマンドラインオプションを使用してテレメトリを無効にすることができます。詳細については、「[コマンドラインオプション](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 で収集されるテレメトリデータは、AWS データプライバシーポリシーに準拠します。詳細については次を参照してください: 
+  [AWS サービス利用規約](https://aws.amazon.com/service-terms/) 
+  [データプライバシーに関するよくある質問](https://aws.amazon.com/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)」のステップに従ってください。

## AWS マネジメントコンソール
<a name="getting-started-step-1-Console"></a>

DynamoDB コンソールを使用して新しい `Music` テーブルを作成するには

1. AWS マネジメントコンソールにサインインして DynamoDB コンソール ([https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)) を開きます。

1. 左のナビゲーションペインで、**[テーブル]** を選択します。

1. **[テーブルの作成]** を選択します。

1. **[テーブルの詳細]** を次のように入力します。

   1. **[テーブル名]** に **Music** と入力します。

   1. **[パーティションキー]** に **Artist** と入力します。

   1. **[ソートキー]** に **SongTitle** と入力します。

1. **[テーブル設定]** は、**[デフォルト設定]** を選択したままにします。

1. **[テーブルを作成]** を選択してテーブルを作成します。  
![\[テーブルの詳細が入力された [テーブルを作成] ページ。\]](http://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/images/GettingStarted/CreateTableMusic.png)

1. テーブルのステータスが [`ACTIVE`] になったら、次の手順を実行して、テーブルの [[DynamoDB のポイントインタイムバックアップ](Point-in-time-recovery.md)] を有効にすることをお勧めします。

   1. テーブル名を選択してテーブルを開きます。

   1. **[バックアップ]** を選択します。

   1. **[ポイントインタイムリカバリ (PITR)]** セクションで、**[編集]** を選択します。

   1. **[ポイントインタイムリカバリ設定の編集]** ページで、**[ポイントタイムリカバリの有効化]** を選択します。

   1. **[Save changes]** (変更の保存) をクリックします。

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

次の AWS CLI の例では、`Music` を使用して新しい `create-table` テーブルを作成します。

**Linux**

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

**Windows CMD**

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

`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://aws.amazon.com/dynamodb/pricing)」を参照してください。

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

次のコード例は、AWS SDK を使用して DynamoDB テーブルを作成する方法を示しています。

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

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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

            TableStatus status;

            int sleepDuration = 2000;

            do
            {
                Thread.Sleep(sleepDuration);

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

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

            return status == TableStatus.ACTIVE;
        }
        catch (ResourceInUseException ex)
        {
            Console.WriteLine($"Table {tableName} already exists. {ex.Message}");
            throw;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while creating table {tableName}. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating table {tableName}. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「**AWS SDK for .NET API リファレンス」の「[CreateTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/CreateTable)」を参照してください。

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

**Bash スクリプトを使用した AWS CLI**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

  # Retrieve the calling parameters.
  while getopts "n:a:k:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      a) attribute_definitions="${OPTARG}" ;;
      k) key_schema="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

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

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

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

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

  local error_code=${?}

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

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 の詳細については、**「AWS CLI コマンドリファレンス」の「[CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)」を参照してください。

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

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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

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

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

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

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

    return waitTableActive(tableName, dynamoClient);
}
```
テーブルがアクティブになるまで待機するコード。  

```
//! 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 の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/CreateTable)」を参照してください。

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

**AWS CLI**  
**例 1: タグ付きのテーブルを作成するには**  
次の `create-table` の例では、指定された属性とキースキーマを使用して、`MusicCollection` という名前のテーブルを作成します。このテーブルはプロビジョニングされたスループットを使用し、保存時にはデフォルトの AWS 所有の 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 ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/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 ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/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 ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 4: ローカルセカンダリインデックスを持つテーブルを作成するには**  
次の例では、指定された属性とキースキーマを使用して、`AlbumTitleIndex` という名前のローカルセカンダリインデックスを持つ `MusicCollection` という名前のテーブルを作成します。  

```
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 ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 5: グローバルセカンダリインデックスを持つテーブルを作成するには**  
次の例では、`GameTitleIndex` という名前のグローバルセカンダリインデックスを持つ `GameScores` という名前のテーブルを作成します。ベーステーブルには、パーティションキー `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 ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 6: 複数のグローバルセカンダリインデックスを持つテーブルを一度に作成するには**  
次の例では、2 つのグローバルセカンダリインデックスを持つ `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 ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 7: ストリームが有効なテーブルを作成するには**  
次の例では、DynamoDB ストリームを有効にした状態の `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 \
    --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 ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 8: Keys-Only ストリームが有効なテーブルを作成するには**  
次の例では、DynamoDB ストリームを有効にした状態の `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 \
    --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.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)」を参照してください。**  
**例 9: Standard Infrequent Access クラスでテーブルを作成するには**  
次の例は、`GameScores` という名前のテーブルを作成し、Standard-Infrequent Access (DynamoDB Standard-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.aws.amazon.com/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.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeletionProtection)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/create-table.html)」を参照してください。

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

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// CreateMovieTable creates a DynamoDB table with a composite primary key defined as
// a string sort key named `title`, and a numeric partition key named `year`.
// This function uses NewTableExistsWaiter to wait for the table to be created by
// DynamoDB before it returns.
func (basics TableBasics) CreateMovieTable(ctx context.Context) (*types.TableDescription, error) {
	var tableDesc *types.TableDescription
	table, err := basics.DynamoDbClient.CreateTable(ctx, &dynamodb.CreateTableInput{
		AttributeDefinitions: []types.AttributeDefinition{{
			AttributeName: aws.String("year"),
			AttributeType: types.ScalarAttributeTypeN,
		}, {
			AttributeName: aws.String("title"),
			AttributeType: types.ScalarAttributeTypeS,
		}},
		KeySchema: []types.KeySchemaElement{{
			AttributeName: aws.String("year"),
			KeyType:       types.KeyTypeHash,
		}, {
			AttributeName: aws.String("title"),
			KeyType:       types.KeyTypeRange,
		}},
		TableName:   aws.String(basics.TableName),
		BillingMode: types.BillingModePayPerRequest,
	})
	if err != nil {
		log.Printf("Couldn't create table %v. Here's why: %v\n", basics.TableName, err)
	} else {
		waiter := dynamodb.NewTableExistsWaiter(basics.DynamoDbClient)
		err = waiter.Wait(ctx, &dynamodb.DescribeTableInput{
			TableName: aws.String(basics.TableName)}, 5*time.Minute)
		if err != nil {
			log.Printf("Wait for table exists failed. Here's why: %v\n", err)
		}
		tableDesc = table.TableDescription
		log.Printf("Ccreating table test")
	}
	return tableDesc, err
}
```
+  API の詳細については、『*AWS SDK for Go API リファレンス*』の「[CreateTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.CreateTable)」を参照してください。

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

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

            Usage:
                <tableName> <key>

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

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

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

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

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

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

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

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/CreateTable)」を参照してください。

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

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

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

const client = new DynamoDBClient({});

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

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/CreateTableCommand)」を参照してください。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

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

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  AttributeDefinitions: [
    {
      AttributeName: "CUSTOMER_ID",
      AttributeType: "N",
    },
    {
      AttributeName: "CUSTOMER_NAME",
      AttributeType: "S",
    },
  ],
  KeySchema: [
    {
      AttributeName: "CUSTOMER_ID",
      KeyType: "HASH",
    },
    {
      AttributeName: "CUSTOMER_NAME",
      KeyType: "RANGE",
    },
  ],
  ProvisionedThroughput: {
    ReadCapacityUnits: 1,
    WriteCapacityUnits: 1,
  },
  TableName: "CUSTOMER_LIST",
  StreamSpecification: {
    StreamEnabled: false,
  },
};

// Call DynamoDB to create the table
ddb.createTable(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Table Created", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateTable](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/CreateTable)」を参照してください。

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

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        var tableArn: String
        val response = ddb.createTable(request)
        ddb.waitUntilTableExists {
            // suspend call
            tableName = tableNameVal
        }
        tableArn = response.tableDescription!!.tableArn.toString()
        println("Table $tableArn is ready")
        return tableArn
    }
}
```
+  API の詳細については、「[AWS SDK for Kotlin API リファレンス](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」の「*CreateTable*」を参照してください。

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

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コードサンプルリポジトリ](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 の詳細については、「*AWS SDK for PHP API リファレンス*」の「[CreateTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/CreateTable)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: この例では、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキーを持つ「Thread」という名前のテーブルを作成します。テーブルの作成に使用したスキーマは、図のように各 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: この例では、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキーを持つ Thread という名前のテーブルを作成します。ローカルセカンダリインデックスも定義されます。ローカルセカンダリインデックスのキーは、テーブルのプライマリハッシュキー (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: この例では、単一のパイプラインを使用して、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキー、およびローカルセカンダリインデックスを持つ「Thread」という名前のテーブルを作成する方法を示します。TableSchema がパイプラインまたは -Schema パラメータから提供されない場合、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 の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateTable](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキーを持つ「Thread」という名前のテーブルを作成します。テーブルの作成に使用したスキーマは、図のように各 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: この例では、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキーを持つ Thread という名前のテーブルを作成します。ローカルセカンダリインデックスも定義されます。ローカルセカンダリインデックスのキーは、テーブルのプライマリハッシュキー (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: この例では、単一のパイプラインを使用して、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキー、およびローカルセカンダリインデックスを持つ「Thread」という名前のテーブルを作成する方法を示します。TableSchema がパイプラインまたは -Schema パラメータから提供されない場合、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 の詳細については、「*AWS Tools for PowerShell Cmdlet リファレンス (V5)*」の「[CreateTable](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
映画データを格納するためのテーブルを作成します。  

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

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

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


    def 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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/CreateTable)」を参照してください。

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

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

  # Creates an Amazon DynamoDB table that can be used to store movie data.
  # The table uses the release year of the movie as the partition key and the
  # title as the sort key.
  #
  # @param table_name [String] The name of the table to create.
  # @return [Aws::DynamoDB::Table] The newly created table.
  def create_table(table_name)
    @table = @dynamo_resource.create_table(
      table_name: table_name,
      key_schema: [
        { attribute_name: 'year', key_type: 'HASH' }, # Partition key
        { attribute_name: 'title', key_type: 'RANGE' } # Sort key
      ],
      attribute_definitions: [
        { attribute_name: 'year', attribute_type: 'N' },
        { attribute_name: 'title', attribute_type: 'S' }
      ],
      billing_mode: 'PAY_PER_REQUEST'
    )
    @dynamo_resource.client.wait_until(:table_exists, table_name: table_name)
    @table
  rescue Aws::DynamoDB::Errors::ServiceError => e
    @logger.error("Failed create table #{table_name}:\n#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[CreateTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/CreateTable)」を参照してください。

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

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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

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

    match create_table_response {
        Ok(out) => {
            println!("Added table {} with key {}", table, key);
            Ok(out)
        }
        Err(e) => {
            eprintln!("Got an error creating table:");
            eprintln!("{}", e);
            Err(Error::unhandled(e))
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Rust API リファレンス」の「[CreateTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.create_table)」を参照してください。

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

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

        " Adjust read/write capacities as desired.
        DATA(lo_dynprovthroughput)  = NEW /aws1/cl_dynprovthroughput(
          iv_readcapacityunits = 5
          iv_writecapacityunits = 5 ).
        oo_result = lo_dyn->createtable(
          it_keyschema = lt_keyschema
          iv_tablename = iv_table_name
          it_attributedefinitions = lt_attributedefinitions
          io_provisionedthroughput = lo_dynprovthroughput ).
        " Table creation can take some time. Wait till table exists before returning.
        lo_dyn->get_waiter( )->tableexists(
          iv_max_wait_time = 200
          iv_tablename     = iv_table_name ).
        MESSAGE 'DynamoDB Table' && iv_table_name && 'created.' TYPE 'I'.
        " This exception can happen if the table already exists.
      CATCH /aws1/cx_dynresourceinuseex INTO DATA(lo_resourceinuseex).
        DATA(lv_error) = |"{ lo_resourceinuseex->av_err_code }" - { lo_resourceinuseex->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

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

**SDK for Swift**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
import AWSDynamoDB


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

            let input = CreateTableInput(
                attributeDefinitions: [
                    DynamoDBClientTypes.AttributeDefinition(attributeName: "year", attributeType: .n),
                    DynamoDBClientTypes.AttributeDefinition(attributeName: "title", attributeType: .s)
                ],
                billingMode: DynamoDBClientTypes.BillingMode.payPerRequest,
                keySchema: [
                    DynamoDBClientTypes.KeySchemaElement(attributeName: "year", keyType: .hash),
                    DynamoDBClientTypes.KeySchemaElement(attributeName: "title", keyType: .range)
                ],
                tableName: self.tableName
            )
            let output = try await client.createTable(input: input)
            if output.tableDescription == nil {
                throw MoviesError.TableNotFound
            }
        } catch {
            print("ERROR: createTable:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[CreateTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/createtable(input:))」を参照してください。

------

DynamoDB のその他の例については、「[AWS 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)」を参照してください。

## AWS マネジメントコンソール
<a name="getting-started-step-2-Console"></a>

以下の手順に従い、DynamoDB コンソールを使用して `Music` テーブルにデータを書き込みます。

1. DynamoDB コンソール ([https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)) を開きます。

1. 左のナビゲーションペインで、**[テーブル]** を選択します。

1. **[テーブル]** ページで、**[Music]** テーブルを選択します。

1. **[Explore table items]** (テーブルアイテムの探索) を選択します。

1. **[返された項目]** セクションで、**[項目を作成]** を選択します。

1. **[項目を作成]** ページで、次の操作を行ってテーブルに項目を追加します。

   1. [**新規属性を追加**] を選択し、[**数値**] を選択します。

   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. [**項目を作成**] を選択します。

1. このプロセスを繰り返して、次の値を持つ別の項目を作成します。

   1. [**Artist**] に「**Acme Band**」と入力します。

   1. [**SongTitle**] に「**Happy Day**」と入力します。

   1. [**AlbumTitle**] に「**Songs About Life**」と入力します。

   1. **[Awards]** に **10** と入力します。

1. これをもう一度実行して、前のステップと同じ **Artist** を含むが、その他の属性の値が異なる項目を作成します。

   1. [**Artist**] に「**Acme Band**」と入力します。

   1. [**SongTitle**] に「**PartiQL Rocks**」と入力します。

   1. [**AlbumTitle**] に「**Another Album Title**」と入力します。

   1. **[Awards]** に **8** と入力します。

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

次の AWS CLI の例では、`Music` テーブルで複数の新しい項目を作成します。この操作は、DynamoDB API または [PartiQL](https://docs.aws.amazon.com/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.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.insert.html)」を参照してください。

------

DynamoDB でサポートされるデータ型の詳細については、「[データ型](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes)」を参照してください。

JSON で DynamoDB のデータ型を表す方法については、「[属性値](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html)」を参照してください。

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

次のコード例は、AWS SDK を使用して DynamoDB テーブルに項目を書き込む方法を示しています。

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

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

            await _amazonDynamoDB.PutItemAsync(request);
            return true;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while putting item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while putting item. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「**AWS SDK for .NET API リファレンス」の「[PutItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/PutItem)」を参照してください。

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

**Bash スクリプトを使用した AWS CLI**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

  while getopts "n:i:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      i) item="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$item" ]]; then
    errecho "ERROR: You must provide an item with the -i parameter."
    usage
    return 1
  fi

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

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

  local error_code=${?}

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

  return 0

}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 の詳細については、**「AWS CLI コマンドリファレンス」の「[PutItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem)」を参照してください。

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

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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

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

    return waitTableActive(tableName, dynamoClient);
}
```
テーブルがアクティブになるまで待機するコード。  

```
//! 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 の詳細については、*AWS SDK for C\$1\$1 API リファレンス*のの「[PutItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/PutItem)」を参照してください。

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

**AWS 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.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)」を参照してください。**  
**例 2: テーブル内の項目を条件付きで上書きするには**  
次の `put-item` の例は、`MusicCollection` テーブル内の既存の項目に `Greatest Hits` の値を持つ `AlbumTitle` 属性がある場合にのみ、その項目を上書きします。このコマンドは、その項目の以前の値を返します。  

```
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.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/put-item.html)」を参照してください。

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

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// AddMovie adds a movie the DynamoDB table.
func (basics TableBasics) AddMovie(ctx context.Context, movie Movie) error {
	item, err := attributevalue.MarshalMap(movie)
	if err != nil {
		panic(err)
	}
	_, err = basics.DynamoDbClient.PutItem(ctx, &dynamodb.PutItemInput{
		TableName: aws.String(basics.TableName), Item: item,
	})
	if err != nil {
		log.Printf("Couldn't add item to table. Here's why: %v\n", err)
	}
	return err
}
```
この例で使用している Movie struct を定義します。  

```
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 の詳細については、*AWS SDK for Go API リファレンス*の「[PutItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.PutItem)」を参照してください。

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

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
[DynamoDbClient](https://docs.aws.amazon.com/sdk-for-java/latest/reference/software/amazon/awssdk/services/dynamodb/DynamoDbClient.html) を使用してテーブルに項目を配置します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import java.util.HashMap;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 * To place items into an Amazon DynamoDB table using the AWS SDK for Java V2,
 * its better practice to use the
 * Enhanced Client. See the EnhancedPutItem example.
 */
public class PutItem {
    public static void main(String[] args) {
        final String usage = """

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

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

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

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

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

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

    public static void putItemInTable(DynamoDbClient ddb,
            String tableName,
            String key,
            String keyVal,
            String albumTitle,
            String albumTitleValue,
            String awards,
            String awardVal,
            String songTitle,
            String songTitleVal) {

        HashMap<String, AttributeValue> itemValues = new HashMap<>();
        itemValues.put(key, AttributeValue.builder().s(keyVal).build());
        itemValues.put(songTitle, AttributeValue.builder().s(songTitleVal).build());
        itemValues.put(albumTitle, AttributeValue.builder().s(albumTitleValue).build());
        itemValues.put(awards, AttributeValue.builder().s(awardVal).build());

        PutItemRequest request = PutItemRequest.builder()
                .tableName(tableName)
                .item(itemValues)
                .build();

        try {
            PutItemResponse response = ddb.putItem(request);
            System.out.println(tableName + " was successfully updated. The request id is "
                    + response.responseMetadata().requestId());

        } catch (ResourceNotFoundException e) {
            System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
            System.err.println("Be sure that it exists and that you've typed its name correctly!");
            System.exit(1);
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[PutItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem)」を参照してください。**

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

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[PutCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/PutCommand/)」を参照してください。  

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

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

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

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/PutItemCommand)」を参照してください。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
テーブルに項目を配置します。  

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

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: "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);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write.html#dynamodb-example-table-read-write-writing-an-item)」を参照してください。
+  API の詳細については、[AWS SDK for JavaScript API リファレンス](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/PutItem)の「*PutItem*」を参照してください。

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

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.putItem(request)
        println(" A new item was placed into $tableNameVal.")
    }
}
```
+  API の詳細については、[AWS SDK for Kotlin API リファレンス](https://sdk.amazonaws.com/kotlin/api/latest/index.html)の「*PutItem*」を参照してください。

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

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コードサンプルリポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

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

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

    public function putItem(array $array)
    {
        $this->dynamoDbClient->putItem($array);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[PutItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/PutItem)」を参照してください。**

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

**Tools for 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 の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutItem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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 の詳細については、「*AWS Tools for PowerShell Cmdlet リファレンス (V5)*」の「[PutItem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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


    def add_movie(self, title, year, plot, rating):
        """
        Adds a movie to the table.

        :param title: The title of the movie.
        :param year: The release year of the movie.
        :param plot: The plot summary of the movie.
        :param rating: The quality rating of the movie.
        """
        try:
            self.table.put_item(
                Item={
                    "year": year,
                    "title": title,
                    "info": {"plot": plot, "rating": Decimal(str(rating))},
                }
            )
        except ClientError as err:
            logger.error(
                "Couldn't add movie %s to table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[PutItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem)」を参照してください。

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

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamo_resource.table(table_name)
  end

  # Adds a movie to the table.
  #
  # @param movie [Hash] The title, year, plot, and rating of the movie.
  def add_item(movie)
    @table.put_item(
      item: {
        'year' => movie[:year],
        'title' => movie[:title],
        'info' => { 'plot' => movie[:plot], 'rating' => movie[:rating] }
      }
    )
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't add movie #{title} to table #{@table.name}. Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[PutItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/PutItem)」を参照してください。**

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

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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

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

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

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

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

    Ok(ItemOut {
        p_type,
        age,
        username,
        first_name,
        last_name,
    })
}
```
+  API の詳細については、[AWS SDK for Rust API リファレンス](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.put_item)の「*PutItem*」を参照してください。

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

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_resp) = lo_dyn->putitem(
          iv_tablename = iv_table_name
          it_item      = it_item ).
        MESSAGE '1 row inserted into DynamoDB Table' && iv_table_name TYPE 'I'.
      CATCH /aws1/cx_dyncondalcheckfaile00.
        MESSAGE 'A condition specified in the operation could not be evaluated.' TYPE 'E'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
      CATCH /aws1/cx_dyntransactconflictex.
        MESSAGE 'Another transaction is using the item' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[PutItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

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

**SDK for Swift**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
import AWSDynamoDB


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

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

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

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


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

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

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

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

        return item
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[PutItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/putitem(input:))」を参照してください。

------

DynamoDB のその他の例については、「[AWS 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)」で作成した項目の 1 つを読み込みます。DynamoDB コンソールまたは AWS CLI を使用して、`Artist` および `SongTitle` を指定しながら `Music` テーブルの項目を読み込むことができます。

DynamoDB の読み込みオペレーションの詳細については、「[項目の読み込み](WorkingWithItems.md#WorkingWithItems.ReadingData)」を参照してください。

## AWS マネジメントコンソール
<a name="getting-started-step-3-Console"></a>

以下の手順に従い DynamoDB コンソールを使用して、`Music` テーブルからデータを読み込みます。

1. DynamoDB コンソール ([https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)) を開きます。

1. 左のナビゲーションペインで、**[テーブル]** を選択します。

1. **[テーブル]** ページで、**[Music]** テーブルを選択します。

1. **[テーブルアイテムの探索]** を選択します。

1. **[返された項目]** セクションで、テーブルに保存されている項目のリストを、`Artist` と `SongTitle` でソートして表示します。リストの最初の項目は、**[Artist]** として **[Acme Band]**、**[SongTitle]** として **[PartiQL Rocks]** になります。

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

次の AWS CLI の例では、`Music` から項目を読み込みます。この操作は、DynamoDB API または [PartiQL](https://docs.aws.amazon.com/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.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.SELECT.html)」を参照してください。

------

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

次のコード例は、AWS SDK を使用して DynamoDB テーブルから項目を読み込む方法を示しています。

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

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
    /// <summary>
    /// Gets information about an existing movie from the table.
    /// </summary>
    /// <param name="newMovie">A Movie object containing information about
    /// the movie to retrieve.</param>
    /// <param name="tableName">The name of the table containing the movie.</param>
    /// <returns>A Dictionary object containing information about the item
    /// retrieved.</returns>
    public async Task<Dictionary<string, AttributeValue>> GetItemAsync(Movie newMovie, string tableName)
    {
        try
        {
            var key = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = newMovie.Title },
                ["year"] = new AttributeValue { N = newMovie.Year.ToString() },
            };

            var request = new GetItemRequest
            {
                Key = key,
                TableName = tableName,
            };

            var response = await _amazonDynamoDB.GetItemAsync(request);
            return response.Item;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return new Dictionary<string, AttributeValue>();
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while getting item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while getting item. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「**AWS SDK for .NET API リファレンス」の「[GetItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/GetItem)」を参照してください。

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

**Bash スクリプトを使用した AWS CLI**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
#############################################################################
# function dynamodb_get_item
#
# This function gets an item from a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k keys  -- Path to json file containing the keys that identify the item to get.
#       [-q query]  -- Optional JMESPath query expression.
#
#  Returns:
#       The item as text output.
#  And:
#       0 - If successful.
#       1 - If it fails.
############################################################################
function dynamodb_get_item() {
  local table_name keys query response
  local option OPTARG # Required to use getopts command in a function.

  # ######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_get_item"
    echo "Get an item from a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k keys  -- Path to json file containing the keys that identify the item to get."
    echo " [-q query]  -- Optional JMESPath query expression."
    echo ""
  }
  query=""
  while getopts "n:k:q:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) keys="${OPTARG}" ;;
      q) query="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

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

  if [[ -n "$query" ]]; then
    response=$(aws dynamodb get-item \
      --table-name "$table_name" \
      --key file://"$keys" \
      --output text \
      --query "$query")
  else
    response=$(
      aws dynamodb get-item \
        --table-name "$table_name" \
        --key file://"$keys" \
        --output text
    )
  fi

  local error_code=${?}

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

  if [[ -n "$query" ]]; then
    echo "$response" | sed "/^\t/s/\t//1" # Remove initial tab that the JMSEPath query inserts on some strings.
  else
    echo "$response"
  fi

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 の詳細については、**「AWS CLI コマンドリファレンス」の「[GetItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/GetItem)」を参照してください。

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

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
//! Get an item from an Amazon DynamoDB table.
/*!
  \sa getItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::DynamoDB::getItem(const Aws::String &tableName,
                               const Aws::String &partitionKey,
                               const Aws::String &partitionValue,
                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);
    Aws::DynamoDB::Model::GetItemRequest request;

    // Set up the request.
    request.SetTableName(tableName);
    request.AddKey(partitionKey,
                   Aws::DynamoDB::Model::AttributeValue().SetS(partitionValue));

    // Retrieve the item's fields and values.
    const Aws::DynamoDB::Model::GetItemOutcome &outcome = dynamoClient.GetItem(request);
    if (outcome.IsSuccess()) {
        // Reference the retrieved fields/values.
        const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &item = outcome.GetResult().GetItem();
        if (!item.empty()) {
            // Output each retrieved field and its value.
            for (const auto &i: item)
                std::cout << "Values: " << i.first << ": " << i.second.GetS()
                          << std::endl;
        }
        else {
            std::cout << "No item found with the key " << partitionKey << std::endl;
        }
    }
    else {
        std::cerr << "Failed to get item: " << outcome.GetError().GetMessage();
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[GetItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/GetItem)」を参照してください。**

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

**AWS CLI**  
**例 1: テーブル内の項目を読み込むには**  
次の `get-item` の例は、`MusicCollection` テーブルから項目を取得します。テーブルにはハッシュおよび範囲プライマリキー (`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.aws.amazon.com/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.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData)」を参照してください。**  
**例 3: 項目の特定の属性を取得するには**  
次の例は、射影式を使用して目的のアイテムの 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.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/get-item.html)」を参照してください。

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

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// GetMovie gets movie data from the DynamoDB table by using the primary composite key
// made of title and year.
func (basics TableBasics) GetMovie(ctx context.Context, title string, year int) (Movie, error) {
	movie := Movie{Title: title, Year: year}
	response, err := basics.DynamoDbClient.GetItem(ctx, &dynamodb.GetItemInput{
		Key: movie.GetKey(), TableName: aws.String(basics.TableName),
	})
	if err != nil {
		log.Printf("Couldn't get info about %v. Here's why: %v\n", title, err)
	} else {
		err = attributevalue.UnmarshalMap(response.Item, &movie)
		if err != nil {
			log.Printf("Couldn't unmarshal response. Here's why: %v\n", err)
		}
	}
	return movie, err
}
```
この例で使用している Movie struct を定義します。  

```
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 の詳細については、*AWS SDK for Go API リファレンス*の「[GetItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.GetItem)」を参照してください。

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

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](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 の詳細については、AWS SDK for Java 2.x API リファレンスの「[GetItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/GetItem)」を参照してください。**

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

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[GetCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/GetCommand/)」を参照してください。  

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

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

export const main = async () => {
  const command = new GetCommand({
    TableName: "AngryAnimals",
    Key: {
      CommonName: "Shoebill",
    },
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/GetItemCommand)」を参照してください。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
テーブルから項目を取得します。  

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

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: "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);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-dynamodb-utilities.html#dynamodb-example-document-client-get)」を参照してください。
+  API の詳細については、[AWS SDK for JavaScript API リファレンス](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/GetItem)の「*GetItem*」を参照してください。

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

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
suspend fun getSpecificItem(
    tableNameVal: String,
    keyName: String,
    keyVal: String,
) {
    val keyToGet = mutableMapOf<String, AttributeValue>()
    keyToGet[keyName] = AttributeValue.S(keyVal)

    val request =
        GetItemRequest {
            key = keyToGet
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val returnedItem = ddb.getItem(request)
        val numbersMap = returnedItem.item
        numbersMap?.forEach { key1 ->
            println(key1.key)
            println(key1.value)
        }
    }
}
```
+  API の詳細については、[AWS SDK for Kotlin API リファレンス](https://sdk.amazonaws.com/kotlin/api/latest/index.html)の「*GetItem*」を参照してください。

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

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コードサンプルリポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
        $movie = $service->getItemByKey($tableName, $key);
        echo "\nThe movie {$movie['Item']['title']['S']} was released in {$movie['Item']['year']['N']}.\n";

    public function getItemByKey(string $tableName, array $key)
    {
        return $this->dynamoDbClient->getItem([
            'Key' => $key['Item'],
            'TableName' => $tableName,
        ]);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[GetItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/GetItem)」を参照してください。**

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

**Tools for 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 の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetItem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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 の詳細については、「*AWS Tools for PowerShell Cmdlet リファレンス (V5)*」の「[GetItem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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


    def get_movie(self, title, year):
        """
        Gets movie data from the table for a specific movie.

        :param title: The title of the movie.
        :param year: The release year of the movie.
        :return: The data about the requested movie.
        """
        try:
            response = self.table.get_item(Key={"year": year, "title": title})
        except ClientError as err:
            logger.error(
                "Couldn't get movie %s from table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Item"]
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/GetItem)」を参照してください。

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

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamo_resource.table(table_name)
  end

  # Gets movie data from the table for a specific movie.
  #
  # @param title [String] The title of the movie.
  # @param year [Integer] The release year of the movie.
  # @return [Hash] The data about the requested movie.
  def get_item(title, year)
    @table.get_item(key: { 'year' => year, 'title' => title })
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't get movie #{title} (#{year}) from table #{@table.name}:\n")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[GetItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/GetItem)」を参照してください。**

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

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
    TRY.
        oo_item = lo_dyn->getitem(
          iv_tablename                = iv_table_name
          it_key                      = it_key ).
        DATA(lt_attr) = oo_item->get_item( ).
        DATA(lo_title) = lt_attr[ key = 'title' ]-value.
        DATA(lo_year) = lt_attr[ key = 'year' ]-value.
        DATA(lo_rating) = lt_attr[ key = 'rating' ]-value.
        MESSAGE 'Movie name is: ' && lo_title->get_s( )
          && 'Movie year is: ' && lo_year->get_n( )
          && 'Moving rating is: ' && lo_rating->get_n( ) TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

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

**SDK for Swift**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
import AWSDynamoDB


    /// Return a `Movie` record describing the specified movie from the Amazon
    /// DynamoDB table.
    ///
    /// - Parameters:
    ///   - title: The movie's title (`String`).
    ///   - year: The movie's release year (`Int`).
    ///
    /// - Throws: `MoviesError.ItemNotFound` if the movie isn't in the table.
    ///
    /// - Returns: A `Movie` record with the movie's details.
    func get(title: String, year: Int) async throws -> Movie {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = GetItemInput(
                key: [
                    "year": .n(String(year)),
                    "title": .s(title)
                ],
                tableName: self.tableName
            )
            let output = try await client.getItem(input: input)
            guard let item = output.item else {
                throw MoviesError.ItemNotFound
            }

            let movie = try Movie(withItem: item)
            return movie
        } catch {
            print("ERROR: get:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[GetItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/getitem(input:))」を参照してください。

------

DynamoDB のその他の例については、「[AWS 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 コンソールまたは AWS CLI を使用して、`Artist`、`SongTitle` および更新された `AlbumTitle` を指定して `Music` テーブルの項目の `AlbumTitle` を更新できます。

書き込みオペレーションの詳細については、「[項目を書き込みます](WorkingWithItems.md#WorkingWithItems.WritingData)」を参照してください。

## AWS マネジメントコンソール
<a name="getting-started-step-4-Console"></a>

DynamoDB コンソールを使用して、`Music` テーブルのデータを更新できます。

1. DynamoDB コンソール ([https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)) を開きます。

1. 左のナビゲーションペインで、**[テーブル]** を選択します。

1. テーブルのリストから **[Music]** テーブルを選択します。

1. **[テーブルアイテムの探索]** を選択します。

1. **[返された項目]** の項目行 (**[Acme Band]** という **[Artist]** と **[Happy Day]** という **[SongTitle]**) で、次の操作を行います。

   1. **[Songs About Life]** という名前の **[AlbumTitle]** にカーソルを置きます。

   1. [編集] アイコンを選択します。

   1. **[文字列を編集]** ポップアップウィンドウに、「**Songs of Twilight**」と入力します。

   1. **[保存]** を選択します。
**ヒント**  
または、項目を更新するには、**[返された項目]** セクションで次の操作を行います。  
**[Artist]** として **[Acme Band]** および **[SongTitle]** として **[Happy Day]** を示す項目行を選択します。
**[アクション]** ドロップダウンリストで、**[項目の編集]** を選択します。
**[AlbumTitle]** に「**Songs of Twilight**」と入力します。
**[保存して閉じる]** を選択します。

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

次の AWS CLI の例では、`Music` テーブルの項目を更新します。この操作は、DynamoDB API または [PartiQL](https://docs.aws.amazon.com/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.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.update.html)」を参照してください。

------

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

次のコード例は、AWS SDK を使用して DynamoDB テーブルで項目を更新する方法を示しています。

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

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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

            await _amazonDynamoDB.UpdateItemAsync(request);
            return true;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} or item was not found. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while updating item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while updating item. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「**AWS SDK for .NET API リファレンス」の「[UpdateItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/UpdateItem)」を参照してください。

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

**Bash スクリプトを使用した AWS CLI**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
##############################################################################
# function dynamodb_update_item
#
# This function updates an item in a DynamoDB table.
#
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k keys  -- Path to json file containing the keys that identify the item to update.
#       -e update expression  -- An expression that defines one or more attributes to be updated.
#       -v values  -- Path to json file containing the update values.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
#############################################################################
function dynamodb_update_item() {
  local table_name keys update_expression values response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_update_item"
    echo "Update an item in a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k keys  -- Path to json file containing the keys that identify the item to update."
    echo " -e update expression  -- An expression that defines one or more attributes to be updated."
    echo " -v values  -- Path to json file containing the update values."
    echo ""
  }

  while getopts "n:k:e:v:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) keys="${OPTARG}" ;;
      e) update_expression="${OPTARG}" ;;
      v) values="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$keys" ]]; then
    errecho "ERROR: You must provide a keys json file path the -k parameter."
    usage
    return 1
  fi
  if [[ -z "$update_expression" ]]; then
    errecho "ERROR: You must provide an update expression with the -e parameter."
    usage
    return 1
  fi

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

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

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

  local error_code=${?}

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

  return 0

}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 の詳細については、**「AWS CLI コマンドリファレンス」の「[UpdateItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateItem)」を参照してください。

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

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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

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

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

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

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

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

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

    return waitTableActive(tableName, dynamoClient);
}
```
テーブルがアクティブになるまで待機するコード。  

```
//! 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 の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/UpdateItem)」を参照してください。

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

**AWS 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.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)」を参照してください。**  
**例 2: 項目を条件付きで更新するには**  
次の例は、既存の項目に `Year` 属性がない場合にのみ、`MusicCollection` テーブル内の項目を更新します。  

```
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.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-item.html)」を参照してください。

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

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// UpdateMovie updates the rating and plot of a movie that already exists in the
// DynamoDB table. This function uses the `expression` package to build the update
// expression.
func (basics TableBasics) UpdateMovie(ctx context.Context, movie Movie) (map[string]map[string]interface{}, error) {
	var err error
	var response *dynamodb.UpdateItemOutput
	var attributeMap map[string]map[string]interface{}
	update := expression.Set(expression.Name("info.rating"), expression.Value(movie.Info["rating"]))
	update.Set(expression.Name("info.plot"), expression.Value(movie.Info["plot"]))
	expr, err := expression.NewBuilder().WithUpdate(update).Build()
	if err != nil {
		log.Printf("Couldn't build expression for update. Here's why: %v\n", err)
	} else {
		response, err = basics.DynamoDbClient.UpdateItem(ctx, &dynamodb.UpdateItemInput{
			TableName:                 aws.String(basics.TableName),
			Key:                       movie.GetKey(),
			ExpressionAttributeNames:  expr.Names(),
			ExpressionAttributeValues: expr.Values(),
			UpdateExpression:          expr.Update(),
			ReturnValues:              types.ReturnValueUpdatedNew,
		})
		if err != nil {
			log.Printf("Couldn't update movie %v. Here's why: %v\n", movie.Title, err)
		} else {
			err = attributevalue.UnmarshalMap(response.Attributes, &attributeMap)
			if err != nil {
				log.Printf("Couldn't unmarshall update response. Here's why: %v\n", err)
			}
		}
	}
	return attributeMap, err
}
```
この例で使用している Movie struct を定義します。  

```
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 の詳細については、*AWS SDK for Go API リファレンス*の「[UpdateItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.UpdateItem)」を参照してください。

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

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
[DynamoDbClient](https://docs.aws.amazon.com/sdk-for-java/latest/reference/software/amazon/awssdk/services/dynamodb/DynamoDbClient.html) を使用してテーブルで項目を更新します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.AttributeAction;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import java.util.HashMap;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 * To update an Amazon DynamoDB table using the AWS SDK for Java V2, its better
 * practice to use the
 * Enhanced Client, See the EnhancedModifyItem example.
 */
public class UpdateItem {
    public static void main(String[] args) {
        final String usage = """

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

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

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

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

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

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

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

        HashMap<String, AttributeValueUpdate> updatedValues = new HashMap<>();
        updatedValues.put(name, AttributeValueUpdate.builder()
                .value(AttributeValue.builder().s(updateVal).build())
                .action(AttributeAction.PUT)
                .build());

        UpdateItemRequest request = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(itemKey)
                .attributeUpdates(updatedValues)
                .build();

        try {
            ddb.updateItem(request);
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("The Amazon DynamoDB table was updated!");
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)」を参照してください。

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

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[UpdateCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/UpdateCommand/)」を参照してください。  

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

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

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

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)」を参照してください。

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

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.updateItem(request)
        println("Item in $tableNameVal was updated")
    }
}
```
+  API の詳細については、[AWS SDK for Kotlin API リファレンス](https://sdk.amazonaws.com/kotlin/api/latest/index.html)の「*UpdateItem*」を参照してください。

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

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コードサンプルリポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

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

    public function updateItemAttributeByKey(
        string $tableName,
        array $key,
        string $attributeName,
        string $attributeType,
        string $newValue
    ) {
        $this->dynamoDbClient->updateItem([
            'Key' => $key['Item'],
            'TableName' => $tableName,
            'UpdateExpression' => "set #NV=:NV",
            'ExpressionAttributeNames' => [
                '#NV' => $attributeName,
            ],
            'ExpressionAttributeValues' => [
                ':NV' => [
                    $attributeType => $newValue
                ]
            ],
        ]);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

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

**Tools for 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 の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateItem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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 の詳細については、「*AWS Tools for PowerShell Cmdlet リファレンス (V5)*」の「[UpdateItem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
更新式を使用して項目を更新します。  

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

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

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


    def 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 の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)の「*UpdateItem*」を参照してください。

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

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamo_resource.table(table_name)
  end

  # Updates rating and plot data for a movie in the table.
  #
  # @param movie [Hash] The title, year, plot, rating of the movie.
  def update_item(movie)
    response = @table.update_item(
      key: { 'year' => movie[:year], 'title' => movie[:title] },
      update_expression: 'set info.rating=:r',
      expression_attribute_values: { ':r' => movie[:rating] },
      return_values: 'UPDATED_NEW'
    )
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't update movie #{movie[:title]} (#{movie[:year]}) in table #{@table.name}\n")
    puts("\t#{e.code}: #{e.message}")
    raise
  else
    response.attributes
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

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

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
    TRY.
        oo_output = lo_dyn->updateitem(
          iv_tablename        = iv_table_name
          it_key              = it_item_key
          it_attributeupdates = it_attribute_updates ).
        MESSAGE '1 item updated in DynamoDB Table' && iv_table_name TYPE 'I'.
      CATCH /aws1/cx_dyncondalcheckfaile00.
        MESSAGE 'A condition specified in the operation could not be evaluated.' TYPE 'E'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
      CATCH /aws1/cx_dyntransactconflictex.
        MESSAGE 'Another transaction is using the item' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[UpdateItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

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

**SDK for Swift**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
import AWSDynamoDB


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

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

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

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

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

            guard let attributes: [Swift.String: DynamoDBClientTypes.AttributeValue] = output.attributes else {
                throw MoviesError.InvalidAttributes
            }
            return attributes
        } catch {
            print("ERROR: update:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[UpdateItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/updateitem(input:))」を参照してください。

------

DynamoDB のその他の例については、「[AWS SDK を使用した DynamoDB のコード例](service_code_examples.md)」を参照してください。

`Music` テーブルのデータをクエリするには、「[ステップ 5: DynamoDB テーブル内のデータにクエリを実行](getting-started-step-5.md)」に進みます。

# ステップ 5: DynamoDB テーブル内のデータにクエリを実行
<a name="getting-started-step-5"></a>

このステップでは、`Music` を指定して [ステップ 2: DynamoDB テーブルにデータを書き込む](getting-started-step-2.md) の `Artist` テーブルに書き込んだデータをクエリします。これにより、パーティションキー `Artist` に関連付けられているすべての曲が表示されます。

クエリオペレーションの詳細については、「[DynamoDB のテーブルに対するクエリの実行](Query.md)」を参照してください。

## AWS マネジメントコンソール
<a name="getting-started-step-5-Console"></a>

DynamoDB コンソールを使用して `Music` テーブルのデータをクエリするには、次のステップに従います。

1. DynamoDB コンソール ([https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)) を開きます。

1. 左のナビゲーションペインで、**[テーブル]** を選択します。

1. テーブルのリストから **[Music]** テーブルを選択します。

1. **[テーブルアイテムの探索]** を選択します。

1. **[項目のスキャンまたはクエリ]** で、**[クエリ]** が選択されていることを確認します。

1. [**パーティションキー**] に「**Acme Band**」と入力し、[**実行**] を選択します。

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

次の AWS CLI の例では、`Music` テーブルの項目にクエリを実行します。この操作は、DynamoDB API または [PartiQL](https://docs.aws.amazon.com/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.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.select.html)」を参照してください。

------

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

次のコード例は、AWS SDK を使用して DynamoDB テーブルに対してクエリを実行する方法を示しています。

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

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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

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

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

            var search = movieTable.Query(config);
            do
            {
                var movieList = await search.GetNextSetAsync();
                moviesFound += movieList.Count;

                foreach (var movie in movieList)
                {
                    DisplayDocument(movie);
                }
            }
            while (!search.IsDone);

            return moviesFound;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return 0;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while querying movies. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while querying movies. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「**AWS SDK for .NET API リファレンス」の「[Query](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/Query)」を参照してください。

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

**Bash スクリプトを使用した AWS CLI**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
#############################################################################
# function dynamodb_query
#
# This function queries a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k key_condition_expression -- The key condition expression.
#       -a attribute_names -- Path to JSON file containing the attribute names.
#       -v attribute_values -- Path to JSON file containing the attribute values.
#       [-p projection_expression]  -- Optional projection expression.
#
#  Returns:
#       The items as json output.
#  And:
#       0 - If successful.
#       1 - If it fails.
###########################################################################
function dynamodb_query() {
  local table_name key_condition_expression attribute_names attribute_values projection_expression response
  local option OPTARG # Required to use getopts command in a function.

  # ######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_query"
    echo "Query a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k key_condition_expression -- The key condition expression."
    echo " -a attribute_names -- Path to JSON file containing the attribute names."
    echo " -v attribute_values -- Path to JSON file containing the attribute values."
    echo " [-p projection_expression]  -- Optional projection expression."
    echo ""
  }

  while getopts "n:k:a:v:p:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) key_condition_expression="${OPTARG}" ;;
      a) attribute_names="${OPTARG}" ;;
      v) attribute_values="${OPTARG}" ;;
      p) projection_expression="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$key_condition_expression" ]]; then
    errecho "ERROR: You must provide a key condition expression with the -k parameter."
    usage
    return 1
  fi

  if [[ -z "$attribute_names" ]]; then
    errecho "ERROR: You must provide a attribute names with the -a parameter."
    usage
    return 1
  fi

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

  if [[ -z "$projection_expression" ]]; then
    response=$(aws dynamodb query \
      --table-name "$table_name" \
      --key-condition-expression "$key_condition_expression" \
      --expression-attribute-names file://"$attribute_names" \
      --expression-attribute-values file://"$attribute_values")
  else
    response=$(aws dynamodb query \
      --table-name "$table_name" \
      --key-condition-expression "$key_condition_expression" \
      --expression-attribute-names file://"$attribute_names" \
      --expression-attribute-values file://"$attribute_values" \
      --projection-expression "$projection_expression")
  fi

  local error_code=${?}

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

  echo "$response"

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 の詳細については、**「AWS CLI コマンドリファレンス」の「[Query](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/Query)」を参照してください。

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

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
//! Perform a query on an Amazon DynamoDB Table and retrieve items.
/*!
  \sa queryItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param projectionExpression: The projections expression, which is ignored if empty.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
  */

/*
 * The partition key attribute is searched with the specified value. By default, all fields and values
 * contained in the item are returned. If an optional projection expression is
 * specified on the command line, only the specified fields and values are
 * returned.
 */

bool AwsDoc::DynamoDB::queryItems(const Aws::String &tableName,
                                  const Aws::String &partitionKey,
                                  const Aws::String &partitionValue,
                                  const Aws::String &projectionExpression,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);
    Aws::DynamoDB::Model::QueryRequest request;

    request.SetTableName(tableName);

    if (!projectionExpression.empty()) {
        request.SetProjectionExpression(projectionExpression);
    }

    // Set query key condition expression.
    request.SetKeyConditionExpression(partitionKey + "= :valueToMatch");

    // Set Expression AttributeValues.
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> attributeValues;
    attributeValues.emplace(":valueToMatch", partitionValue);

    request.SetExpressionAttributeValues(attributeValues);

    bool result = true;

    // "exclusiveStartKey" is used for pagination.
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> exclusiveStartKey;
    do {
        if (!exclusiveStartKey.empty()) {
            request.SetExclusiveStartKey(exclusiveStartKey);
            exclusiveStartKey.clear();
        }
        // Perform Query operation.
        const Aws::DynamoDB::Model::QueryOutcome &outcome = dynamoClient.Query(request);
        if (outcome.IsSuccess()) {
            // Reference the retrieved items.
            const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>> &items = outcome.GetResult().GetItems();
            if (!items.empty()) {
                std::cout << "Number of items retrieved from Query: " << items.size()
                          << std::endl;
                // Iterate each item and print.
                for (const auto &item: items) {
                    std::cout
                            << "******************************************************"
                            << std::endl;
                    // Output each retrieved field and its value.
                    for (const auto &i: item)
                        std::cout << i.first << ": " << i.second.GetS() << std::endl;
                }
            }
            else {
                std::cout << "No item found in table: " << tableName << std::endl;
            }

            exclusiveStartKey = outcome.GetResult().GetLastEvaluatedKey();
        }
        else {
            std::cerr << "Failed to Query items: " << outcome.GetError().GetMessage();
            result = false;
            break;
        }
    } while (!exclusiveStartKey.empty());

    return result;
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[Query](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/Query)」を参照してください。**

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

**AWS CLI**  
**例 1: テーブルにクエリを実行するには**  
次の `query` の例では、`MusicCollection` テーブルの項目にクエリを実行します。テーブルにはハッシュおよび範囲プライマリキー (`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.aws.amazon.com/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.aws.amazon.com/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.aws.amazon.com/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.aws.amazon.com/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.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Query](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/query.html)」を参照してください。

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

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// Query gets all movies in the DynamoDB table that were released in the specified year.
// The function uses the `expression` package to build the key condition expression
// that is used in the query.
func (basics TableBasics) Query(ctx context.Context, releaseYear int) ([]Movie, error) {
	var err error
	var response *dynamodb.QueryOutput
	var movies []Movie
	keyEx := expression.Key("year").Equal(expression.Value(releaseYear))
	expr, err := expression.NewBuilder().WithKeyCondition(keyEx).Build()
	if err != nil {
		log.Printf("Couldn't build expression for query. Here's why: %v\n", err)
	} else {
		queryPaginator := dynamodb.NewQueryPaginator(basics.DynamoDbClient, &dynamodb.QueryInput{
			TableName:                 aws.String(basics.TableName),
			ExpressionAttributeNames:  expr.Names(),
			ExpressionAttributeValues: expr.Values(),
			KeyConditionExpression:    expr.KeyCondition(),
		})
		for queryPaginator.HasMorePages() {
			response, err = queryPaginator.NextPage(ctx)
			if err != nil {
				log.Printf("Couldn't query for movies released in %v. Here's why: %v\n", releaseYear, err)
				break
			} else {
				var moviePage []Movie
				err = attributevalue.UnmarshalListOfMaps(response.Items, &moviePage)
				if err != nil {
					log.Printf("Couldn't unmarshal query response. Here's why: %v\n", err)
					break
				} else {
					movies = append(movies, moviePage...)
				}
			}
		}
	}
	return movies, err
}
```
この例で使用している Movie struct を定義します。  

```
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 の詳細については、*AWS SDK for Go API リファレンス*の「[Query](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.Query)」を参照してください。

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

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
[DynamoDbClient](https://docs.aws.amazon.com/sdk-for-java/latest/reference/software/amazon/awssdk/services/dynamodb/DynamoDbClient.html) を使用してテーブルに対してクエリを実行します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import java.util.HashMap;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 * To query items from an Amazon DynamoDB table using the AWS SDK for Java V2,
 * its better practice to use the
 * Enhanced Client. See the EnhancedQueryRecords example.
 */
public class Query {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <partitionKeyName> <partitionKeyVal>

                Where:
                    tableName - The Amazon DynamoDB table to put the item in (for example, Music3).
                    partitionKeyName - The partition key name of the Amazon DynamoDB table (for example, Artist).
                    partitionKeyVal - The value of the partition key that should match (for example, Famous Band).
                """;

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

        String tableName = args[0];
        String partitionKeyName = args[1];
        String partitionKeyVal = args[2];

        // For more information about an alias, see:
        // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html
        String partitionAlias = "#a";

        System.out.format("Querying %s", tableName);
        System.out.println("");
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        int count = queryTable(ddb, tableName, partitionKeyName, partitionKeyVal, partitionAlias);
        System.out.println("There were " + count + "  record(s) returned");
        ddb.close();
    }

    public static int queryTable(DynamoDbClient ddb, String tableName, String partitionKeyName, String partitionKeyVal,
            String partitionAlias) {
        // Set up an alias for the partition key name in case it's a reserved word.
        HashMap<String, String> attrNameAlias = new HashMap<String, String>();
        attrNameAlias.put(partitionAlias, partitionKeyName);

        // Set up mapping of the partition name with the value.
        HashMap<String, AttributeValue> attrValues = new HashMap<>();
        attrValues.put(":" + partitionKeyName, AttributeValue.builder()
                .s(partitionKeyVal)
                .build());

        QueryRequest queryReq = QueryRequest.builder()
                .tableName(tableName)
                .keyConditionExpression(partitionAlias + " = :" + partitionKeyName)
                .expressionAttributeNames(attrNameAlias)
                .expressionAttributeValues(attrValues)
                .build();

        try {
            QueryResponse response = ddb.query(queryReq);
            return response.count();

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return -1;
    }
}
```
`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 の詳細については、AWS SDK for Java 2.x API リファレンスの「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。**

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

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[QueryCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/QueryCommand/)」を参照してください。  

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

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

export const main = async () => {
  const command = new QueryCommand({
    TableName: "CoffeeCrop",
    KeyConditionExpression:
      "OriginCountry = :originCountry AND RoastDate > :roastDate",
    ExpressionAttributeValues: {
      ":originCountry": "Ethiopia",
      ":roastDate": "2023-05-01",
    },
    ConsistentRead: true,
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

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

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

var params = {
  ExpressionAttributeValues: {
    ":s": 2,
    ":e": 9,
    ":topic": "PHRASE",
  },
  KeyConditionExpression: "Season = :s and Episode > :e",
  FilterExpression: "contains (Subtitle, :topic)",
  TableName: "EPISODES_TABLE",
};

docClient.query(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Items);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying)」を参照してください。
+  API の詳細については、[AWS SDK for JavaScript API リファレンス](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/Query)の「*Query*」を参照してください。

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

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
suspend fun queryDynTable(
    tableNameVal: String,
    partitionKeyName: String,
    partitionKeyVal: String,
    partitionAlias: String,
): Int {
    val attrNameAlias = mutableMapOf<String, String>()
    attrNameAlias[partitionAlias] = partitionKeyName

    // Set up mapping of the partition name with the value.
    val attrValues = mutableMapOf<String, AttributeValue>()
    attrValues[":$partitionKeyName"] = AttributeValue.S(partitionKeyVal)

    val request =
        QueryRequest {
            tableName = tableNameVal
            keyConditionExpression = "$partitionAlias = :$partitionKeyName"
            expressionAttributeNames = attrNameAlias
            this.expressionAttributeValues = attrValues
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val response = ddb.query(request)
        return response.count
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[Query](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コードサンプルリポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
        $birthKey = [
            'Key' => [
                'year' => [
                    'N' => "$birthYear",
                ],
            ],
        ];
        $result = $service->query($tableName, $birthKey);

    public function query(string $tableName, $key)
    {
        $expressionAttributeValues = [];
        $expressionAttributeNames = [];
        $keyConditionExpression = "";
        $index = 1;
        foreach ($key as $name => $value) {
            $keyConditionExpression .= "#" . array_key_first($value) . " = :v$index,";
            $expressionAttributeNames["#" . array_key_first($value)] = array_key_first($value);
            $hold = array_pop($value);
            $expressionAttributeValues[":v$index"] = [
                array_key_first($hold) => array_pop($hold),
            ];
        }
        $keyConditionExpression = substr($keyConditionExpression, 0, -1);
        $query = [
            'ExpressionAttributeValues' => $expressionAttributeValues,
            'ExpressionAttributeNames' => $expressionAttributeNames,
            'KeyConditionExpression' => $keyConditionExpression,
            'TableName' => $tableName,
        ];
        return $this->dynamoDbClient->query($query);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[Query](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/Query)」を参照してください。**

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

**Tools for 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 の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Query](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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 の詳細については、「*AWS Tools for PowerShell Cmdlet リファレンス (V5)*」の「[Query](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。
キー条件式を使用して項目に対してクエリを実行します。  

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

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

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


    def 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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

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

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamo_resource.table(table_name)
  end

  # Queries for movies that were released in the specified year.
  #
  # @param year [Integer] The year to query.
  # @return [Array] The list of movies that were released in the specified year.
  def query_items(year)
    response = @table.query(
      key_condition_expression: '#yr = :year',
      expression_attribute_names: { '#yr' => 'year' },
      expression_attribute_values: { ':year' => year }
    )
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't query for movies released in #{year}. Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  else
    response.items
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[Query](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/Query)」を参照してください。**

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

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](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 の詳細については、「*AWS SDK for Rust API リファレンス*」の「[Query](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.query)」を参照してください。

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

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
    TRY.
        " Query movies for a given year .
        DATA(lt_attributelist) = VALUE /aws1/cl_dynattributevalue=>tt_attributevaluelist(
            ( NEW /aws1/cl_dynattributevalue( iv_n = |{ iv_year }| ) ) ).
        DATA(lt_key_conditions) = VALUE /aws1/cl_dyncondition=>tt_keyconditions(
          ( VALUE /aws1/cl_dyncondition=>ts_keyconditions_maprow(
          key = 'year'
          value = NEW /aws1/cl_dyncondition(
          it_attributevaluelist = lt_attributelist
          iv_comparisonoperator = |EQ|
          ) ) ) ).
        oo_result = lo_dyn->query(
          iv_tablename = iv_table_name
          it_keyconditions = lt_key_conditions ).
        DATA(lt_items) = oo_result->get_items( ).
        "You can loop over the results to get item attributes.
        LOOP AT lt_items INTO DATA(lt_item).
          DATA(lo_title) = lt_item[ key = 'title' ]-value.
          DATA(lo_year) = lt_item[ key = 'year' ]-value.
        ENDLOOP.
        DATA(lv_count) = oo_result->get_count( ).
        MESSAGE 'Item count is: ' && lv_count TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[Query](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

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

**SDK for Swift**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
import AWSDynamoDB


    /// Get all the movies released in the specified year.
    ///
    /// - Parameter year: The release year of the movies to return.
    ///
    /// - Returns: An array of `Movie` objects describing each matching movie.
    ///
    func getMovies(fromYear year: Int) async throws -> [Movie] {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = QueryInput(
                expressionAttributeNames: [
                    "#y": "year"
                ],
                expressionAttributeValues: [
                    ":y": .n(String(year))
                ],
                keyConditionExpression: "#y = :y",
                tableName: self.tableName
            )
            // Use "Paginated" to get all the movies.
            // This lets the SDK handle the 'lastEvaluatedKey' property in "QueryOutput".

            let pages = client.queryPaginated(input: input)

            var movieList: [Movie] = []
            for try await page in pages {
                guard let items = page.items else {
                    print("Error: no items returned.")
                    continue
                }

                // Convert the found movies into `Movie` objects and return an array
                // of them.

                for item in items {
                    let movie = try Movie(withItem: item)
                    movieList.append(movie)
                }
            }
            return movieList
        } catch {
            print("ERROR: getMovies:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[Query](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/query(input:))」を参照してください。

------

DynamoDB のその他の例については、「[AWS 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 コンソールまたは AWS CLI を使用して、[ステップ 1: DynamoDB にテーブルを作成する](getting-started-step-1.md) で作成した `Music` テーブルを削除することができます。

DynamoDB のテーブルオペレーションの詳細については、「[DynamoDB でのテーブルとデータの操作](WorkingWithTables.md)」を参照してください。

## AWS マネジメントコンソール
<a name="getting-started-step-8-Console"></a>

コンソールを使用して `Music` テーブルを削除するには:

1. DynamoDB コンソール ([https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)) を開きます。

1. 左のナビゲーションペインで、**[テーブル]** を選択します。

1. テーブルリストで、**[Music]** テーブルの横のチェックボックスをオンにします。

1. **[削除]** を選択します。

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

以下の AWS CLI の例では、`Music` を使用して `delete-table` テーブルを削除します。

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

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

次のコード例は、AWS SDK を使用して DynamoDB テーブルを削除する方法を示しています。

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

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
    /// <summary>
    /// Deletes a DynamoDB table.
    /// </summary>
    /// <param name="tableName">The name of the table to delete.</param>
    /// <returns>A Boolean value indicating the success of the operation.</returns>
    public async Task<bool> DeleteTableAsync(string tableName)
    {
        try
        {
            var request = new DeleteTableRequest
            {
                TableName = tableName,
            };

            var response = await _amazonDynamoDB.DeleteTableAsync(request);

            Console.WriteLine($"Table {response.TableDescription.TableName} successfully deleted.");
            return true;

        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found and cannot be deleted. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while deleting table {tableName}. {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting table {tableName}. {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、「**AWS SDK for .NET API リファレンス」の「[DeleteTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/DeleteTable)」を参照してください。

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

**Bash スクリプトを使用した AWS CLI**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
###############################################################################
# function dynamodb_delete_table
#
# This function deletes a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table to delete.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function dynamodb_delete_table() {
  local table_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function dynamodb_delete_table"
    echo "Deletes an Amazon DynamoDB table."
    echo " -n table_name  -- The name of the table to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

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

  response=$(aws dynamodb delete-table \
    --table-name "$table_name")

  local error_code=${?}

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

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 の詳細については、**「AWS CLI コマンドリファレンス」の「[DeleteTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteTable)」を参照してください。

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

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
//! Delete an Amazon DynamoDB table.
/*!
  \sa deleteTable()
  \param tableName: The DynamoDB table name.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::deleteTable(const Aws::String &tableName,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DeleteTableRequest request;
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::DeleteTableOutcome &result = dynamoClient.DeleteTable(
            request);
    if (result.IsSuccess()) {
        std::cout << "Your table \""
                  << result.GetResult().GetTableDescription().GetTableName()
                  << " was deleted.\n";
    }
    else {
        std::cerr << "Failed to delete table: " << result.GetError().GetMessage()
                  << std::endl;
    }

    return result.IsSuccess();
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[DeleteTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/DeleteTable)」を参照してください。

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

**AWS 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.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeleteTable)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/delete-table.html)」を参照してください。

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

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// DeleteTable deletes the DynamoDB table and all of its data.
func (basics TableBasics) DeleteTable(ctx context.Context) error {
	_, err := basics.DynamoDbClient.DeleteTable(ctx, &dynamodb.DeleteTableInput{
		TableName: aws.String(basics.TableName)})
	if err != nil {
		log.Printf("Couldn't delete table %v. Here's why: %v\n", basics.TableName, err)
	}
	return err
}
```
+  API の詳細については、『*AWS SDK for Go API リファレンス*』の「[DeleteTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.DeleteTable)」を参照してください。

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

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class DeleteTable {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName>

                Where:
                    tableName - The Amazon DynamoDB table to delete (for example, Music3).

                **Warning** This program will delete the table that you specify!
                """;

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

        String tableName = args[0];
        System.out.format("Deleting the Amazon DynamoDB table %s...\n", tableName);
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        deleteDynamoDBTable(ddb, tableName);
        ddb.close();
    }

    public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {
        DeleteTableRequest request = DeleteTableRequest.builder()
                .tableName(tableName)
                .build();

        try {
            ddb.deleteTable(request);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println(tableName + " was successfully deleted!");
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス* の「[DeleteTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DeleteTable)」を参照してください。

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

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

const client = new DynamoDBClient({});

export const main = async () => {
  const command = new DeleteTableCommand({
    TableName: "DecafCoffees",
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DeleteTableCommand)」を参照してください。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

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

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: process.argv[2],
};

// Call DynamoDB to delete the specified table
ddb.deleteTable(params, function (err, data) {
  if (err && err.code === "ResourceNotFoundException") {
    console.log("Error: Table not found");
  } else if (err && err.code === "ResourceInUseException") {
    console.log("Error: Table in use");
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-deleting-a-table)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteTable](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/DeleteTable)」を参照してください。

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

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
suspend fun deleteDynamoDBTable(tableNameVal: String) {
    val request =
        DeleteTableRequest {
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.deleteTable(request)
        println("$tableNameVal was deleted")
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[DeleteTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コードサンプルリポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
    public function deleteTable(string $TableName)
    {
        $this->customWaiter(function () use ($TableName) {
            return $this->dynamoDbClient->deleteTable([
                'TableName' => $TableName,
            ]);
        });
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/DeleteTable)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: 指定されたテーブルを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-DDBTable -TableName "myTable"
```
**例 2: 指定されたテーブルを削除します。操作を続行する前に確認画面は表示されません。**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteTable](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: 指定されたテーブルを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-DDBTable -TableName "myTable"
```
**例 2: 指定されたテーブルを削除します。操作を続行する前に確認画面は表示されません。**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet リファレンス (V5)*」の「[DeleteTable](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

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


    def delete_table(self):
        """
        Deletes the table.
        """
        try:
            self.table.delete()
            self.table = None
        except ClientError as err:
            logger.error(
                "Couldn't delete table. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[DeleteTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DeleteTable)」を参照してください。

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

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

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

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

  # Deletes the table.
  def delete_table
    @table.delete
    @table = nil
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't delete table. Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス* の「[DeleteTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/DeleteTable)」を参照してください。

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

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
pub async fn delete_table(client: &Client, table: &str) -> Result<DeleteTableOutput, Error> {
    let resp = client.delete_table().table_name(table).send().await;

    match resp {
        Ok(out) => {
            println!("Deleted table");
            Ok(out)
        }
        Err(e) => Err(Error::Unhandled(e.into())),
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.delete_table)」を参照してください。

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

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
    TRY.
        lo_dyn->deletetable( iv_tablename = iv_table_name ).
        " Wait till the table is actually deleted.
        lo_dyn->get_waiter( )->tablenotexists(
          iv_max_wait_time = 200
          iv_tablename     = iv_table_name ).
        MESSAGE 'Table ' && iv_table_name && ' deleted.' TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table ' && iv_table_name && ' does not exist' TYPE 'E'.
      CATCH /aws1/cx_dynresourceinuseex.
        MESSAGE 'The table cannot be deleted since it is in use' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

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

**SDK for Swift**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
import AWSDynamoDB


    ///
    /// Deletes the table from Amazon DynamoDB.
    ///
    func deleteTable() async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = DeleteTableInput(
                tableName: self.tableName
            )
            _ = try await client.deleteTable(input: input)
        } catch {
            print("ERROR: deleteTable:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[DeleteTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/deletetable(input:))」を参照してください。

------

DynamoDB のその他の例については、「[AWS 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 と AWS SDK を使用したプログラミング](Programming.md)

# Console-to-Code を使用して Amazon DynamoDB のインフラストラクチャコードを生成する
<a name="console-to-code"></a>

Amazon Q Developer の Console-to-Code 機能は、手動でのテーブル作成の手順を再現可能なオートメーションコードに変換することで、Amazon DynamoDB のインフラストラクチャ管理を簡素化します。この機能は、開発者がデータベースリソース設定を環境全体で効率的にスケールするのに役立ちます。詳細については、「[Amazon Q Developer Console-to-Code での AWS のサービスの自動化](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/console-to-code.html)」を参照してください。

Console-to-Code は、パーティションキー、ソートキー、プロビジョニングされたスループット設定、セカンダリインデックスなど、詳細な DynamoDB テーブル設定をキャプチャし、正確な infrastructure-as-code テンプレートに変換します。生成 AI を使用すると、ツールは生成されたコードがコンソールワークフロー中に確立されたパラメータの互換性を維持するようにします。

開発者は、次のような複数の形式で DynamoDB インフラストラクチャコードを生成できます。
+ TypeScript、Python、Java の AWS Cloud Development Kit (AWS CDK)
+ YAML または JSON の CloudFormation

このアプローチにより、チームは次のことが可能になります。
+ データベースリソース管理を標準化する
+ バージョン管理下のインフラストラクチャを実装する
+ 手動設定のエラーを減らす

Amazon DynamoDB の Console-to-Code は、すべての商用 AWS リージョンで利用可能で、手動設定を自動化された再現可能なインフラストラクチャコードに変換するための強力なソリューションを提供します。

## 仕組み
<a name="how-it-works"></a>

DynamoDB で Console-to-Code を使用する場合、通常、プロセスには次が含まれます。

1. **コンソールでのプロトタイプ作成** - DynamoDB コンソールを使用して、テーブルなどのリソースを作成し、設定します。詳細については、「[Amazon DynamoDB に接続する](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStartedDynamoDB.html)」を参照してください。

1. **アクションの記録** - Console-to-Code は、実行するときにこれらのアクションを記録します。

1. **コードの生成** - この機能は Amazon Q Developer の生成 AI 機能を使用して、コンソールアクションを任意の形式で再利用可能なコードに変換します。

1. **コードのカスタマイズ** - その後、このコードをコピーまたはダウンロードし、本番稼働用ワークロードに合わせてさらにカスタマイズできます。

## DynamoDB で Console-to-Code を使用する利点
<a name="benefits"></a>

**オートメーションの簡素化**  
手動の DynamoDB テーブルの作成と設定を、ワンクリックで再利用可能なコードに変換します。

**ベストプラクティス**  
生成されたコードは、AWS ガイドの信頼性の高いデプロイのベストプラクティスに従います。

**コンソールとコード間のブリッジ**  
AWS マネジメントコンソール または Infrastructure-as-Code (IaC) のどちらを使用するかを選択する必要はありません。両方のアプローチを一緒に使用できます。

**開発の加速**  
本番稼働環境用にさらにカスタマイズできるオートメーションコードをすぐに使用開始できます。

## ユースケースの例
<a name="example-use-cases"></a>
+ 特定の属性、キー、容量設定を使用した DynamoDB テーブルの作成
+ グローバルセカンダリインデックスとローカルセカンダリインデックスの設定
+ DynamoDB テーブルの自動スケーリングポリシーの設定
+ バックアップと復元の設定の確立
+ DynamoDB ストリームの作成と管理

## 開始方法
<a name="getting-started"></a>

DynamoDB で Console-to-Code の使用を開始するには。

1. AWS マネジメントコンソールにサインインして DynamoDB コンソール ([https://console.aws.amazon.com/dynamodbv2/](https://console.aws.amazon.com/dynamodbv2/)) を開きます。

1. コンソールインターフェイスを使用して DynamoDB リソースの作成または変更を開始します。

1. Console-to-Code 機能を使用して、任意の形式でアクションのコードを生成します。

1. 生成されたコードをコピーまたはダウンロードし、特定の要件に応じて必要に応じてカスタマイズします。

Console-to-Code の使用方法に関する詳細と手順については、「*Amazon Q Developer ユーザーガイド*」の「[Amazon Q Developer Console-to-Code を使用した AWS のサービスの自動化](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/console-to-code.html)」を参照してください。