Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Fetch All Items In DynamoDB Query using Node JS

This is probably more of an JS/Async question than a DynamoDB specific question -

I want to fetch all the items in a table with a hash key in Amazon's DynamoDB. The table also has Range key in it.

I am using a NodeJS library which is a wrapper around AWS DynamoDB REST API. - Node-DynamoDB

DynamoDB only returns 1 MB worth of results with each query. To fetch reminder of results, it includes lastEvaluatedKey . We can include this in another query to fetch another 1 MB worth of results and so on...

I am facing difficulty in writing a recursive async function which should hit the service sequentially till i can get all the results back. (table will never have more than 10 MB for my use case, no chance of a runaway query)

Some pseudo code for illustration:

ddb.query('products', primarykey, {}, function(err,result){
    //check err
    if(result && result.lastEvaluatedKey){
        //run the query again
        var tempSet = result.items;
        //temporarily store result.items so we can continue and fetch remaining items.
    }
    else{
        var finalSet = result.items;
        //figure out how to merge with items that were fetched before.
    }
});
like image 298
Koder Avatar asked Aug 11 '14 11:08

Koder


1 Answers

var getAll = function(primarykey, cb) {
    var finalSet = [],
        nextBatch = function(lek) {
            ddb.query('products', primarykey, {
                exclusiveStartKey: lek
            }, function(err, result) {
                if (err) return cb(err);

                if (result.items.length)
                    finalSet.push.apply(finalSet, result.items);

                if (result.lastEvaluatedKey)
                    nextBatch(result.lastEvaluatedKey);
                else
                    cb(null, finalSet);
            });
        };

    nextBatch();
};


getAll(primarykey, function(err, all) {
    console.log(err, all);
});
like image 87
aaaristo Avatar answered Oct 09 '22 09:10

aaaristo