搭CreateTable配 AWS 開發套件或 CLI 使用 - Amazon DynamoDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

CreateTable配 AWS 開發套件或 CLI 使用

下列程式碼範例會示範如何使用CreateTable

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Creates a new Amazon DynamoDB table and then waits for the new /// table to become active. /// </summary> /// <param name="client">An initialized Amazon DynamoDB client object.</param> /// <param name="tableName">The name of the table to create.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public static async Task<bool> CreateMovieTableAsync(AmazonDynamoDBClient client, string tableName) { var response = await client.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, }, }, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = 5, WriteCapacityUnits = 5, }, }); // 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 { System.Threading.Thread.Sleep(sleepDuration); var describeTableResponse = await client.DescribeTableAsync(request); status = describeTableResponse.Table.TableStatus; Console.Write("."); } while (status != "ACTIVE"); return status == TableStatus.ACTIVE; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考CreateTable中的。

Bash
AWS CLI 與 Bash 腳本
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

############################################################################### # 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. # -p provisioned_throughput -- Provisioned throughput settings for the table. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function dynamodb_create_table() { local table_name attribute_definitions key_schema provisioned_throughput 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." 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 " -p provisioned_throughput -- Provisioned throughput settings for the table." echo "" } # Retrieve the calling parameters. while getopts "n:a:k:p:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; a) attribute_definitions="${OPTARG}" ;; k) key_schema="${OPTARG}" ;; p) provisioned_throughput="${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 if [[ -z "$provisioned_throughput" ]]; then errecho "ERROR: You must provide a provisioned throughput json file path the -p parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " attribute_definitions: $attribute_definitions" iecho " key_schema: $key_schema" iecho " provisioned_throughput: $provisioned_throughput" iecho "" response=$(aws dynamodb create-table \ --table-name "$table_name" \ --attribute-definitions file://"$attribute_definitions" \ --key-schema file://"$key_schema" \ --provisioned-throughput "$provisioned_throughput") 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中的。

C++
適用於 C++ 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

//! 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 outcome.IsSuccess(); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for C++ API 參考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 開發人員指南中的表格的基本操作

範例 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 開發人員指南中的表格的基本操作

範例 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 開發人員指南中的表格的基本操作

範例 4:若要建立具有本機次要索引的資料表

下列範例會使用指定的屬性和索引鍵結構描述,建立名為 MusicCollection「本機次要索引」的資料表AlbumTitleIndex

aws dynamodb create-table \ --table-name MusicCollection \ --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S AttributeName=AlbumTitle,AttributeType=S \ --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \ --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \ --local-secondary-indexes \ "[ { \"IndexName\": \"AlbumTitleIndex\", \"KeySchema\": [ {\"AttributeName\": \"Artist\",\"KeyType\":\"HASH\"}, {\"AttributeName\": \"AlbumTitle\",\"KeyType\":\"RANGE\"} ], \"Projection\": { \"ProjectionType\": \"INCLUDE\", \"NonKeyAttributes\": [\"Genre\", \"Year\"] } } ]"

輸出:

{ "TableDescription": { "AttributeDefinitions": [ { "AttributeName": "AlbumTitle", "AttributeType": "S" }, { "AttributeName": "Artist", "AttributeType": "S" }, { "AttributeName": "SongTitle", "AttributeType": "S" } ], "TableName": "MusicCollection", "KeySchema": [ { "AttributeName": "Artist", "KeyType": "HASH" }, { "AttributeName": "SongTitle", "KeyType": "RANGE" } ], "TableStatus": "CREATING", "CreationDateTime": "2020-05-26T15:59:49.473000-07:00", "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "ReadCapacityUnits": 10, "WriteCapacityUnits": 5 }, "TableSizeBytes": 0, "ItemCount": 0, "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection", "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "LocalSecondaryIndexes": [ { "IndexName": "AlbumTitleIndex", "KeySchema": [ { "AttributeName": "Artist", "KeyType": "HASH" }, { "AttributeName": "AlbumTitle", "KeyType": "RANGE" } ], "Projection": { "ProjectionType": "INCLUDE", "NonKeyAttributes": [ "Genre", "Year" ] }, "IndexSizeBytes": 0, "ItemCount": 0, "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/index/AlbumTitleIndex" } ] } }

如需詳細資訊,請參閱 Amazon DynamoDB 開發人員指南中的表格的基本操作

範例 5:若要建立具有全域次要索引的資料表

下列範例會建立名GameScores為全域次要索引的資料表GameTitleIndex。基礎資料表具有分割區索引鍵 UserId 和排序索引鍵 GameTitle,可讓您有效率地找到個別使用者在特定遊戲中的最佳分數,而 GSI 具有分割區索引鍵 GameTitle 和排序索引鍵 TopScore,可讓您快速找到特定遊戲的整體最高分數。

aws dynamodb create-table \ --table-name GameScores \ --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S AttributeName=TopScore,AttributeType=N \ --key-schema AttributeName=UserId,KeyType=HASH \ AttributeName=GameTitle,KeyType=RANGE \ --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \ --global-secondary-indexes \ "[ { \"IndexName\": \"GameTitleIndex\", \"KeySchema\": [ {\"AttributeName\":\"GameTitle\",\"KeyType\":\"HASH\"}, {\"AttributeName\":\"TopScore\",\"KeyType\":\"RANGE\"} ], \"Projection\": { \"ProjectionType\":\"INCLUDE\", \"NonKeyAttributes\":[\"UserId\"] }, \"ProvisionedThroughput\": { \"ReadCapacityUnits\": 10, \"WriteCapacityUnits\": 5 } } ]"

輸出:

{ "TableDescription": { "AttributeDefinitions": [ { "AttributeName": "GameTitle", "AttributeType": "S" }, { "AttributeName": "TopScore", "AttributeType": "N" }, { "AttributeName": "UserId", "AttributeType": "S" } ], "TableName": "GameScores", "KeySchema": [ { "AttributeName": "UserId", "KeyType": "HASH" }, { "AttributeName": "GameTitle", "KeyType": "RANGE" } ], "TableStatus": "CREATING", "CreationDateTime": "2020-05-26T17:28:15.602000-07:00", "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "ReadCapacityUnits": 10, "WriteCapacityUnits": 5 }, "TableSizeBytes": 0, "ItemCount": 0, "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores", "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "GlobalSecondaryIndexes": [ { "IndexName": "GameTitleIndex", "KeySchema": [ { "AttributeName": "GameTitle", "KeyType": "HASH" }, { "AttributeName": "TopScore", "KeyType": "RANGE" } ], "Projection": { "ProjectionType": "INCLUDE", "NonKeyAttributes": [ "UserId" ] }, "IndexStatus": "CREATING", "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "ReadCapacityUnits": 10, "WriteCapacityUnits": 5 }, "IndexSizeBytes": 0, "ItemCount": 0, "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/index/GameTitleIndex" } ] } }

如需詳細資訊,請參閱 Amazon DynamoDB 開發人員指南中的表格的基本操作

範例 6:一次建立含有多個全域次要索引的表格

下列範例會建立一個以兩個全域次要索引命名GameScores的資料表。GSI 結構描述是透過檔案傳遞的,而不是透過命令列傳遞。

aws dynamodb create-table \ --table-name GameScores \ --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S AttributeName=TopScore,AttributeType=N AttributeName=Date,AttributeType=S \ --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \ --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \ --global-secondary-indexes file://gsi.json

gsi.json 的內容:

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

輸出:

{ "TableDescription": { "AttributeDefinitions": [ { "AttributeName": "Date", "AttributeType": "S" }, { "AttributeName": "GameTitle", "AttributeType": "S" }, { "AttributeName": "TopScore", "AttributeType": "N" }, { "AttributeName": "UserId", "AttributeType": "S" } ], "TableName": "GameScores", "KeySchema": [ { "AttributeName": "UserId", "KeyType": "HASH" }, { "AttributeName": "GameTitle", "KeyType": "RANGE" } ], "TableStatus": "CREATING", "CreationDateTime": "2020-08-04T16:40:55.524000-07:00", "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "ReadCapacityUnits": 10, "WriteCapacityUnits": 5 }, "TableSizeBytes": 0, "ItemCount": 0, "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores", "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "GlobalSecondaryIndexes": [ { "IndexName": "GameTitleIndex", "KeySchema": [ { "AttributeName": "GameTitle", "KeyType": "HASH" }, { "AttributeName": "TopScore", "KeyType": "RANGE" } ], "Projection": { "ProjectionType": "ALL" }, "IndexStatus": "CREATING", "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "ReadCapacityUnits": 10, "WriteCapacityUnits": 5 }, "IndexSizeBytes": 0, "ItemCount": 0, "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/index/GameTitleIndex" }, { "IndexName": "GameDateIndex", "KeySchema": [ { "AttributeName": "GameTitle", "KeyType": "HASH" }, { "AttributeName": "Date", "KeyType": "RANGE" } ], "Projection": { "ProjectionType": "ALL" }, "IndexStatus": "CREATING", "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "ReadCapacityUnits": 5, "WriteCapacityUnits": 5 }, "IndexSizeBytes": 0, "ItemCount": 0, "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/index/GameDateIndex" } ] } }

如需詳細資訊,請參閱 Amazon DynamoDB 開發人員指南中的表格的基本操作

範例 7:若要建立啟用「串流」的表格

下列範例會建立一個名為啟GameScores用 DynamoDB Streams 的資料表。每個項目的新舊圖像都將被寫入流中。

aws dynamodb create-table \ --table-name GameScores \ --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S \ --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \ --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \ --stream-specification StreamEnabled=TRUE,StreamViewType=NEW_AND_OLD_IMAGES

輸出:

{ "TableDescription": { "AttributeDefinitions": [ { "AttributeName": "GameTitle", "AttributeType": "S" }, { "AttributeName": "UserId", "AttributeType": "S" } ], "TableName": "GameScores", "KeySchema": [ { "AttributeName": "UserId", "KeyType": "HASH" }, { "AttributeName": "GameTitle", "KeyType": "RANGE" } ], "TableStatus": "CREATING", "CreationDateTime": "2020-05-27T10:49:34.056000-07:00", "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "ReadCapacityUnits": 10, "WriteCapacityUnits": 5 }, "TableSizeBytes": 0, "ItemCount": 0, "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores", "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "StreamSpecification": { "StreamEnabled": true, "StreamViewType": "NEW_AND_OLD_IMAGES" }, "LatestStreamLabel": "2020-05-27T17:49:34.056", "LatestStreamArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/stream/2020-05-27T17:49:34.056" } }

如需詳細資訊,請參閱 Amazon DynamoDB 開發人員指南中的表格的基本操作

範例 8:若要建立已啟用「僅限金鑰串流」的資料表

下列範例會建立一個名為啟GameScores用 DynamoDB Streams 的資料表。只有修改項目的索引鍵屬性會寫入資料流。

aws dynamodb create-table \ --table-name GameScores \ --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S \ --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \ --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \ --stream-specification StreamEnabled=TRUE,StreamViewType=KEYS_ONLY

輸出:

{ "TableDescription": { "AttributeDefinitions": [ { "AttributeName": "GameTitle", "AttributeType": "S" }, { "AttributeName": "UserId", "AttributeType": "S" } ], "TableName": "GameScores", "KeySchema": [ { "AttributeName": "UserId", "KeyType": "HASH" }, { "AttributeName": "GameTitle", "KeyType": "RANGE" } ], "TableStatus": "CREATING", "CreationDateTime": "2023-05-25T18:45:34.140000+00:00", "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "ReadCapacityUnits": 10, "WriteCapacityUnits": 5 }, "TableSizeBytes": 0, "ItemCount": 0, "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores", "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "StreamSpecification": { "StreamEnabled": true, "StreamViewType": "KEYS_ONLY" }, "LatestStreamLabel": "2023-05-25T18:45:34.140", "LatestStreamArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/stream/2023-05-25T18:45:34.140", "DeletionProtectionEnabled": false } }

如需詳細資訊,請參閱 Amazon DynamoDB 開發人員指南中的變更 DynamoDB 串流的資料擷取

範例 9:若要建立具有標準不常存取類別的資料表

下列範例會建立名為的資料表,GameScores並指派標準不常存取 (DynamoDB 標準 — IA) 表類別。此表類別針對主要成本的儲存進行了最佳化。

aws dynamodb create-table \ --table-name GameScores \ --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S \ --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \ --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \ --table-class STANDARD_INFREQUENT_ACCESS

輸出:

{ "TableDescription": { "AttributeDefinitions": [ { "AttributeName": "GameTitle", "AttributeType": "S" }, { "AttributeName": "UserId", "AttributeType": "S" } ], "TableName": "GameScores", "KeySchema": [ { "AttributeName": "UserId", "KeyType": "HASH" }, { "AttributeName": "GameTitle", "KeyType": "RANGE" } ], "TableStatus": "CREATING", "CreationDateTime": "2023-05-25T18:33:07.581000+00:00", "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "ReadCapacityUnits": 10, "WriteCapacityUnits": 5 }, "TableSizeBytes": 0, "ItemCount": 0, "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores", "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "TableClassSummary": { "TableClass": "STANDARD_INFREQUENT_ACCESS" }, "DeletionProtectionEnabled": false } }

如需詳細資訊,請參閱 Amazon DynamoDB 開發人員指南中的表格類別

範例 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 開發人員指南中的使用刪除保護

  • 如需 API 詳細資訊,請參閱AWS CLI 命令參考CreateTable中的。

Go
SDK for Go V2
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

// 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() (*types.TableDescription, error) { var tableDesc *types.TableDescription table, err := basics.DynamoDbClient.CreateTable(context.TODO(), &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), ProvisionedThroughput: &types.ProvisionedThroughput{ ReadCapacityUnits: aws.Int64(10), WriteCapacityUnits: aws.Int64(10), }, }) 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(context.TODO(), &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 } return tableDesc, err }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Go API 參考CreateTable中的。

Java
適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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.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.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. * * For more information, see the following documentation topic: * * 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()) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(10L) .writeCapacityUnits(10L) .build()) .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中的。

JavaScript
適用於 JavaScript (v3) 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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", }, ], ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, }); const response = await client.send(command); console.log(response); return response; };
適用於 JavaScript (v2) 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

// 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); } });
Kotlin
適用於 Kotlin 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 provisionedVal = ProvisionedThroughput { readCapacityUnits = 10 writeCapacityUnits = 10 } val request = CreateTableRequest { attributeDefinitions = listOf(attDef) keySchema = listOf(keySchemaVal) provisionedThroughput = provisionedVal tableName = tableNameVal } DynamoDbClient { 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 CreateTable中的 Kotlin API 參考。

PHP
適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

建立 資料表。

$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中的。

PowerShell
適用的工具 PowerShell

範例 1:此範例會建立名為 Thread 的資料表,其主索引鍵由 'ForumName' (雜湊金鑰類型) 和 'Subject' (索引鍵類型範圍) 組成。用來建構資料表的結構描述可以傳送至每個指令程式,如所示或使用-Schema 參數指定。

$schema = New-DDBTableSchema $schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S" $schema | Add-DDBKeySchema -KeyName "Subject" -KeyType RANGE -KeyDataType "S" $schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5

輸出:

AttributeDefinitions : {ForumName, Subject} TableName : Thread KeySchema : {ForumName, Subject} TableStatus : CREATING CreationDateTime : 10/28/2013 4:39:49 PM ProvisionedThroughput : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription TableSizeBytes : 0 ItemCount : 0 LocalSecondaryIndexes : {}

範例 2:此範例會建立名為 Thread 的資料表,其主索引鍵由 'ForumName' (雜湊金鑰類型) 和 'Subject' (索引鍵類型範圍) 組成。也會定義本機次要索引。本地輔助索引的鍵將從表上的主哈希鍵自動設置(ForumName)。用來建構資料表的結構描述可以傳送至每個指令程式,如所示或使用-Schema 參數指定。

$schema = New-DDBTableSchema $schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S" $schema | Add-DDBKeySchema -KeyName "Subject" -KeyDataType "S" $schema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only" $schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5

輸出:

AttributeDefinitions : {ForumName, LastPostDateTime, Subject} TableName : Thread KeySchema : {ForumName, Subject} TableStatus : CREATING CreationDateTime : 10/28/2013 4:39:49 PM ProvisionedThroughput : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription TableSizeBytes : 0 ItemCount : 0 LocalSecondaryIndexes : {LastPostIndex}

範例 3:此範例顯示如何使用單一管線建立名為 Thread 的資料表,其主索引鍵由 'ForumName' (索引鍵類型 hash) 和 'Subject' (索引鍵類型範圍) 和本機次要索引組成。如果沒有從管線或-Schema 參數提供,Add-DDB KeySchema 和 Add-DDB 會為您IndexSchema 建立新 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 指令程CreateTable式參考中的。

Python
適用於 Python (Boto3) 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

建立用於存放電影資料的資料表。

class Movies: """Encapsulates an Amazon DynamoDB table of movie data.""" 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"}, ], ProvisionedThroughput={ "ReadCapacityUnits": 10, "WriteCapacityUnits": 10, }, ) 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 開發套件CreateTable中的 Python (博托 3) API 參考。

Ruby
適用於 Ruby 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

# Encapsulates an Amazon DynamoDB table of movie data. class Scaffold attr_reader :dynamo_resource attr_reader :table_name attr_reader :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"} ], provisioned_throughput: {read_capacity_units: 10, write_capacity_units: 10}) @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中的。

Rust
適用於 Rust 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 pt = ProvisionedThroughput::builder() .read_capacity_units(10) .write_capacity_units(5) .build() .map_err(Error::BuildError)?; let create_table_response = client .create_table() .table_name(table_name) .key_schema(ks) .attribute_definitions(ad) .provisioned_throughput(pt) .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 CreateTable中的 Rust API 參考資料。

SAP ABAP
適用於 SAP ABAP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 CreateTable中的 SAP ABAP API 參考資料。

Swift
適用於 Swift 的 SDK
注意

這是適用於預覽版本 SDK 的發行前版本文件。內容可能變動。

注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// /// Create a movie table in the Amazon DynamoDB data store. /// private func createTable() async throws { 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), ], keySchema: [ DynamoDBClientTypes.KeySchemaElement(attributeName: "year", keyType: .hash), DynamoDBClientTypes.KeySchemaElement(attributeName: "title", keyType: .range) ], provisionedThroughput: DynamoDBClientTypes.ProvisionedThroughput( readCapacityUnits: 10, writeCapacityUnits: 10 ), tableName: self.tableName ) let output = try await client.createTable(input: input) if output.tableDescription == nil { throw MoviesError.TableNotFound } }
  • 有關 API 的詳細信息,請參閱 AWS SDK CreateTable中的斯威夫特 API 參考

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱搭配開發套件使用 DynamoDB AWS。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。