Search code examples
javascriptamazon-web-servicesamazon-dynamodbaws-sdkdynamodb-queries

Replace DynamoDB Scan operation with Query


I am using DynamoDB Scan operations to get all items from DynamoDB table. The code is as below:

"use strict";
const AWS = require("aws-sdk");

module.exports.get = async () => {
  try {
    const dynamodb = new AWS.DynamoDB.DocumentClient();

    console.log("getting items");

    const params = {
      TableName: "ProductsTable",
    };

    const result = await dynamodb.scan(params).promise();

    console.log("got results", result.Items);

    return { body: JSON.stringify(result.Items) };
  } catch (error) {
    console.error(error);
    return {
      status: 500,
      message: error.message,
      body: JSON.stringify(error),
    };
  }
};

But scan is not an efficient operation an is not recommended. How can I use Query operation to get all items from the table ? Can I replace scan Operation with Query to get all items ? Is there any other way to get all items from the table ? Please let me know.

thanks


Solution

  • Scan is only inefficient because it has to look at everything.

    If you want to return everything anyways, there's no reason not to use Scan.

    In fact, you could use the built in parallel scan to speed up the process.

    Query() has to be run in parallel manually by your application code.