【问题标题】:How do I request a single record using AWS DynamoDB? Code samples are not working如何使用 AWS DynamoDB 请求单个记录?代码示例不起作用
【发布时间】:2019-03-18 05:14:19
【问题描述】:

我已经从最基本的代码示例中提取了代码示例,但我仍然无法通过键检索单个记录。这是我使用 nodejs 的基本示例(此 sn-p 中不包含凭据):

var dynamodbClient = new AWS.DynamoDB.DocumentClient();

var params = {
    TableName: 'newsarticles',
    Key: { id: '068d1110-cd0c-11e8-a4d4-57cb772554a4' }
};

//log full dynamodb request object
console.log("request params: ", JSON.stringify(params));

//make dynamodb request
dynamodbClient.get(params, function(err, data) {
    if (err) {
        console.log("error: " + err)
    } else {
        console.log(data.Item);
    }
});

在上面的示例中运行此代码会给我以下错误:

ValidationException:提供的关键元素与架构不匹配

我的数据集很容易插入,系统中的记录如下例所示:

{
  "added": 1539231216801,
  "description": "A number of ethics complaints filed against Supreme Court Justice Brett Kavanaugh have yet to be resolved and will be transferred to a new jurisdiction, Chief Justice John Roberts wrote in a letter Wednesday. ",
  "edited": 1539231216402,
  "id": "068d1110-cd0c-11e8-a4d4-57cb772554a4",
  "largeImageUrl": "https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2018/10/09/105496148-1539094642099gettyimages-1047769784.1910x1000.jpeg",
  "newstitle": "Ethics complaints against Brett Kavanaugh have not been resolved yet",
  "newsurl": "https://www.cnbc.com/2018/10/10/ethics-complaints-against-brett-kavanaugh-have-not-been-resolved-yet.html",
  "posted": 1539231216402,
  "scrapeid": "05c3a690-cd0c-11e8-a4d4-57cb772554a4",
  "scrapes": [
    "05c3a690-cd0c-11e8-a4d4-57cb772554a4"
  ],
  "source": "www.cnbc.com",
  "type": "rate"
}

表是这样定义的:

表名:newsarticles

主分区键:id(字符串)

主排序键:添加(数字)

错误消息并没有真正告诉我问题所在。谁能看到我的请求有什么问题?是否有另一种方法来诊断可能丢失或不正确的内容?在此先感谢,对于 NOOB 问题,我很抱歉,但我只是第一次开始使用 AWS DynamoDB。

【问题讨论】:

    标签: amazon-dynamodb aws-sdk aws-sdk-js aws-sdk-nodejs dynamodb-queries


    【解决方案1】:

    你没有包括完整的主键,你还需要指定排序键,added在这种情况下

    var params = {
        TableName: 'newsarticles',
        Key: {
          id: '068d1110-cd0c-11e8-a4d4-57cb772554a4',
          added: aNumberHere
        }
    };
    

    或者,如果您尝试获取具有特定 ID 的所有记录,则需要使用查询。

    【讨论】:

    • 所以如果我包含排序键,我必须同时使用主键和排序键吗?嗯,我认为这只是为了使查询更快 > 或
    • 这是我测试和工作的:var params = { TableName: 'newsarticles', Key: { id: '068d1110-cd0c-11e8-a4d4-57cb772554a4', added: 1539231216801 } };
    • 嘿@cementmixer,为什么这个对索引主键的简单请求需要 250 毫秒?这似乎很疯狂。我的数据库少于 100 行。
    • 可能是网络延迟和连接开销。如果您重复使用连接,您可以获得更快的响应。此外,获取的延迟与表中的行数无关。我有超过 500m 行的表,并且延迟没有增加。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2012-06-14
    相关资源
    最近更新 更多