0

Am a beginner learning serverless with AWS and am trying to query DynamoDB to get an image from DB using a secondary global index but it returns an error stating Query condition missed key schema element: groupId. groupId is the partition key out of the secondary global index field in the serverless.yml file. View the files below.

serverless.yml

ImagesDynamoDBTable:
      Type: AWS::DynamoDB::Table
      Properties:
        AttributeDefinitions:
          - AttributeName: groupId
            AttributeType: S
          - AttributeName: timestamp
            AttributeType: S
          - AttributeName: imageId
            AttributeType: S
        KeySchema:
          - AttributeName: groupId
            KeyType: HASH
          - AttributeName: timestamp
            KeyType: RANGE
        GlobalSecondaryIndexes:
          - IndexName: ImageIdIndexDemo
            KeySchema:
            - AttributeName: imageId
              KeyType: HASH
            Projection:
              ProjectionType: ALL
        BillingMode: PAY_PER_REQUEST
        TableName: Images-demo-${env:stage, 'dev'}

Get image function

const imagesTable = process.env.IMAGES_TABLE;
const imageIdIndex = process.env.IMAGES_ID_INDEX;

export const handler: APIGatewayProxyHandler = async (
  event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
  
  const imageId = event.pathParameters.imageId;

  const result = await docClient
    .query({
      TableName: imagesTable,
      IndexName: imageIdIndex,
      KeyConditionExpression: "imageId = :imageId",
      ExpressionAttributeValues: {
        ":imageId": imageId,
      },
    })
    .promise();

  if (result.Count !== 0) {
    return {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin": "*",
      },
      body: JSON.stringify(result.Items[0]),
    };
  }
};
  • 1
    I think [this](https://stackoverflow.com/questions/70333425/validationexception-query-condition-missed-key-schema-element-company) post answers your question. – Alex Chadyuk Feb 19 '23 at 16:23
  • Your code looks good to me. Check to be sure that there's no trailing white space in your indexes partition key. You can see this easily if you call `DescribeTable` – Leeroy Hannigan Feb 19 '23 at 16:54
  • I would check that `process.env.IMAGES_ID_INDEX` contains what you think it does. Add some logging to the Lambda function to print those environment variables. – Mark B Feb 19 '23 at 17:56

0 Answers0