This is my API request body (Array of numbers):
{
"userIds": [10,11,12, 20]
}
Where the usersIds in DB is a number type and it’s not the primary or secondary keys.
I need to query DynamoDB and get the details of these users in NodeJs please.
I tried:
const keys: { userIds: number }[] = userIds.map(id => ({ userID: id }))
const params: BatchGetCommandInput = {
RequestItems: {
[this.tableName]: {
Keys: keys,
ProjectionExpression: projectionExpression
}
}
};
return ResultAsync.fromPromise(this.dynamoDocumentClient.batchGet(params),
I think that batchGet needs the keys to be passed so doesn’t work in this case!
2
Answers
It’s best you make an index and have that attribute as a key to have some efficiency.
But in your current setup you’d need to use a Scan with a FilterExpression on the values that you require, be forewarned it make seem quick and efficient with a small amount of data but it doesn’t scale well.
In this situation, you will need to perform a
Scan
operation over your table which is not recommended for big tables and amount of data.There are a few solutions:
As the previous reply suggested – add a secondary index.
Because your DynamoDB table is already created you can only add a Global secondary index (GSI) and not Local secondary index (LSI). It will give you the ability to perform queries on the user ids over this table.
Usually it will be best practice to define the
UserId
as the primary key. Maybe you can adjust the architecture and build a table using UserId as the primary key + your sort key, instead of the current sort key you’ve got, and create GSI/LSI for it if you need.