DynamoDB - 建立表



建立表通常包括生成表、命名錶、建立其主鍵屬性以及設定屬性資料型別。

可以使用GUI控制檯、Java或其他選項來執行這些任務。

使用GUI控制檯建立表

透過訪問https://console.aws.amazon.com/dynamodb上的控制檯來建立表。然後選擇“建立表”選項。

GUI Console

我們的示例生成一個填充了產品資訊的表,其中具有唯一屬性的產品由ID號(數字屬性)標識。在建立表螢幕中,在表名稱欄位中輸入表名稱;在分割槽鍵欄位中輸入主鍵 (ID);並在資料型別中輸入“Number”。

Create Table

輸入所有資訊後,選擇建立

使用Java建立表

使用Java建立相同的表。其主鍵包含以下兩個屬性:

  • ID - 使用分割槽鍵和ScalarAttributeType N(表示數字)。

  • Nomenclature - 使用排序鍵和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("https://: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引數,本地安裝會忽略此引數。

廣告
© . All rights reserved.