Utilizzo CreateTable con un AWS SDK o una CLI - Amazon DynamoDB

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Utilizzo CreateTable con un AWS SDK o una CLI

I seguenti esempi di codice mostrano come utilizzareCreateTable.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nei seguenti esempi di codice:

.NET
AWS SDK for .NET
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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; }
  • Per i dettagli sull'API, consulta la CreateTablesezione AWS SDK for .NET API Reference.

Bash
AWS CLI con lo script Bash
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 }

Le funzioni di utilità utilizzate in questo esempio.

############################################################################### # 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 }
C++
SDK per C++
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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(); }
  • Per i dettagli sull'API, consulta la CreateTablesezione AWS SDK for C++ API Reference.

CLI
AWS CLI

Esempio 1: creare una tabella con tag

L'create-tableesempio seguente utilizza gli attributi e lo schema chiave specificati per creare una tabella denominataMusicCollection. Questa tabella utilizza la velocità effettiva assegnata ed è crittografata a riposo utilizzando la CMK di AWS proprietà predefinita. Il comando applica anche un tag alla tabella, con una chiave di Owner e un valore di. 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

Output:

{ "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" } }

Per ulteriori informazioni, consulta Basic Operations for Tables nella Amazon DynamoDB Developer Guide.

Esempio 2: creare una tabella in modalità On-Demand

L'esempio seguente crea una tabella chiamata MusicCollection utilizzando la modalità on-demand, anziché la modalità throughput assegnata. Questa funzionalità è utile per le tabelle con carichi di lavoro imprevedibili.

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

Output:

{ "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" } } }

Per ulteriori informazioni, consulta Basic Operations for Tables nella Amazon DynamoDB Developer Guide.

Esempio 3: creare una tabella e crittografarla con una CMK gestita dal cliente

L'esempio seguente crea una tabella denominata MusicCollection e la crittografa utilizzando una CMK gestita dal cliente.

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

Output:

{ "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" } } }

Per ulteriori informazioni, consulta Basic Operations for Tables nella Amazon DynamoDB Developer Guide.

Esempio 4: creare una tabella con un indice secondario locale

L'esempio seguente utilizza gli attributi e lo schema chiave specificati per creare una tabella denominata MusicCollection con un indice secondario locale denominatoAlbumTitleIndex.

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\"] } } ]"

Output:

{ "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" } ] } }

Per ulteriori informazioni, consulta Basic Operations for Tables nella Amazon DynamoDB Developer Guide.

Esempio 5: creare una tabella con un indice secondario globale

L'esempio seguente crea una tabella denominata GameScores con un indice secondario globale chiamatoGameTitleIndex. La tabella di base ha una chiave di partizione di UserId e una chiave di ordinamento di GameTitle, permettendo di trovare il miglior punteggio di un singolo utente per un gioco specifico in modo efficiente, mentre il GSI ha una chiave di partizione di GameTitle e una chiave di ordinamento di TopScore, permettendo di trovare rapidamente il punteggio più alto complessivo per un determinato gioco.

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 } } ]"

Output:

{ "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" } ] } }

Per ulteriori informazioni, consulta Basic Operations for Tables nella Amazon DynamoDB Developer Guide.

Esempio 6: creare una tabella con più indici secondari globali contemporaneamente

L'esempio seguente crea una tabella denominata GameScores con due indici secondari globali. Gli schemi GSI vengono passati tramite un file, anziché sulla riga di comando.

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

Contenuto di 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 } } ]

Output:

{ "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" } ] } }

Per ulteriori informazioni, consulta Basic Operations for Tables nella Amazon DynamoDB Developer Guide.

Esempio 7: creare una tabella con Streams abilitato

L'esempio seguente crea una tabella chiamata GameScores con DynamoDB Streams abilitato. Sia le immagini nuove che quelle vecchie di ogni elemento verranno scritte nello stream.

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

Output:

{ "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" } }

Per ulteriori informazioni, consulta Basic Operations for Tables nella Amazon DynamoDB Developer Guide.

Esempio 8: creare una tabella con Keys-Only Stream abilitato

L'esempio seguente crea una tabella chiamata GameScores con DynamoDB Streams abilitato. Nel flusso vengono scritti solo gli attributi chiave degli elementi modificati.

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

Output:

{ "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 } }

Per ulteriori informazioni, consulta Change data capture for DynamoDB Streams nella Amazon DynamoDB Developer Guide.

Esempio 9: creare una tabella con la classe Standard Infrequent Access

L'esempio seguente crea una tabella chiamata GameScores e assegna la classe di tabella Standard-Infrequent Access (DynamoDB Standard-IA). Questa classe di tabelle è ottimizzata perché lo storage è il costo principale.

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

Output:

{ "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 } }

Per ulteriori informazioni, consulta Table classes nella Amazon DynamoDB Developer Guide.

Esempio 10: creare una tabella con la protezione da eliminazione abilitata

L'esempio seguente crea una tabella denominata GameScores e abilita la protezione da eliminazione.

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

Output:

{ "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 } }

Per ulteriori informazioni, consulta Using Delection Protection nella Amazon DynamoDB Developer Guide.

  • Per i dettagli sull'API, consulta AWS CLI Command CreateTableReference.

Go
SDK per Go V2
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 }
  • Per i dettagli sull'API, consulta la CreateTablesezione AWS SDK for Go API Reference.

Java
SDK per Java 2.x
Nota

C'è di più su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 ""; } }
  • Per i dettagli sull'API, consulta la CreateTablesezione AWS SDK for Java 2.x API Reference.

JavaScript
SDK per JavaScript (v3)
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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; };
SDK per JavaScript (v2)
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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
SDK per Kotlin
Nota

C'è di più su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 } }
  • Per i dettagli sull'API, CreateTableconsulta AWS SDK for Kotlin API reference.

PHP
SDK per PHP
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Creare una tabella .

$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], ]); }
  • Per i dettagli sull'API, consulta la CreateTablesezione AWS SDK for PHP API Reference.

PowerShell
Strumenti per PowerShell

Esempio 1: Questo esempio crea una tabella denominata Thread con una chiave primaria composta da 'ForumName' (hash del tipo di chiave) e 'Subject' (intervallo dei tipi di chiave). Lo schema utilizzato per costruire la tabella può essere inserito in ogni cmdlet come mostrato o specificato utilizzando il parametro -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

Output:

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 : {}

Esempio 2: questo esempio crea una tabella denominata Thread con una chiave primaria composta da '' (hash del tipo di chiave) e ForumName 'Subject' (intervallo dei tipi di chiave). Viene inoltre definito un indice secondario locale. La chiave dell'indice secondario locale verrà impostata automaticamente dalla chiave hash primaria sulla tabella (ForumName). Lo schema utilizzato per costruire la tabella può essere inserito in ogni cmdlet come mostrato o specificato utilizzando il parametro -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

Output:

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}

Esempio 3: Questo esempio mostra come utilizzare una singola pipeline per creare una tabella denominata Thread con una chiave primaria composta da '' (hash del tipo di chiave) e ForumName 'Subject' (intervallo dei tipi di chiave) e un indice secondario locale. Add-DB KeySchema e Add-DDB IndexSchema creano automaticamente un nuovo TableSchema oggetto se uno non viene fornito dalla pipeline o dal parametro -Schema.

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

Output:

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}
  • Per i dettagli sull'API, vedere in Cmdlet Reference. CreateTableAWS Tools for PowerShell

Python
SDK per Python (Boto3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Crea una tabella per la memorizzazione dei dati del filmato.

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
  • Per i dettagli sull'API, consulta CreateTable AWSSDK for Python (Boto3) API Reference.

Ruby
SDK per Ruby
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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
  • Per i dettagli sull'API, consulta la CreateTablesezione AWS SDK for Ruby API Reference.

Rust
SDK per Rust
Nota

C'è di più su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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)) } } }
  • Per i dettagli sulle API, consulta la CreateTableguida di riferimento all'API AWS SDK for Rust.

SAP ABAP
SDK per SAP ABAP
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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.
  • Per i dettagli sulle API, CreateTableconsulta AWS SDK for SAP ABAP API reference.

Swift
SDK per Swift
Nota

Si tratta di una documentazione di pre-rilascio di un SDK nella versione di anteprima. ed è soggetta a modifiche.

Nota

C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 } }
  • Per i dettagli sull'API, consulta la CreateTableguida di riferimento all'API AWS SDK for Swift.

Per un elenco completo delle guide per sviluppatori AWS SDK e degli esempi di codice, consulta. Utilizzo di DynamoDB con un SDK AWS Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell'SDK.