创建表通常包括生成表,命名表,建立主键属性以及设置属性数据类型.
使用GUI控制台,Java或其他选项执行这些任务.
通过访问控制台 https://console.aws.amazon.com/dynamodb .然后选择"创建表格"选项.
我们的示例生成一个填充了产品信息的表,其中包含由ID号(数字属性)标识的唯一属性的产品.在创建表屏幕中,在表名称字段中输入表名称;输入分区键字段内的主键(ID);并输入数据类型的"数字".
输入所有信息后,选择创建.
使用Java创建同一个表.它的主键包括以下两个属性 :
ID : 使用分区键,ScalarAttributeType N ,表示数字.
命名法 : 使用排序键,ScalarAttributeType S ,意思是字符串.
Java使用 createTable方法生成一个表;并且在调用中,指定了表名,主键属性和属性数据类型.
您可以查看以下示例 :
import java.util.Arrays; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; public class ProductsCreateTable { public static void main(String[] args) throws Exception { AmazonDynamoDBClient client = new AmazonDynamoDBClient() .withEndpoint("http://localhost:8000"); DynamoDB dynamoDB = new DynamoDB(client); String tableName = "Products"; try { System.out.println("Creating the table, wait..."); Table table = dynamoDB.createTable (tableName, Arrays.asList ( new KeySchemaElement("ID", KeyType.HASH), // the partition key // the sort key new KeySchemaElement("Nomenclature", KeyType.RANGE) ), Arrays.asList ( new AttributeDefinition("ID", ScalarAttributeType.N), new AttributeDefinition("Nomenclature", ScalarAttributeType.S) ), new ProvisionedThroughput(10L, 10L) ); table.waitForActive(); System.out.println("Table created successfully. Status: " + table.getDescription().getTableStatus()); } catch (Exception e) { System.err.println("Cannot create the table: "); System.err.println(e.getMessage()); } } }
在上面的示例中,请注意端点: .withEndpoint .
它表示使用localhost使用本地安装.另请注意本地安装忽略所需的 ProvisionedThroughput参数.