- AWS Code Sample demonstrates how to create an Amazon DynamoDB table with a composite key.

/* Copyright, Inc. or its affiliates. All Rights Reserved. This file is licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.dynamodb; import; import; import; import; import; import; import; import; import; import; /** * Create an Amazon DynamoDB table * * Takes the name of the table to create. The table will contain a single * primary key, "Name". * * This code expects that you have AWS credentials set up, as described here: * */ public class CreateTableCompositeKey { public static void main(String[] args) { final String USAGE = "\n" + "Usage:\n" + " CreateTable <table>\n\n" + "Where:\n" + " table - the table to create (i.e., Music3)\n\n" + "Example:\n" + " CreateTable Music3\n"; if (args.length < 1) { System.out.println(USAGE); System.exit(1); } /* Read the table name from command args */ String tableName = args[0]; // Create the DynamoDbClient object Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder().region(region).build(); System.out.format("Creating table %s\n with a composite primary key:\n", tableName); System.out.format("* Language - partition key\n"); System.out.format("* Greeting - sort key\n"); String tableId =createTableComKey(ddb,tableName); System.out.println("The table ID is "+tableId); } public static String createTableComKey(DynamoDbClient ddb, String tableName) { CreateTableRequest request = CreateTableRequest.builder() .attributeDefinitions( AttributeDefinition.builder() .attributeName("Language") .attributeType(ScalarAttributeType.S) .build(), AttributeDefinition.builder() .attributeName("Greeting") .attributeType(ScalarAttributeType.S) .build()) .keySchema( KeySchemaElement.builder() .attributeName("Language") .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName("Greeting") .keyType(KeyType.RANGE) .build()) .provisionedThroughput( ProvisionedThroughput.builder() .readCapacityUnits(new Long(10)) .writeCapacityUnits(new Long(10)).build()) .tableName(tableName) .build(); String tableId = ""; try { CreateTableResponse result = ddb.createTable(request); tableId = result.tableDescription().tableId(); return tableId; } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } return ""; } }

Sample Details

Service: Amazon DynamoDB

Last tested: 2/5/2020

Author: scmacdon-aws

Type: full-example