Search code examples
node.jsamazon-dynamodbdynamodb-queries

How To Get Item From DynamoDB Based On Multiple (one primary) Attributes Lambda/NodeJS


My table structure in DynamoDB looks like the following:

uuid (Primary Key) | ip | userAgent

From within a NodeJS function inside of lambda, I would like to get the uuid of an item whose ip and useragent match the information I provide.

Scan becomes less and less efficient and more expensive over time as millions of items are added to the table every week.

Here is the code I am using to try and accomplish this:

function tieDown(sIP, uA){
 const userQuery = {
       Key : {
         "ip" : "192.168.0.1",
         "userAgent" : "sample"
       },
       TableName: "mytable"
      };
  return ddb.get(userQuery, function(err, data){
   if (err) console.log(err.stack);
  }).promise();
}

When this code executes, the following error is thrown ValidationException: The provided key element does not match the schema.

So I guess my questions are:

  • Is it even possible to get one specific item based on non-primary attributes
  • Are there any issues with the code sample I provided that could lead to this error being thrown? (I'm using DocumentClient so no need to explicitly declare strings, numbers etc.

Thanks!


Solution

  • You cannot get a single item using the get operation without specifying the partition key, and sort key if you have one. Scans should be avoided in most cases. What you probably need is a Global Secondary Index that allows you to query by ip and userAgent. Keep in mind that the records on a GSI are not guaranteed unique, so you may get more than one result.