使用 Document API 在 Java 中建立表
在以下示例中,我們將使用 AWS Java SDK for DynamoDB 建立一個名為 Membership
的表。該表將包含代表團隊分配的專案。該表將由 TeamID 分割槽。每個團隊將有多個成員,由 MemberID 標識(作為排序鍵)。
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
}