

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# を使用した Amazon DynamoDB の例 AWS SDK for C\$1\$1
<a name="examples-dynamodb"></a>

Amazon DynamoDB は、フルマネージド NoSQL データベースサービスであり、シームレスなスケーラビリティを備えた高速で予測可能なパフォーマンスを提供します。以下の例では、 AWS SDK for C\$1\$1を使用して [Amazon DynamoDB](https://aws.amazon.com/dynamodb) をプログラミングする方法を示しています。

**注記**  
このガイドには、特定の手法を示すために必要最低限のコードのみを掲載していますが、[完全なコード例は GitHub で入手できます](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp)。GitHub では、ソースファイル単体をダウンロードすることも、リポジトリをローカルにクローンして、すべての例を取得、ビルド、実行することもできます。

**Topics**
+ [DynamoDB でのテーブルの使用](examples-dynamodb-tables.md)
+ [DynamoDB での項目の使用](examples-dynamodb-items.md)

# DynamoDB でのテーブルの使用
<a name="examples-dynamodb-tables"></a>

テーブルは、DynamoDB データベースのすべての項目のコンテナです。DynamoDB のデータの追加または削除を行う前に、テーブルを作成する必要があります。

テーブルごとに、以下を定義する必要があります。
+  AWS アカウント と に固有のテーブル*名* AWS リージョン。
+ すべての値が一意である必要のある*プライマリキー*。同じテーブル内でプライマリキーが重複する項目は存在できません。

  プライマリキーは、単一のパーティション (ハッシュ) キーで構成される*シンプル*なプライマリキーにするか、パーティションとソート (範囲) キーで構成される*複合*プライマリキーにすることができます。

  各キーバリューには、[ScalarAttributeType](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/namespace_aws_1_1_dynamo_d_b_1_1_model.html#a4b39ae66214e022d3737079d071e4bcb.html) クラスによって列挙される*データ型*が関連付けられています。キー値は、バイナリ (B)、数値 (N)、または文字列 (S) になります。詳細については、「Amazon DynamoDB デベロッパーガイド」の「[命名規則とデータ型](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html)」を参照してください。
+  テーブル用に予約された読み込み/書き込みキャパシティーユニットの数を定義する*プロビジョニングされたスループット*の値。
**注記**  
 [Amazon DynamoDB の料金表](https://aws.amazon.com/dynamodb/pricing/)は、テーブルに設定したプロビジョニングされたスループット値に基づくため、テーブルに必要と予想される分だけのキャパシティーを予約します。  
テーブルのプロビジョニングされたスループットはいつでも変更できるため、必要に応じてキャパシティーを調整できます。

## テーブルを作成する
<a name="dynamodb-create-table"></a>

新しい DynamoDB テーブルを作成するには、[DynamoDB クライアント](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)の `CreateTable` メソッドを使用します。テーブルのプライマリキーを識別するために使用する、テーブル属性とテーブルスキーマを構築する必要があります。また、初期プロビジョンドスループット値とテーブル名を指定する必要があります。`CreateTable` は非同期オペレーションです。`GetTableStatus` はテーブルの作成中は CREATING を返し、テーブルが使用可能になると ACTIVE を返します。

### シンプルプライマリキーを使用してテーブルを作成する
<a name="dynamodb-create-table-simple"></a>

このコードでは、シンプルプライマリキー (「Name」) を持つテーブルを作成します。

 **を含む** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/CreateTableRequest.h>
#include <aws/dynamodb/model/KeySchemaElement.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/ScalarAttributeType.h>
#include <iostream>
```

 **コード** 

```
//! 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);
}
```

[完全な例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/create_table.cpp)をご覧ください。

### 複合プライマリキーを使用してテーブルを作成する
<a name="dynamodb-create-table-composite"></a>

別の [AttributeDefinition](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_attribute_definition.html) および [KeySchemaElement](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_key_schema_element.html) を [CreateTableRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_create_table_request.html) に追加します。

 **を含む** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/CreateTableRequest.h>
#include <aws/dynamodb/model/KeySchemaElement.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/ScalarAttributeType.h>
#include <iostream>
```

 **Code** 

```
//! Create an Amazon DynamoDB table with a composite key.
/*!
  \sa createTableWithCompositeKey()
  \param tableName: Name for the DynamoDB table.
  \param partitionKey: Name for the partition (hash) key.
  \param sortKey: Name for the sort (range) key.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::createTableWithCompositeKey(const Aws::String &tableName,
                                                   const Aws::String &partitionKey,
                                                   const Aws::String &sortKey,
                                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::cout << "Creating table " << tableName <<
              " with a composite primary key:\n" \
            "* " << partitionKey << " - partition key\n" \
            "* " << sortKey << " - sort key\n";

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

    Aws::DynamoDB::Model::AttributeDefinition hashKey1, hashKey2;
    hashKey1.WithAttributeName(partitionKey).WithAttributeType(
            Aws::DynamoDB::Model::ScalarAttributeType::S);
    request.AddAttributeDefinitions(hashKey1);
    hashKey2.WithAttributeName(sortKey).WithAttributeType(
            Aws::DynamoDB::Model::ScalarAttributeType::S);
    request.AddAttributeDefinitions(hashKey2);

    Aws::DynamoDB::Model::KeySchemaElement keySchemaElement1, keySchemaElement2;
    keySchemaElement1.WithAttributeName(partitionKey).WithKeyType(
            Aws::DynamoDB::Model::KeyType::HASH);
    request.AddKeySchema(keySchemaElement1);
    keySchemaElement2.WithAttributeName(sortKey).WithKeyType(
            Aws::DynamoDB::Model::KeyType::RANGE);
    request.AddKeySchema(keySchemaElement2);

    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() <<
                  "\" was created!" << std::endl;
    }
    else {
        std::cerr << "Failed to create table:" << outcome.GetError().GetMessage()
                  << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/create_table_composite_key.cpp) で完全な例をご覧ください。

## テーブルの一覧表示
<a name="dynamodb-list-tables"></a>

特定のリージョン内のテーブルを一覧表示するには、[DynamoDB クライアント](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)の `ListTables` メソッドを呼び出します。

 **を含む** 

```
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/ListTablesRequest.h>
#include <aws/dynamodb/model/ListTablesResult.h>
#include <iostream>
```

 **コード** 

```
//! List the Amazon DynamoDB tables for the current AWS account.
/*!
  \sa listTables()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::DynamoDB::listTables(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::ListTablesRequest listTablesRequest;
    listTablesRequest.SetLimit(50);
    do {
        const Aws::DynamoDB::Model::ListTablesOutcome &outcome = dynamoClient.ListTables(
                listTablesRequest);
        if (!outcome.IsSuccess()) {
            std::cout << "Error: " << outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        for (const auto &tableName: outcome.GetResult().GetTableNames())
            std::cout << tableName << std::endl;
        listTablesRequest.SetExclusiveStartTableName(
                outcome.GetResult().GetLastEvaluatedTableName());

    } while (!listTablesRequest.GetExclusiveStartTableName().empty());

    return true;
}
```

デフォルトでは、1 回の呼び出しごとに最大 100 個のテーブルが返されます。返された [ListTablesOutcome](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html) オブジェクトに対して `GetExclusiveStartTableName` を使用して、最後に評価されたテーブルを取得します。この値を使用して、前回の一覧表示で返された最後の値以降から、一覧表示を開始できます。

[完全な例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/list_tables.cpp)をご覧ください。

## テーブルに関する情報を取得する
<a name="dynamodb-describe-table"></a>

[DynamoDB クライアント](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)の `DescribeTable` メソッドを呼び出すことで、テーブルの詳細を確認できます。

 **を含む** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/DescribeTableRequest.h>
#include <iostream>
```

 **Code** 

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

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

    const Aws::DynamoDB::Model::DescribeTableOutcome &outcome = dynamoClient.DescribeTable(
            request);

    if (outcome.IsSuccess()) {
        const Aws::DynamoDB::Model::TableDescription &td = outcome.GetResult().GetTable();
        std::cout << "Table name  : " << td.GetTableName() << std::endl;
        std::cout << "Table ARN   : " << td.GetTableArn() << std::endl;
        std::cout << "Status      : "
                  << Aws::DynamoDB::Model::TableStatusMapper::GetNameForTableStatus(
                          td.GetTableStatus()) << std::endl;
        std::cout << "Item count  : " << td.GetItemCount() << std::endl;
        std::cout << "Size (bytes): " << td.GetTableSizeBytes() << std::endl;

        const Aws::DynamoDB::Model::ProvisionedThroughputDescription &ptd = td.GetProvisionedThroughput();
        std::cout << "Throughput" << std::endl;
        std::cout << "  Read Capacity : " << ptd.GetReadCapacityUnits() << std::endl;
        std::cout << "  Write Capacity: " << ptd.GetWriteCapacityUnits() << std::endl;

        const Aws::Vector<Aws::DynamoDB::Model::AttributeDefinition> &ad = td.GetAttributeDefinitions();
        std::cout << "Attributes" << std::endl;
        for (const auto &a: ad)
            std::cout << "  " << a.GetAttributeName() << " (" <<
                      Aws::DynamoDB::Model::ScalarAttributeTypeMapper::GetNameForScalarAttributeType(
                              a.GetAttributeType()) <<
                      ")" << std::endl;
    }
    else {
        std::cerr << "Failed to describe table: " << outcome.GetError().GetMessage();
    }

    return outcome.IsSuccess();
}
```

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/describe_table.cpp) で完全な例をご覧ください。

## テーブルを変更する
<a name="dynamodb-update-table"></a>

[DynamoDB クライアント](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)の `UpdateTable` メソッドを呼び出すことで、テーブルのプロビジョンドスループット値を随時変更できます。

 **を含む** 

```
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/UpdateTableRequest.h>
#include <iostream>
```

 **コード** 

```
//! Update a DynamoDB table.
/*!
  \sa updateTable()
  \param tableName: Name for the DynamoDB table.
  \param readCapacity: Provisioned read capacity.
  \param writeCapacity: Provisioned write capacity.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::updateTable(const Aws::String &tableName,
                                   long long readCapacity, long long writeCapacity,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::cout << "Updating " << tableName << " with new provisioned throughput values"
              << std::endl;
    std::cout << "Read capacity : " << readCapacity << std::endl;
    std::cout << "Write capacity: " << writeCapacity << std::endl;

    Aws::DynamoDB::Model::UpdateTableRequest request;
    Aws::DynamoDB::Model::ProvisionedThroughput provisionedThroughput;
    provisionedThroughput.WithReadCapacityUnits(readCapacity).WithWriteCapacityUnits(
            writeCapacity);
    request.WithProvisionedThroughput(provisionedThroughput).WithTableName(tableName);

    const Aws::DynamoDB::Model::UpdateTableOutcome &outcome = dynamoClient.UpdateTable(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated the table." << std::endl;
    } else {
        const Aws::DynamoDB::DynamoDBError &error = outcome.GetError();
        if (error.GetErrorType() == Aws::DynamoDB::DynamoDBErrors::VALIDATION &&
            error.GetMessage().find("The provisioned throughput for the table will not change") != std::string::npos) {
            std::cout << "The provisioned throughput for the table will not change." << std::endl;
        } else {
            std::cerr << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }

    return waitTableActive(tableName, dynamoClient);
}
```

[完全な例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/update_table.cpp)をご覧ください。

## テーブルの削除
<a name="dynamodb-delete-table"></a>

[DynamoDB クライアント](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)の `DeleteTable` メソッドを呼び出し、それにテーブルの名前を渡します。

 **を含む** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/DeleteTableRequest.h>
#include <iostream>
```

 **Code** 

```
//! 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();
}
```

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/delete_table.cpp) で完全な例をご覧ください。

## 詳細情報
<a name="more-info"></a>
+  「Amazon DynamoDB デベロッパーガイド」の「[テーブルの使用に関するガイドライン](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html)」
+  「Amazon DynamoDB デベロッパーガイド」の「[DynamoDB でのテーブルの使用](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html)」

# DynamoDB での項目の使用
<a name="examples-dynamodb-items"></a>

DynamoDB では、項目とは *属性*の集合体です。各属性には*名前*と*値*があります。属性値はスカラー型、セット型、ドキュメント型のいずれかです。詳細については、「Amazon DynamoDB デベロッパーガイド」の「[命名規則とデータ型](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html)」を参照してください。

## テーブルから項目を取得する
<a name="dynamodb-get-item"></a>

[DynamoDB クライアント](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)の `GetItem` メソッドを呼び出します。取得する項目のテーブル名とプライマリキー値を含む [GetItemRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_get_item_request.html) オブジェクトをそのメソッドに渡します。[GetItemResult](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_get_item_result.html) オブジェクトが返されます。

返された `GetItemResult` オブジェクトの `GetItem()` メソッドを使用して、項目に関連付けられているキー `Aws::String` と値 [AttributeValue](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_attribute_value.html) のペアの `Aws::Map` を取得できます。

 **を含む** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/GetItemRequest.h>
#include <iostream>
```

 **Code** 

```
//! 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();
}
```

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/get_item.cpp) で完全な例をご覧ください。

## テーブルに項目を追加する
<a name="dynamodb-add-item"></a>

各項目を表すキー `Aws::String` と値 [AttributeValue](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_attribute_value.html) のペアを作成します。これらには、テーブルのプライマリキーフィールドの値を含める必要があります。プライマリキーで特定される項目がすでにある場合、フィールドはリクエストによって*更新*されます。`AddItem` メソッドを使用して、それらの項目を [PutItemRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_put_item_request.html) に追加します。

 **を含む** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/PutItemRequest.h>
#include <aws/dynamodb/model/PutItemResult.h>
#include <iostream>
```

 **Code** 

```
//! 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);
}
```

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/put_item.cpp) で完全な例をご覧ください。

## テーブルの既存の項目の更新
<a name="dynamodb-update-item"></a>

DynamoDBClient の `UpdateItem` メソッドを使用し、テーブル名、プライマリキー値、更新するフィールドとその対応する値を指定することで、テーブルに既に存在する項目の属性を更新できます。

 **インポート** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/UpdateItemRequest.h>
#include <aws/dynamodb/model/UpdateItemResult.h>
#include <iostream>
```

 **コード** 

```
//! 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);
}
```

[完全な例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/update_item.cpp)をご覧ください。

## 詳細情報
<a name="more-info"></a>
+  「Amazon DynamoDB デベロッパーガイド」の「[項目の使用に関するガイドライン](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForItems.html)」
+  「Amazon DynamoDB デベロッパーガイド」の「[DynamoDB での項目の使用](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html)」