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

使用 Amazon SDK 创建 DynamoDB 表

以下代码示例说明如何创建 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 = "S", }, new AttributeDefinition { AttributeName = "year", AttributeType = "N", }, }, KeySchema = new List<KeySchemaElement>() { new KeySchemaElement { AttributeName = "year", KeyType = "HASH", }, new KeySchemaElement { AttributeName = "title", 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

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

Go
SDK for Go V2
注意

在 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
SDK for Java 2.x
注意

在 GitHub 上查看更多内容。在 Amazon 代码示例存储库 中查找完整示例,了解如何进行设置和运行。

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(new Long(10)) .writeCapacityUnits(new Long(10)) .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
SDK for JavaScript V3
注意

在 GitHub 上查看更多内容。在 Amazon 代码示例存储库 中查找完整示例,了解如何进行设置和运行。

创建客户端。

// Create service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon DynamoDB service client object. const ddbClient = new DynamoDBClient({ region: REGION }); export { ddbClient };

创建 表。

// Import required AWS SDK clients and commands for Node.js import { CreateTableCommand } from "@aws-sdk/client-dynamodb"; import { ddbClient } from "./libs/ddbClient.js"; // Set the parameters export const params = { AttributeDefinitions: [ { AttributeName: "Season", //ATTRIBUTE_NAME_1 AttributeType: "N", //ATTRIBUTE_TYPE }, { AttributeName: "Episode", //ATTRIBUTE_NAME_2 AttributeType: "N", //ATTRIBUTE_TYPE }, ], KeySchema: [ { AttributeName: "Season", //ATTRIBUTE_NAME_1 KeyType: "HASH", }, { AttributeName: "Episode", //ATTRIBUTE_NAME_2 KeyType: "RANGE", }, ], ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, TableName: "TEST_TABLE", //TABLE_NAME StreamSpecification: { StreamEnabled: false, }, }; export const run = async () => { try { const data = await ddbClient.send(new CreateTableCommand(params)); console.log("Table Created", data); return data; } catch (err) { console.log("Error", err); } }; run();
SDK for 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
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

注意

在 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 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 CreateTable

PHP
SDK for PHP
注意

在 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 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 详细信息,请参阅《适用于 Python (Boto3) 的 Amazon SDK API 参考》中的 CreateTable

Ruby
SDK for Ruby
注意

在 GitHub 上查看更多内容。在 Amazon 代码示例存储库 中查找完整示例,了解如何进行设置和运行。

# 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) rescue Aws::Errors::ServiceError => e puts("Couldn't create table #{table_name}. Here's why:") puts("\t#{e.code}: #{e.message}") raise else @table end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 CreateTable

Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

注意

在 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(); let ks = KeySchemaElement::builder() .attribute_name(&a_name) .key_type(KeyType::Hash) .build(); let pt = ProvisionedThroughput::builder() .read_capacity_units(10) .write_capacity_units(5) .build(); 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 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 CreateBucket

有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 结合使用 DynamoDB 与 Amazon SDK。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。