Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

amazon dynamodb - 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()
question from:https://stackoverflow.com/questions/65872319/query-condition-missed-key-schema-element-with-a-secondary-index-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...