Search code examples
amazon-web-servicesamazon-dynamodbdynamodb-queriesamazon-dynamodb-index

Query dynamodb table by primary key


I'm having problems creating a simple query request. Here they show an example of how to do a query using the global secondary index. Now in this case, I just have the primary key, and I'd like to query from my table. This is currently the error that I'm getting:

Query condition missed key schema element: id

Here is what I'm currently trying:

var params = {
  TableName : "XactRemodel-7743-DynamoDBImagesTable-8183NQ0UG0Y5",
  KeyConditionExpression: 'HashKey = :hkey',
  ExpressionAttributeValues: {
    ':hkey': event.projectId
  }
};
documentClient.query(params, function(err, data) {
   if (err) {
     console.log(err)
   } else {
     console.log(data);
   }
});

I know that in the example they used "indexName" which corresponds to the secondary indexes name. They Key Schema doesn't seem to have such an attribute.

This is what my table looks like defined in a YAML file:

DynamoDBImagesTable:
Type: AWS::DynamoDB::Table
Properties:
  BillingMode: PAY_PER_REQUEST
  SSESpecification:
    SSEEnabled: true
  PointInTimeRecoverySpecification:
    PointInTimeRecoveryEnabled: true
  AttributeDefinitions:
    - AttributeName: id
      AttributeType: S
    - AttributeName: companyId
      AttributeType: S
    - AttributeName: lastModified
      AttributeType: S
  KeySchema:
    - AttributeName: id
      KeyType: HASH
  GlobalSecondaryIndexes:
    - IndexName: companyId-index
      KeySchema:
        - AttributeName: companyId
          KeyType: HASH
        - AttributeName: lastModified
          KeyType: RANGE
      Projection:
        ProjectionType: ALL

What am I missing?


Solution

  • This is trying to query by primary key named HashKey:

    KeyConditionExpression: 'HashKey = :hkey',
    

    However your primary key is named id which is what the error message is pointing out. So change that line to:

    KeyConditionExpression: 'id = :hkey',