首页 > 解决方案 > 如何使用 DynamoDB.DocumentClient for NodeJS 指定主键?

问题描述

我一直在阅读很多文档,特别是针对 的文档,AWS.DynamoDB.DocumentClient并且我正在尝试弄清楚如何使用特定的主键创建 Table / DocumentClient,例如id. 我的理解是主键是必需的,并且“二级索引”是嵌套属性,但我没有看到任何构造函数参数来实际指定id它将为主键。

如何指定id应该是 Table / DocumentClient 的主键?


https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html

注意 主键是必需的。此代码添加了一个具有主键(年份、标题)和信息属性的项目。info 属性存储提供有关电影的更多信息的示例 JSON。

标签: node.jsamazon-web-servicesamazon-ec2amazon-dynamodb

解决方案


好吧,我没有意识到创建表的架构是如此复杂。通过对本地 DynamoDB 的反复试验,它告诉我 KeySchema 必须存在 AttributeDefinitions。这个键模式是指定“主”键名的东西,类型在一个完全独立的字段中。

构造函数对象不填充表,它只设置初始分区(主?)键和可选的排序键,这将形成一个复合键。

var AWS = require('aws-sdk');

AWS.config.update({
  region: 'us-west-2',
  endpoint: 'http://localhost:8000'
});

var db = new AWS.DynamoDB();
var awaitTable = db.describeTable({ TableName: 'app-content' }).promise();

awaitTable.catch(e => {
    if (e.statusCode === 400) {

        return db.createTable({
            TableName: 'app-content',
            KeySchema: [
                { 'AttributeName' : 'fooPartitionKeyName', 'KeyType' : 'HASH' },
                { 'AttributeName' : 'barSortKeyName', 'KeyType' : 'RANGE' }
            ],
            AttributeDefinitions: [
                { 'AttributeName' : 'fooPartitionKeyName', 'AttributeType' : 'S' },
                { 'AttributeName' : 'barSortKeyName', 'AttributeType' : 'S' }
            ],
            ProvisionedThroughput: {
                ReadCapacityUnits: 5,
                WriteCapacityUnits: 5,
            },
        }).promise();

    } else { return Promise.reject('Unknown error fetching table.') }

}).then(table => {
    console.log('table!', table);
});

推荐阅读