4

I am designing a simple serverless app in AWS: API Gateway-> Lambda (node.js) -> DynamoDB.

I want to keep number of customers in the same table and coresponding items e.g.

Client_id, no, item, price

0001, 1, box, 10

0001, 2, table, 100

0002, 1, chair, 20

0003, 1, lamp, 15

I choose Primary Key = Client_id and Sort Key = no and currently I am able to get single item using "dynamodb.get" function, but have problems with getting all items for one client. I tried to use "dynomodb.batchget", but I need to know how many items are in table and do some loops perhaps. Maybe there is different, batter way to to get all items from single client?


const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();

module.exports.get2 = (event, context, callback) => {

    var params = {
        "RequestItems": {
            "items": {
                "Keys": [{
                        id: Number(event.pathParameters.id),
                        no: 1
                    },
                    {
                        id: Number(event.pathParameters.id),
                        no: 2
                    }
                ]
            }
        },
        "ReturnConsumedCapacity": "TOTAL"
    };

    dynamoDb.batchGet(params, function(err, data) {
        if (err) {
            console.error(err);
            callback(null, {
                statusCode: err.statusCode || 501,
                headers: { 'Content-Type': 'text/plain' },
                body: 'Couldn\'t fetch the item.',
            });
            return;
        }
        const response = {
            statusCode: 200,
            body: JSON.stringify(data),
        };
        callback(null, response);
    });
};```
0

1 Answer 1

7

To find all records for a given Client_id, use query. Here's an example:

const AWS = require("aws-sdk");

AWS.config.update({region: 'us-east-1'});

const params = {
  TableName: 'mytable',
  KeyConditionExpression: 'Client_id = :Client_id',
  ExpressionAttributeValues: {
    ':Client_id': '0001',
  },
};

const dc = new AWS.DynamoDB.DocumentClient();

dc.query(params, (err, data) => {
  if (err) {
    console.log('Error', err);
  } else {
    for (const item of data.Items) {
      console.log('item:', item);
    };
  }
});

If, however, you knew in advance the full (partition and sort) keys of the items you wanted (as opposed to all items with a given partition key) then you could use batchGetItem.

Also, consider using the promisified variants of the SDK functions.

1
  • Yes you are right I can use query. Thanks. In fact I figure it out last night. Commented Sep 24, 2019 at 8:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.