Reputation: 1475
I am new to Lambda, SAM and DynamoDB. I want to select a record from DynamoDB Table by matching the email
attribute which is defined as the sort key in table definition in the template.yml
. When I invoke the function, all I get is this:
{"errorType":"ValidationException","errorMessage":"The provided key element does not match the schema"}
Here's the SAM template definition
CustomersTable:
Type: AWS::DynamoDB::Table
Properties:
ProvisionedThroughput:
ReadCapacityUnits: 50
WriteCapacityUnits: 100
AttributeDefinitions:
-
AttributeName: "id"
AttributeType: "S"
-
AttributeName: "email"
AttributeType: "S"
KeySchema:
-
AttributeName: "id"
KeyType: "HASH"
-
AttributeName: "email"
KeyType: "RANGE"
And here's the NodeJS code.
const { v4: uuidv4 } = require('uuid');
const dynamodb = require('aws-sdk/clients/dynamodb');
const docClient = new dynamodb.DocumentClient();
const tableCustomers = process.env.TABLE_CUSTOMERS;
exports.handlerFunction = async (event) => {
const body = JSON.parse(event.body);
const email = (body.hasOwnProperty('email')) ? body.email : null;
let emailData = await docClient.get({
TableName: tableCustomers,
Key: { email: email },
AttributesToGet: ['email']
}).promise();
const response = {
statusCode: 200,
body: JSON.stringify({ EMAILDATA: emailData }),
headers: {
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Origin": "*", // Allow from anywhere
"Access-Control-Allow-Methods": "POST" // Allow only GET request
},
};
// All log statements are written to CloudWatch
console.info(`response from: ${event.path} statusCode: ${response.statusCode} body: ${response.body}`);
return response;
}
What could be wrong in this?
Upvotes: 0
Views: 10048
Reputation: 25639
TL;DR Your query is missing a value for the partition key id
.
Your table schema has a composite primary key of id
("Hash" or "Partition" Key) and email
("Range" or "Sort" Key). docClient.get
executes a DynamoDB query operation, which finds items based on primary key values:
You must provide the name of the partition key attribute and a single value for that attribute. Query returns all items with that partition key value. Optionally, you can provide a sort key attribute and use a comparison operator to refine the search results.
Upvotes: 2