skip to Main Content

I want to insert an item on a GSI, however the AWS SDK library doesn’t seem to cooperate.

This is the relevant code:

const updateLeaderbordAggreagte = async (documentClient, leaderboardPK, tournamentPoints, participant) => {

    try {
        const putLeaderboardScore = new PutItemCommand({
            TableName: process.env.TABLE_NAME,
            IndexName: 'GSI1',
            Item: {
                'GSI1-PK': leaderboardPK,
                'GSI1-SK': `${tournamentPoints.padStart(5, '0')}#${participant}`,
            }
        })
        await documentClient.send(putLeaderboardScore)
    } catch (error) {
        console.error('Error adding leaderboard: ', error)
    }
}

When I run the code, I don’t get any error, but the items don’t get inserted. The argument IndexName is not even suggested by intellisense, I tried to use it because that is how you do it with boto3.

For reference, this is the table and index code:

this.leaderboardsTable = new dynamodb.Table(this, `${props.STAGE}leaderboardsTable`, {
            tableName: `${props.STAGE}Leaderboards`,
            partitionKey: { name: 'PK', type: dynamodb.AttributeType.STRING },
            sortKey: { name: 'SK', type: dynamodb.AttributeType.STRING },
            removalPolicy: cdk.RemovalPolicy.DESTROY,
            billingMode: dynamodb.BillingMode.PROVISIONED,
            stream: dynamodb.StreamViewType.NEW_AND_OLD_IMAGES
        })

        this.leaderboardsTable.addGlobalSecondaryIndex({
            indexName: 'GSI1',
            partitionKey: { name: 'GSI1-PK', type: dynamodb.AttributeType.STRING },
            sortKey: { name: 'GSI1-SK', type: dynamodb.AttributeType.STRING },
            projectionType: dynamodb.ProjectionType.KEYS_ONLY
        })

2

Answers


  1. Chosen as BEST ANSWER

    I think I just answered myself, my bad.

    The issue was this: I was trying to project attributes that don't exist.

    partitionKey: { name: 'GSI1-PK', type: dynamodb.AttributeType.STRING },
    sortKey: { name: 'GSI1-SK', type: dynamodb.AttributeType.STRING },
    

    the names of the attribute don't exist in my table. In my case, I should use as partitionKey 'SK' and as sortKey 'points'. Adjust it to match your case.

    Have a nice day :)


  2. In DynamoDB you don’t write to an index, you write to the base table and the data is async replicated to the index. That also means you must always know the keys or your base table while writing data.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search