ValidationException: The provided key element does not match the schema
TL;DR — 你传入的键与表声明的键模式对不上:属性名错误、类型错误(字符串对数字),或缺少排序键。让请求的键与 KeySchema + AttributeDefinitions 精确匹配。
含义
# what the engine actually returns, reproduced against DynamoDB Local — GetItem with pk passed as N where the schema declares S:
ValidationException: One or more parameter values were invalid: Type mismatch for key每个 DynamoDB 项目都由它的主键寻址——一个分区键,可选地加上一个排序键——名称和类型在表创建时固定。GetItem、DeleteItem、UpdateItem 以及批次中的每个 Key 都必须提供恰好那个键:正如 API 参考所述,"对于主键,你必须提供所有的属性。" 当提供的键不匹配时,这个错误就会触发。它是一个 ValidationException(HTTP 400)且不可重试——在键被修正之前,同样的请求会一直失败。
为什么会发生
- 属性名错误——你传入了
id,但表的键是pk。 - 类型错误——键定义为 Number(
N),但你发送了一个 String("123"),或反之。对 DynamoDB 而言"123"和123是不同的键。 - 缺少排序键——表有一个复合键,但你的
Key只有分区键(或者在一个仅分区键的表上多了一个排序键)。 Key中有多余的属性——Keymap 必须_只_包含键属性,别无其他。
如何修复
- 检查表的键模式(
DescribeTable→KeySchema+AttributeDefinitions),然后让请求的Key逐名称、逐类型地匹配。DynoTable 的表统计面板一眼就能看到同样的键模式——分区键、排序键及其类型。 - 修正数字/字符串的不匹配。 如果键是
N,就传一个 JS 数字(文档客户端会 marshal 它);用底层客户端时用{N: '123'},而不是{S: '123'}。 - 提供完整的复合键。 复合键表在每个基于项目的调用上都需要分区键和排序键。
示例
// Table: Users, key = { pk (S) HASH, sk (S) RANGE }
import {DynamoDBClient} from '@aws-sdk/client-dynamodb';
import {DynamoDBDocumentClient, GetCommand} from '@aws-sdk/lib-dynamodb';
const doc = DynamoDBDocumentClient.from(new DynamoDBClient({}));
// both key parts, correct names/types
await doc.send(new GetCommand({TableName: 'Users', Key: {pk: 'USER#1', sk: 'PROFILE'}}));
// missing sort key → "provided key element does not match the schema"
// await doc.send(new GetCommand({TableName: 'Users', Key: {pk: 'USER#1'}}));常见问题
是什么导致了 "The provided key element does not match the schema"? 你请求中的键与表声明的键模式对不上:一个错误的属性名、一个错误的类型(一个 Number 键作为 String 发送或反之)、一个复合键表上缺失的排序键,或者 Key map 中多余的非键属性。
我如何检查我表的键模式?
调用 DescribeTable 并读取 KeySchema 加 AttributeDefinitions,然后让请求的 Key 逐名称、逐类型地匹配。复合键表在每个基于项目的调用上都需要分区键和排序键。
相关错误
- Query condition missed key schema element
- ValidationException (overview)
- 学习:DynamoDB data types · Composite primary keys
参考资料
- GetItem — Amazon DynamoDB API Reference
- Core components of Amazon DynamoDB — Amazon DynamoDB Developer Guide
- Constraints in Amazon DynamoDB — Amazon DynamoDB Developer Guide
- Error handling with DynamoDB — Amazon DynamoDB Developer Guide
最后核实于 2026-07-13,依据上方链接的 AWS 官方文档。