dynamodb get all items by an array of ids
11,705
Solution 1
You can also use
DocumentClient
andbatchGet
.
const AWS = require('aws-sdk');
const documentClient = new AWS.DynamoDB.DocumentClient();
let queryParams = {RequestItems: {}};
queryParams.RequestItems['tableName'] = {
Keys: [{'id': 'Value1'}, {'id': 'value2'}],
ProjectionExpression: 'id' //define other fileds that you have Ex: 'id,name'
};
documentClient.batchGet(queryParams, function (err, data) {
if (err) {
console.log('failure:getItemByBatch data from Dynamo error', err);
} else {
console.log('success:getItemByBatch data from Dynamo data');
console.log(data)
}
});
Solution 2
Please use BatchGetItem
API to get multiple values from DynamoDB table.
Example:-
var dynamodb = new AWS.DynamoDB({maxRetries: 5, retryDelayOptions: {base: 300} });
var table = "Movies";
var year_val = 2015;
var title = "The Big New Movie";
var params = {
"RequestItems" : {
"Movies" : {
"Keys" : [ {
"yearkey" : {N : "2016"},
"title" : {S : "The Big New Movie 1"}
} ]
}
},
"ReturnConsumedCapacity" : "TOTAL"
};
dynamodb.batchGetItem(params, function(err, data) {
if (err) {
console.error("Unable to get item. Error JSON:", JSON.stringify(err,
null, 2));
} else {
console.log("Movie data:", JSON.stringify(data, null, 2));
}
});
Related videos on Youtube
Comments
-
thatsIT almost 2 years
I have a table with an attribute with name id and of type HASH. I want to get all items from a array of id's.
{ TableName: `MyTable`, FilterExpression: 'id IN (:id)', ExpressionAttributeValues: { ':id': ids }, };
What should I do to get all items by my ids?
-
thatsIT over 5 yearsI get a 'Invalid attribute value type' error. Changed the params object to this: { "RequestItems" : { "MyTable" : { "Keys" : [ { "id" : {S : "f403f77e-8c18-4ed5-94bb-c4b5f14d1b01"} }] } }, "ReturnConsumedCapacity" : "TOTAL" }
-
Tanuki almost 5 yearsDoesnt work with Typescript strick checking. It returns
Element implicitly has an 'any' type because expression of type '"tableName"' can't be used to index type '{}'. Property 'tableName' does not exist on type '{}'
-
Tanuki almost 5 yearsIts this code. Possibly because I have
"strict": true
intsconfig.json
. The work around I found is to do(queryParams as any).
-
Caveman over 3 years@Tanuki that's an error that depends on your TS config. It's irrelevant to the answer.