callmevari
callmevari

Reputation: 77

Which is the correct way to scan a table on DynamoDB?

As the title says, I want to know which is the best way to scan a table in Amazon DynamoDB, searching by another field than the primary key.

I searched about this and read a lot, but I found this solution for me:

let DynamoDBServiceObj = new AWS.DynamoDB({apiVersion: '2012-08-10'});

let params = {
   ExpressionAttributeValues: {
       ':hash' : { S: req.param('wildcard') }
   },
   ProjectionExpression: 'directory',
   FilterExpression: 'qrCode = :hash',
   TableName: 'business'
};

let business = await DynamoDBServiceObj.scan(params).promise();
if (business.Count == 1) return res.ok();
else return res.view('404');

This works for me, but I also read that perform an scan on a table is a bad idea, for performance and pricing. But, how to do it then?

I read these posts, and I suppose that GSI is the solution, but I don't understand how it works.

Upvotes: 2

Views: 1634

Answers (1)

Tommy
Tommy

Reputation: 1034

Like you said, scanning the table is not a great idea and you have already read about it. I would suggest two things.

  1. Use a composite primary key (if you're not doing so yet). Using the combination of partition key and sort key gives you more possibilities to query (and not scan) your table depending on your frequent access patterns.

  2. If you still need to query the table by an attribute other than the ones included in your composite primary key, you are right that the GSI is the solution. You can check this post on how the GSI works. Choose primary index for Global secondary index You can think of a GSI as a copy of your table with a different primary key.

Upvotes: 2

Related Questions