You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CloudFormation创建DynamoDB表时出现KeySchema与属性定义不匹配错误

解决CloudFormation创建DynamoDB表时的"KeySchema与AttributeDefinitions属性数量不匹配"错误

问题原因

DynamoDB的AttributeDefinitions字段仅需要包含表主键(KeySchema内的属性)以及全局/局部二级索引的键属性,不需要提前声明所有业务属性——DynamoDB是无模式数据库,写入数据时可自由添加未预先定义的属性。你之前的代码错误地把所有业务属性都放进了AttributeDefinitions,但KeySchema只包含2个属性,两者数量不匹配,触发了CloudFormation的校验错误。

修正后的代码

将AttributeDefinitions中除主键(id和event_id)之外的属性全部移除,修改后的serverless.yml资源片段如下:

resources:
    Resources:
        usersTable:
            Type: AWS::DynamoDB::Table
            Properties:
                TableName: users
                AttributeDefinitions:
                    - 
                      AttributeName: "id"
                      AttributeType: "S"
                    - 
                      AttributeName: "event_id"
                      AttributeType: "N"
                KeySchema:
                    - 
                      AttributeName: "id"
                      KeyType: "HASH"
                    - 
                      AttributeName: "event_id"
                      KeyType: "RANGE"
                BillingMode: PAY_PER_REQUEST

补充说明

  • 如果后续需要添加全局/局部二级索引,只需要把索引的键属性添加到AttributeDefinitions中即可,不需要额外添加其他业务属性。
  • DynamoDB会自动处理写入时的新属性,无需在表定义阶段提前声明。

内容的提问来源于stack exchange,提问作者Luis Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 09:20:19