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]),
};
}
};