amazon-dynamodb Crear tabla en Java utilizando Document API


Ejemplo

En el siguiente ejemplo, crearemos una tabla llamada Membership utilizando el SDK Java de AWS para DynamoDB. La tabla constará de elementos que representan las tareas del equipo. La tabla será particionada por TeamID. Cada equipo tendrá varios miembros, identificados por el MemberID (como una clave de clasificación).

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
}