dynamodb get all items by an array of ids

11,705

Solution 1

You can also use DocumentClient and batchGet.

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.

BatchGetItem

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));
    }
});
Share:
11,705

Related videos on Youtube

thatsIT
Author by

thatsIT

I'm a software developer that loves my job.

Updated on June 04, 2022

Comments

  • thatsIT
    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
    thatsIT over 5 years
    I 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
    Tanuki almost 5 years
    Doesnt 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
    Tanuki almost 5 years
    Its this code. Possibly because I have "strict": true in tsconfig.json. The work around I found is to do (queryParams as any).
  • Caveman
    Caveman over 3 years
    @Tanuki that's an error that depends on your TS config. It's irrelevant to the answer.