DEV Community

codeisgood
codeisgood

Posted on

DynamoDB Scan with sort

To query and retrieve 100 records from DynamoDB and order them by a sort key column in Node.js, you can use the AWS SDK for JavaScript. Make sure you have the AWS SDK installed and configured. Here's an example code snippet:

const AWS = require('aws-sdk');

AWS.config.update({
  region: 'your-dynamodb-region', // Replace with your DynamoDB region
  accessKeyId: 'your-access-key-id', // Replace with your AWS access key ID
  secretAccessKey: 'your-secret-access-key', // Replace with your AWS secret access key
});

const dynamoDB = new AWS.DynamoDB.DocumentClient();
const tableName = 'your-dynamodb-table-name'; // Replace with your DynamoDB table name
const sortKeyColumn = 'your-sort-key-column'; // Replace with your sort key column name

const params = {
  TableName: tableName,
  Limit: 100,
  ScanIndexForward: true, // Set to false for descending order
  KeyConditionExpression: '#sk > :sk', // Replace > with < for descending order
  ExpressionAttributeNames: {
    '#sk': sortKeyColumn,
  },
  ExpressionAttributeValues: {
    ':sk': '0', // Replace with your start key value
  },
};

dynamoDB.query(params, (err, data) => {
  if (err) {
    console.error('Error querying DynamoDB:', err);
  } else {
    console.log('Queried records:', data.Items);
  }
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)