amazon-dynamodb Create Table in Java using Document API


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()
      // optionally: add a sort key (also called a range key)
  keySchema.add(new KeySchemaElement()

      // 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()
      //  if using a sort key we need to specify its type; suppose that it's numeric
  attrDefinitions.add(new AttributeDefinition()

      // 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()
      .withProvisionedThroughput(new ProvisionedThroughput()

      // 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

      // 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