创建 DynamoDB 表 - Amazon DynamoDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

创建 DynamoDB 表

您可以使用 Amazon Web Services Management Console Amazon CLI、或 Amazon SDK 创建表。有关表的更多信息,请参阅Amazon DynamoDB 的核心组件

使用 Amazon SDK 创建 DynamoDB 表。

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

.NET
Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <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 的详细信息,请参阅 Amazon SDK for .NET API 参考CreateTable中的。

Bash
Amazon CLI 使用 Bash 脚本
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

############################################################################### # 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 的详细信息,请参阅Amazon CLI 命令参考CreateTable中的。

C++
适用于 C++ 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

//! 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 的详细信息,请参阅 Amazon SDK for C++ API 参考CreateTable中的。

CLI
Amazon CLI

示例 1:创建带标签的表

以下 create-table 示例将使用指定的属性和键架构来创建名为 MusicCollection 的表。此表使用预配置的吞吐量,并使用默认 Amazon 拥有的 CMK 进行静态加密。该命令还将标签应用于该表,其键为 Owner,值为 blueTeam

aws dynamodb create-table \ --table-name MusicCollection \ --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S \ --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \ --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \ --tags Key=Owner,Value=blueTeam

输出:

{ "TableDescription": { "AttributeDefinitions": [ { "AttributeName": "Artist", "AttributeType": "S" }, { "AttributeName": "SongTitle", "AttributeType": "S" } ], "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "WriteCapacityUnits": 5, "ReadCapacityUnits": 5 }, "TableSizeBytes": 0, "TableName": "MusicCollection", "TableStatus": "CREATING", "KeySchema": [ { "KeyType": "HASH", "AttributeName": "Artist" }, { "KeyType": "RANGE", "AttributeName": "SongTitle" } ], "ItemCount": 0, "CreationDateTime": "2020-05-26T16:04:41.627000-07:00", "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection", "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" } }

有关更多信息,请参阅《Amazon DynamoDB 开发人员指南》中的表的基本操作

示例 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:创建启用了 Streams 的表

以下示例将创建一个名为 GameScores 且启用了 DynamoDB Streams 的表。每个项的新旧映像都将写入流中。

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

输出:

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

有关更多信息,请参阅《Amazon DynamoDB 开发人员指南》中的表的基本操作

示例 8:创建启用了 Keys-Only Stream 的表

以下示例将创建一个名为 GameScores 且启用了 DynamoDB Streams 的表。仅将所修改项的键属性写入流中。

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

输出:

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

有关更多信息,请参阅《Amazon DynamoDB 开发人员指南》中的更改 DynamoDB Streams 的数据捕获

示例 9:使用 Standard Infrequent Access 类创建表

以下示例将创建名为 GameScores 的表并分配 Standard-Infrequent Access(DynamoDB 标准-IA)表类。此表类针对主要的存储成本进行了优化。

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

输出:

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

有关更多信息,请参阅《Amazon DynamoDB 开发人员指南》中的表类

示例 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 的详细信息,请参阅Amazon CLI 命令参考CreateTable中的。

Go
适用于 Go V2 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

// 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 的详细信息,请参阅 Amazon SDK for Go API 参考CreateTable中的。

Java
适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考CreateTable中的。

JavaScript
适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

// 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。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 的详细信息,请参阅适用CreateTable于 K otlin 的 Amazon SDK API 参考

PHP
适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库 中查找完整示例,了解如何进行设置和运行。

创建表。

$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 的详细信息,请参阅 Amazon SDK for PHP API 参考CreateTable中的。

Python
适用于 Python (Boto3) 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

创建用于存储电影数据的表。

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 的详细信息,请参阅适用CreateTablePython 的 Amazon SDK (Boto3) API 参考

Ruby
适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# 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 的详细信息,请参阅 Amazon SDK for Ruby API 参考CreateTable中的。

Rust
适用于 Rust 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 的详细信息,请参阅适用CreateTableRust 的 Amazon SDK API 参考

SAP ABAP
SDK for SAP ABAP
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 的详细信息,请参阅适用CreateTable于 S AP 的 Amazon SDK ABAP API 参考

Swift
SDK for Swift
注意

这是预览版 SDK 的预发布文档。本文档随时可能更改。

注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// /// 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 的详细信息,请参阅适用于 S wift 的 Amazon SDK API 参考CreateTable中。

有关更多 DynamoDB 示例,请参阅使用软件开发工具包的 DynamoDB 的代码示例 Amazon