logo
post image

AWS DynamoDB : Query Multiple Items in Node.js

There is no DynamoDB API to query multiple items by primary key in a single operation. You need to make multiple requests to QueryCommand or GetItemCommand.

However the BatchGetItemCommand method can be used to batch multiple read requests in a single command. You can get up to 100 items through this command.

The below code shows the working of BatchGetItemCommand method. It involves reading from the table Posts having PostID (Number) as the primary key.

const { DynamoDBClient, BatchGetItemCommand } = require("@aws-sdk/client-dynamodb")

// init dynamodb client
const dbclient = new DynamoDBClient({ region: process.env.AWS_REGION })

// list of posts to query
const allPostIDs = [ '100', '101', '102', '103' ]

const batchResponse = await dbclient.send(new BatchGetItemCommand({
  RequestItems: {
    'Posts': {
      Keys: allPostIDs.map(id => ({ PostID: { N: id } })),
      ProjectionExpression: 'PostID'
    }
  }
}))