Tobi
Tobi

Reputation: 1902

Serverless and GlobalSecondaryIndexes - Query condition missed key schema element with dynamodb

I tried to create GlobalSecondaryIndexes with serverless and query for it later. I get an

Query condition missed key schema element: id

error doing this, which makes sense but my plan is to query for all elements at a specific day.

  var params = {
    TableName: process.env.DYNAMODB_TABLE_LIGHTHOUSE,
    KeyConditionExpression: 'fetchDate = :fetchDate',
    ExpressionAttributeValues: {
      ':fetchDate': { S: '2019-05-13' }
    }
  };

  const dbResult = await dynamoDb.query(params).promise()
  console.log(dbResult)

This is the serverless part for the dynamodb. Probably here is something missing?

DynamoDbTableExpenses:
  Type: 'AWS::DynamoDB::Table'
  Properties:
    AttributeDefinitions:
      -
        AttributeName: id
        AttributeType: S
      -
        AttributeName: fetchDate
        AttributeType: S
    KeySchema:
      -
        AttributeName: id
        KeyType: HASH
    GlobalSecondaryIndexes:
      - IndexName: fetchDateIndex
        KeySchema:
          - AttributeName: fetchDate
            KeyType: HASH
        Projection:
          ProjectionType: ALL
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
    ProvisionedThroughput:
      ReadCapacityUnits: 1
      WriteCapacityUnits: 1
    TableName: ${self:provider.environment.DYNAMODB_TABLE_LIGHTHOUSE}

In the web frontend it looks like this:

enter image description here

Upvotes: 0

Views: 522

Answers (1)

A.Khan
A.Khan

Reputation: 4002

You need to add the IndexName attribute. Try:

var params = {
    TableName: process.env.DYNAMODB_TABLE_LIGHTHOUSE,
    IndexName: 'fetchDateIndex',
    KeyConditionExpression: 'fetchDate = :fetchDate',
    ExpressionAttributeValues: {
      ':fetchDate': '2019-05-13'
    }
};

See API Query

The Query operation finds items based on primary key values. You can query any table or secondary index that has a composite primary key (a partition key and a sort key).

Upvotes: 2

Related Questions