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
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.
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.
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.