node.js:如何在创建表时在 DynamoDB 中添加非键属性?

nad*_*nad 4 node.js amazon-dynamodb

我在本地使用 dynamoDB。我想创建一个具有 6 个属性的表,其中只有一个是key. 我怎么做?keySchemaAttributeDefinitions? 中指定键属性和所有属性?

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));
    }
});
Run Code Online (Sandbox Code Playgroud)

msc*_*ker 7

您是否收到以下错误?

一个或多个参数值无效:KeySchema 中的属性数与 AttributeDefinitions 中定义的属性数不完全匹配

这是因为您AttributeDefinitions包含一个未在KeySchema. 如果您只打算使用HASH密钥而不需要RANGE密钥,则可以titleAttributeDefinitions.

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));
    }
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,可以参考AWS SDK文档createTable功能上DynamoDB的服务。

希望这可以帮助!