2017-08-08 68 views
1

我正在使用dynamoDB本地。我想創建一個具有6個屬性的表格,其中只有一個是key。我怎麼做?在keySchema中指定關鍵屬性,並在AttributeDefinitions中指定所有屬性?node.js:如何在創建表時在DynamoDB中添加非鍵屬性?

var params = { 
    TableName : "Movies", 
    KeySchema: [ 
     { AttributeName: "year", KeyType: "HASH"}, //Partition key 
    ], 
    AttributeDefinitions: [ 
     { AttributeName: "year", AttributeType: "N" }, 
     { AttributeName: "title", AttributeType: "S" } 
    ], 
    ProvisionedThroughput: { 
     ReadCapacityUnits: 10, 
     WriteCapacityUnits: 10 
    } 
}; 

dynamodb.createTable(params, function(err, data) { 
    if (err) { 
     console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2)); 
    } else { 
     console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2)); 
    } 
}); 

回答

1

您是否收到以下錯誤?

一個或多個參數值無效:屬性在 KeySchema號碼,因爲你AttributeDefinitions包含未中定義的屬性不完全匹配 AttributeDefinitions

這是定義的屬性數量KeySchema。如果您只打算使用HASH密鑰,並且不需要RANGE密鑰,則可以從AttributeDefinitions中刪除title屬性。

DynamoDB是無模式,所以你並不需要在AttributeDefinitions任何非關鍵屬性定義。當您將一個項目放入您的表格時,您可以添加任何其他屬性(必須包含分區/排序鍵)。

下面的代碼將創建只有HASH (Partition) key表:

var dynamodb = new AWS_SDK.DynamoDB(); 

var params = { 
    TableName : "MyNewTable", 
    KeySchema: [ 
     { AttributeName: "year", KeyType: "HASH"}, //Partition key 
     //{ AttributeName: "title", KeyType: "RANGE"}, //Sort key 
    ], 
    AttributeDefinitions: [ 
     { AttributeName: "year", AttributeType: "N" }, 
     // { AttributeName: "title", AttributeType: "S" } 
    ], 
    ProvisionedThroughput: { 
     ReadCapacityUnits: 10, 
     WriteCapacityUnits: 10 
    } 
}; 

dynamodb.createTable(params, function(err, data) { 
    if (err) { 
     console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2)); 
    } else { 
     console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2)); 
    } 

欲瞭解更多信息,可以參考AWS SDK documentation有關DynamoDB服務createTable功能。

希望這會有所幫助!