skip to Main Content

I have a dynamoDB table with a HASH key and a SORT key.

**Now I have a situation where I need to get table contents based on the HASH key only and it will return an array of items. **

I am able to do this with .query() operation

    const params = {
      KeyConditionExpression: `${key} = :${key}`,
      ExpressionAttributeValues: {
        [`:${key}`]: value,
      },
      TableName: tableName,
    }
    const result = await this.dynamodb.query(params).promise()

Now the question I have is around ‘best practices’ and ‘cost’.

GOAL: I need to get many items based on one key.

QUESTION: Is this the best way to do it? Or am I performing a full scan every time I query?

NOTE: I have knowledge on GSI/LSI but since I’m querying on the HASH key only, I think making another Index is redundant?

    const params = {
      KeyConditionExpression: `${key} = :${key}`,
      ExpressionAttributeValues: {
        [`:${key}`]: value,
      },
      TableName: tableName,
    }
    const result = await this.dynamodb.query(params).promise()

2

Answers


  1. A Query is an efficient operation. It does not do a full table scan, it only reads the items related to the provided hash key.

    If you want it to be more efficient you can provide a condition on the sort key to help filter the result set, such as SK begins_with(ABC).

    And you are correct that an index is not required, as you are already as efficient as you can be.

    Login or Signup to reply.
  2. Replace ‘us-east-1‘, ‘YourTableName‘, ‘YourHashKeyName‘, and ‘YourHashKeyValue‘ with appropriate values for your DynamoDB setup. Make sure you have the AWS SDK installed (npm install aws-sdk) and properly configured with your AWS credentials.

    // write it in the terminal to be sure that code does work properly
    npm install aws-sdk
    
    // to check if u have this library and install it before
    aws-sdk --v

    Main example of code. This code defines a function queryItems that takes the table name, HASH key name, and HASH key value as parameters. It constructs the necessary params object and uses dynamodb.query() to retrieve the items based on the provided HASH key. The retrieved items are returned as an array.

    const AWS = require('aws-sdk');
    
    AWS.config.update({
      region: 'us-east-1', // Replace with your desired region
      // Other AWS configuration options as needed
    });
    
    const dynamodb = new AWS.DynamoDB();
    
    async function queryItems(tableName, hashKeyName, hashKeyValue) {
      const params = {
        TableName: tableName,
        KeyConditionExpression: `${hashKeyName} = :hashKeyValue`,
        ExpressionAttributeValues: {
          ':hashKeyValue': { S: hashKeyValue }, // Adjust data type based on your schema
        },
      };
    
      try {
        const result = await dynamodb.query(params).promise();
        return result.Items;
      } catch (error) {
        console.error('Error querying DynamoDB:', error);
        throw error;
      }
    }
    
    // example how to use this code
    (async () => {
      try {
        const tableName = 'YourTableName';
        const hashKeyName = 'YourHashKeyName';
        const hashKeyValue = 'YourHashKeyValue';
    
        const items = await queryItems(tableName, hashKeyName, hashKeyValue);
        console.log('Retrieved items:', items);
      } catch (error) {
        console.error('Error:', error);
      }
    })();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search