javascriptnode.jsamazon-dynamodbdynamodb-queriesamazon-dynamodb-index

Query DynamoDB with array of numbers that is not the pk or sk in NodeJs?


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!


Solution

  • 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:

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

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