Query Multiple Items From DynamoDB
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);
});
};```
Answer
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.
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error