您的问题的直接答案是您需要在回调函数中使用 result.Table.ItemCount 而不是 result.ItemCount。但是请注意,此计数不会实时更新,并且可能不会反映最近对表的插入或删除。如果您想要当前项目计数,则需要扫描表并使用 Count 属性来获取扫描项目的计数。像这样的扫描可能会消耗您为表配置的所有容量,因此如果这是一项要求,请务必平衡对最近项目计数的需求与可能同时在表上运行的其他操作。
这是返回项目计数的扫描的 node.js 示例。由于扫描被迭代调用,直到所有行都被读取,我使用异步模块在发出下一个循环之前等待结果。
var async = require('async');
var AWS = require('aws-sdk');
AWS.config.update({accessKeyId: 'AKID',
secretAccessKey: 'secret',
region: 'us-east-1'});
var svc = new AWS.DynamoDB();
var scanComplete = false,
itemCountTotal = 0,
consumedCapacityUnitsTotal = 0;
var scanParams = { TableName : 'usertable',
Count : 'true' };
// scan is called iteratively until all rows have been scanned
// this uses the asyc module to wait for each call to complete
// before issuing the next.
async.until( function() { return scanComplete; },
function (callback) {
svc.scan(scanParams, function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
if (typeof (result.LastEvaluatedKey) === 'undefined' ) {
scanComplete = true;
} else {
// set the start key for the next scan to our last key
scanParams.ExclusiveStartKey = result.LastEvaluatedKey;
}
itemCountTotal += result.Count;
consumedCapacityUnitsTotal += result.ConsumedCapacityUnits;
if (!scanComplete) {
console.log("cumulative itemCount " + itemCountTotal);
console.log("cumulative capacity units " + consumedCapacityUnitsTotal);
}
}
callback(err);
});
},
// this runs when the loop is complete or returns an error
function (err) {
if (err) {
console.log('error in processing scan ');
console.log(err);
} else {
console.log('scan complete')
console.log('Total items: ' + itemCountTotal);
console.log('Total capacity units consumed: ' + consumedCapacityUnitsTotal);
}
}
);