如何为DynamoDB的NodeJS AWS-SDK使用“BatchGetItem”

我正在尝试使用Node JS AWS-SDK将项目从DynamoDB表中取出。 函数getItem工作正常,但BatchGetItem更难使用。

我使用官方文档: http : //docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/Client.html#batchGetItem-property

我正在寻找如何正确使用这个function的例子,但我找不到任何。 我写的代码是:

 var params = { "RequestItems" : { "Keys" : [ {"HashKeyElement" : { "N" : "1000" } }, {"HashKeyElement" : { "N" : "1001" } } ] } } db.client.batchGetItem(params, function(err, data) { console.log('error: '+ err); console.log(jsDump.parse(data)); }); 

我得到一个SerializationException: Start of list found where not expected错误,但就我的NodeJS和JSON的专业知识去,我的语法是正确的。 但令人困惑的是: http : //docs.aws.amazon.com/amazondynamodb/latest/developerguide/API_BatchGetItems.html

在该语法示例中,您必须提供表名称。

我感到你的痛苦… AWS文档充其量是令人困惑的。 我认为这是由于基础设施老化和技术写作不好造成的。 SDK使用的nodejs和JSON语法让我想起了XML结构。

无论如何,我设法让BatchGetItem在一个小时后运行。 参数应该如下所示:

 "RequestItems": { "<TableName>": { "Keys": [ {"<HashKeyName>": {"<type>":"<hash key value>"}}, {"<HashKeyName>": {"<type>":"<hash key value>"}}, {"<HashKeyName>": {"<type>":"<hash key value>"}} ] } } 

我相信你缺less表名。 你要这个:

 var params = { "RequestItems" : { "TableName": { "Keys" : [ {"HashKeyElement" : { "N" : "1000" } }, {"HashKeyElement" : { "N" : "1001" } } ] } } } 

我使用的发电机客户端版本…经过一个小时的研究,我设法使其工作…

 var params = { RequestItems: { // map of TableName to list of Key to get from each table Music: { Keys: [ // a list of primary key value maps { Artist: 'No One You Know', SongTitle:'Call Me Today' // ... more key attributes, if the primary key is hash/range }, // ... more keys to get from this table ... ], AttributesToGet: [ // option (attributes to retrieve from this table) 'AlbumTitle', // ... more attribute names ... ], ConsistentRead: false, // optional (true | false) }, // ... more tables and keys ... }, ReturnConsumedCapacity: 'NONE', // optional (NONE | TOTAL | INDEXES) }; docClient.batchGet(params, function(err, data) { if (err) ppJson(err); // an error occurred else ppJson(data); // successful response }); 

试试这个,但没有经过testing:

 var params = { TableName: "tableName", RequestItems : { Keys : [ { HashKeyElement : { N : "1000" } }, { HashKeyElement : { N : "1001" } } ] } } 

尝试这个:

 db.client.batchGetItem( {"RequestItems":{ "TableName":{ "Keys":[ {"HashKeyElement" : {"N":"1000"}}, {"HashKeyElement" : {"N":"1001"}} ] } } }, function(err, result){ //handle error and result here }); 

在你的情况下,正确的答案应该是:

 var params = { "RequestItems": { "<table_name>": { "Keys": [ {"HashKeyElement" : { "N" : "1000" } }, {"HashKeyElement" : { "N" : "1001" } } ] } } } 

我在这里尝试了所有的解决scheme,没有一个为我工作,这可能意味着NodeJS库已经得到了更新。 引用他们更好的书面文档 ,你应该可以这样做:

 var params = { RequestItems: { 'Table-1': { Keys: [ { HashKey: 'haskey', NumberRangeKey: 1 } ] }, 'Table-2': { Keys: [ { foo: 'bar' }, ] } } }; var docClient = new AWS.DynamoDB.DocumentClient(); docClient.batchGet(params, function(err, data) { if (err) console.log(err); else console.log(data); }); 

具体而言,提供这种types不再是必需的。