Dynamodb 简明教程

DynamoDB - Create Table

Creating a table generally consists of spawning the table, naming it, establishing its primary key attributes, and setting attribute data types.

Utilize the GUI Console, Java, or another option to perform these tasks.

Create Table using the GUI Console

Create a table by accessing the console at https://console.aws.amazon.com/dynamodb. Then choose the “Create Table” option.

gui console

我们的示例生成一个包含产品信息的表,其中具有唯一属性的产品由 ID 号(数字属性)标识。在 Create Table 屏幕中,在表名字段输入表名;在分区键字段中输入主键 (ID);输入数据类型的“数字”。

create table

输入所有信息后,选择 Create

Create Table using Java

使用 Java 创建相同的表。其主键包含以下两个属性 -

  1. ID − 使用分区键,即 ScalarAttributeType N ,表示数字。

  2. Nomenclature − 使用排序键,即 ScalarAttributeType S ,表示字符串。

Java 使用 createTable method 生成一个表;并在调用中,指定表名、主键属性和属性数据类型。

您可以查看以下示例 -

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 parameter ,本地安装将其忽略。