Kod*_*der 5 javascript recursion amazon-web-services node.js amazon-dynamodb
这可能是一个JS/Async问题而不是DynamoDB特定问题 -
我想在亚马逊的DynamoDB中使用哈希键获取表中的所有项目.该表中还包含Range键.
我使用的是NodeJS库,它是AWS DynamoDB REST API的包装器.- Node-DynamoDB
每次查询时,DynamoDB仅返回1 MB的结果.要获取结果提醒,它包含lastEvaluatedKey.我们可以在另一个查询中包含这个以获取另外1 MB的结果,依此类推......
我在编写递归异步函数方面遇到困难,该函数应按顺序命中服务,直到我可以获得所有结果.(对于我的用例,表永远不会超过10 MB,没有失控查询的可能性)
一些伪代码用于说明:
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.
}
});
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)