Error: The provided key element does not match the schema

Error: The provided key element does not match the schema

我是 Lambda、SAM 和 DynamoDB 的新手。我想通过匹配 email 属性来 select 来自 DynamoDB Table 的记录,该属性在 template.yml 的 table 定义中定义为排序键。当我调用该函数时,我得到的是:

{"errorType":"ValidationException","errorMessage":"The provided key element does not match the schema"}

这是 SAM 模板定义


  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"

这是 NodeJS 代码。

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;
}

这有什么问题吗?

TL;DR 您的查询缺少分区键值 id

您的 table 架构有一个 composite primary key of id ("Hash" or "Partition" Key) and email ("Range" or "Sort" Key). docClient.get executes a DynamoDB query operation,它根据主键值查找项目:

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.