user14101761
user14101761

Reputation:

Query condition missed key schema element with a secondary index field

First time to dynamodb and serverless framework. I am trying to create a simple todo app. With todoId as primary key and userId as a secondary index. This is my definition of the table in serverless.yaml but when i try to get todo list of the user, i get the above error.

resources:
  Resources:
    GroupsDynamoDBTable:
      Type: AWS::DynamoDB::Table
      Properties:
        AttributeDefinitions:
          - AttributeName: todoId
            AttributeType: S
          - AttributeName: userId
            AttributeType: S

        KeySchema:
          - AttributeName: todoId
            KeyType: HASH
        BillingMode: PAY_PER_REQUEST
        TableName: ${self:provider.environment.TODOLIST_TABLE}
        GlobalSecondaryIndexes:
          - IndexName: ${self:provider.environment.USER_ID_INDEX}
            KeySchema:
            - AttributeName: userId
              KeyType: HASH
            Projection:
              ProjectionType: ALL

query:

  const result = await docClient
    .query({
      TableName: toDoListTable,
      KeyConditionExpression: 'userId = :userId',
      ExpressionAttributeValues: {
        ':userId': 5
      },
      ScanIndexForward: false
    })
    .promise()

Upvotes: 0

Views: 314

Answers (1)

marco.santonocito
marco.santonocito

Reputation: 1703

Since you are making a query with a global secondary index you must specify the name of the index that you want to use and the attributes to be returned in the query results.

The result should be this:

const result = await docClient
    .query({
      TableName: toDoListTable,
      IndexName: "UserIdIndex", // the name specified here: self:provider.environment.USER_ID_INDEX
      KeyConditionExpression: "userId = :userId",
      ExpressionAttributeValues: {
        ":userId": 5
      },
      ProjectionExpression: "todoId, userId",
      ScanIndexForward: false
    })
    .promise()

Upvotes: 1

Related Questions