Node.js 无法使用查询DynamoDB获取所有项
如何使用node.js扫描AWS dynamodb中的所有项目。我在这里张贴我的代码Node.js 无法使用查询DynamoDB获取所有项,node.js,amazon-web-services,amazon-dynamodb,Node.js,Amazon Web Services,Amazon Dynamodb,如何使用node.js扫描AWS dynamodb中的所有项目。我在这里张贴我的代码 //Load the AWS SDK for Node.js var AWS = require('aws-sdk'); var unmarshalItem = require('dynamodb-marshaler').unmarshalItem; // Set the region AWS.config.update({region: 'us-east-1'}); // Create DynamoDB
//Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
var unmarshalItem = require('dynamodb-marshaler').unmarshalItem;
// Set the region
AWS.config.update({region: 'us-east-1'});
// Create DynamoDB service object
var b = new AWS.DynamoDB({apiVersion: '2012-08-10'});
exports.handler = (event, context, callback) => {
var params = {
TableName: 'IoTdata2',
FilterExpression: "#deviceid = :unitID and #devicetimestamp BETWEEN :ftimestamp and :ttimestamp",
ExpressionAttributeNames: {
"#deviceid": "id",
"#devicetimestamp": "timestamp"
},
ExpressionAttributeValues: {
':unitID': {S: 'arena-MXHGMYzBBP5F6jztnLUdCL' },
':ftimestamp' : {S: '1584022680000' },
':ttimestamp' : {S: '1584023280000' }
},
};
b.scan(params, onScan);
function onScan(err, data) {
if (err) {
console.error("Unable to scan the table. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("Scan succeeded.");
var items = data.Items.map(function(val){
return unmarshalItem(val);
})
// continue scanning if we have more items
if (typeof data.LastEvaluatedKey != "undefined") {
console.log("Scanning for more...");
params.ExclusiveStartKey = data.LastEvaluatedKey;
b.scan(params, onScan);
}
}
callback(null, items);
}
};
我已经跟踪了链接
过一会儿我就有时间在这里了。我也检查了这个链接
我想我无法正确返回数据,有什么建议吗?谢谢从这里开始,通过遵循Hank的解决方案,这对我起到了作用:
在最后一个评估的键处重新运行扫描的迭代解决方案比这种递归方法更好。我的建议是把所有的物品都积累起来,以后再把它们全部拆开。这是假设您确实需要同时将所有项读入内存(如果是一个大表,则不理想)。根据需要实施退避/重试,或者评估DynamoDB表支持执行此完全扫描所需的RCU的能力。看起来您正在使用lambda。确保延长执行时间,并在函数中添加async,Wait。
exports.handler = async (event, context, callback) => {
let params = {
ExpressionAttributeNames: {
"#deviceid": "id",
"#devicetimestamp": "timestamp"
},
ExpressionAttributeValues: {
':unitID': {S: event.deviceid },
':ftimestamp' : {S: event.fromtime },
':ttimestamp' : {S: event.totime }
},
KeyConditionExpression: '#deviceid = :unitID and #devicetimestamp BETWEEN :ftimestamp and :ttimestamp',
TableName: 'IoTdata2'
};
let scanResults = [];
let items;
do {
items = await b.query(params).promise();
items.Items.map((item) => scanResults.push(unmarshalItem(item)));
params.ExclusiveStartKey = items.LastEvaluatedKey;
} while (typeof items.LastEvaluatedKey != "undefined");
var len = scanResults.length;
console.log(len);
callback(null, scanResults);
};