amazon-dynamodb Create Table in Java using Document API


Example

In the following example we will be creating a table called Membership using the AWS Java SDK for DynamoDB. The table will consist of items that represent team assignments. The table will be partitioned by TeamID. Each team will have multiple members, identified by the MemberID (as a sort key).

AWSCredentials credentials = new BasicAWSCredentials("access_key", "secret_key");
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(credentials));

try {
      // every DynamoDB table must have basic schema that determines
      //   which attributes are to be used as partition key (and optionally sort key) 
  List<KeySchemaElement> keySchema = new ArrayList<~>();
      // required: specify the partition key (also called hash key)
  keySchema.add(new KeySchemaElement()
             .withAttributeName("TeamID")
             .withKeyType(KeyType.HASH)); 
      // optionally: add a sort key (also called a range key)
  keySchema.add(new KeySchemaElement()
             .withAttributeName("MemberID")
             .withKeyType(KeyType.RANGE));

      // after defining the key schema - the attributes that will be used as partition and range key
      //  we need to specify these attributes' type
  List<AttributeDefinition> attrDefinitions = new ArrayList<~>();
      //  we must specify the type for the TeamID attribute; suppose it's a string
  attrDefinitions.add(new AttributeDefinition()
                  .withAttributeName("TeamID")
                  .withAttributeType("S"));
      //  if using a sort key we need to specify its type; suppose that it's numeric
  attrDefinitions.add(new AttributeDefinition()
                  .withAttributeName("MemberID")
                  .withAttributeType("N"));

        
      // after defining the attributes making up the schema and their type
      // we build a request, specifying the table name and the provisioned capacity 
  CreateTableRequest request = new CreateTableRequest()
      .withTableName("Membership")
      .withKeySchema(keySchema)
      .withAttributeDefinitions(attrDefinitions)
      .withProvisionedThroughput(new ProvisionedThroughput()
           .withReadCapacityUnits(30L)
           .withWriteCapacityUnits(10L));

      // now submit the request to create the table in DynamoDB
  Table table = dynamoDB.createTable(request);

      // creating a table is an asynchronous operation
      // we can wait for the table to be created
  table.waitForActive();

      // the table is now ready and can be used

} catch (Exception e) {
      // the table creation failed. 
      //   the reason for failure may be determined from the exception
}