DynamoDB에서 테이블 작업 - AWS SDK for C++

DynamoDB에서 테이블 작업

테이블은 DynamoDB 데이터베이스 내 모든 항목을 위한 컨테이너입니다. DynamoDB에 데이터를 추가하거나 제거하기 전에 테이블을 생성해야 합니다.

각 테이블마다 다음을 정의해야 합니다.

  • AWS 계정 및 AWS 리전에 고유한 테이블 이름

  • 프라이머리 키(모든 값이 고유해야 함). 테이블 내 두 항목은 동일한 프라이머리 키 값을 사용할 수 없습니다.

    기본 키는 단일 파티션(HASH) 키로 이루어진 단순형이거나, 파티션과 정렬(RANGE) 키로 이루어진 복합형일 수 있습니다.

    각 키 값에는 ScalarAttributeType 클래스에 의해 열거되는 관련 데이터 유형이 있습니다. 키 값은 이진(B), 숫자(N) 또는 문자열(S)일 수 있습니다. 자세한 내용은 Amazon DynamoDB 개발자 안내서에서 이름 지정 규칙 및 데이터 형식을 참조하세요.

  • 테이블에 대해 예약된 읽기/쓰기 용량 단위를 정의하는 프로비저닝된 처리량

    참고

    Amazon DynamoDB 요금은 테이블에 대해 설정하는 프로비저닝된 처리량 값을 기준으로 하므로 테이블에 대해 필요한 만큼의 용량만 예약하십시오.

    언제라도 테이블의 프로비저닝된 처리량을 수정할 수 있으므로 변경이 필요할 경우 용량을 조정할 수 있습니다.

테이블 생성

새 DynamoDB 테이블을 생성하려면 DynamoDB 클라이언트CreateTable 메서드를 사용합니다. 테이블 속성과 테이블 스키마를 구성해야 하며, 이 두 가지 요소 모두 테이블의 기본 키를 식별하는 데 사용됩니다. 초기 프로비저닝 처리량 값과 테이블 이름을 제공해야 합니다. CreateTable은 비동기식 작업입니다. 테이블이 ACTIVE 상태가 되어 사용 준비가 될 때까지 GetTableStatus는 CREATING 상태를 반환합니다.

단순형 기본 키를 사용하여 테이블 생성

이 코드는 단순형 기본 키("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); }

전체 예제를 참조하세요.

복합형 기본 키를 사용하여 테이블 생성

다른 AttributeDefinitionKeySchemaElementCreateTableRequest에 추가합니다.

포함 파일

#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 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에서 확인하세요.

테이블 나열

DynamoDB 클라이언트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; }

기본적으로 호출당 최대 100개의 테이블이 반환됩니다. 반환된 ListTablesOutcome 객체에 GetExclusiveStartTableName을 사용하면 마지막으로 평가된 테이블을 가져올 수 있습니다. 이 값을 사용하여 이전 목록의 마지막으로 반환된 값 다음에 이어지는 목록을 시작할 수 있습니다.

전체 예제를 참조하세요.

테이블 정보 검색

테이블에 대한 자세한 정보는 DynamoDB 클라이언트DescribeTable 메서드를 호출하여 확인할 수 있습니다.

포함 파일

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

코드

//! 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에서 확인하세요.

테이블 수정

DynamoDB 클라이언트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); }

전체 예제를 참조하세요.

테이블 삭제

DynamoDB 클라이언트DeleteTable 메서드를 호출하고 테이블 이름을 이 메서드에 전달합니다.

포함 파일

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

코드

//! 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에서 확인하세요.

추가 정보