Search code examples
amazon-dynamodbaws-sdkaws-sdk-jsaws-sdk-nodejsdynamodb-queries

How do I request a single record using AWS DynamoDB? Code samples are not working


I have taken the code sample down the the very basics and I am still unable to retrieve a single record by the key. Here is my basic example with nodejs (creds not included in this snippet):

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);
    }
});

running this code above example gives me the following error:

ValidationException: The provided key element does not match the schema

my dataset gets inserted easily and the records in the system look like this example:

{
  "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"
}

The table is defined like this:

Table name: newsarticles

Primary partition key: id (String)

Primary sort key: added (Number)

The error message doesn't really tell me what the issue is. Could anyone see what is wrong in my request? Is there another way to diagnose what may be missing or incorrect? Thanks in advance, sorry about the NOOB question but I am just starting with AWS DynamoDB for the first time.


Solution

  • You are not including the full primary key, you need to specify the sort key also,added in this case

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

    Alternately if you are trying to get all the record with a specific id you need to use a query.