ValidationException: The provided key element does not match the schema
TL;DR — 你傳入的鍵與表格宣告的 key schema 不對齊:屬性名稱錯誤、型別錯誤(字串對數字),或缺少 sort key。讓請求的鍵精確符合 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 項目都以其primary key(partition key,選擇性加上 sort key)定址 — 名稱與型別在建立表格時固定。GetItem、DeleteItem、UpdateItem 與批次中的每個 Key 都必須提供確切的那個鍵:如 API 參考所述,「對 primary key,你必須提供所有屬性」。當提供的鍵不符時,這個錯誤就會觸發。它是 ValidationException(HTTP 400)且不可重試 — 在鍵更正前,相同的請求都會失敗。
為什麼會發生
- 屬性名稱錯誤 — 你傳入
id,但表格的鍵是pk。 - 型別錯誤 — 鍵定義為 Number(
N),但你送出了 String("123"),反之亦然。對 DynamoDB 而言"123"與123是不同的鍵。 - 缺少 sort key — 表格有複合鍵,但你的
Key只有 partition key(或在僅 partition 的表格上多了 sort key)。 Key中有多餘的屬性 —Keymap 必須_只_含鍵屬性,別無其他。
如何修正
- 檢查表格的 key schema(
DescribeTable→KeySchema+AttributeDefinitions),然後讓請求的Key逐名稱、逐型別相符。DynoTable 的表格統計面板一眼就能看到同樣的 key schema — partition key、sort key 及其型別。 - 修正數字/字串不符。 若鍵是
N,傳入 JS 數字(Document Client 會 marshal 它);用低階用戶端則使用{N: '123'},而非{S: '123'}。 - 提供完整的複合鍵。 複合鍵表格在每個以項目為基礎的呼叫上都需要 partition 與 sort key。
範例
// 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" 是什麼原因造成的? 你請求中的鍵與表格宣告的 key schema 不對齊:屬性名稱錯誤、型別錯誤(Number 鍵被當作 String 送出,反之亦然)、複合鍵表格上缺少 sort key,或 Key map 中有多餘的非鍵屬性。
我要如何檢查表格的 key schema?
呼叫 DescribeTable 並讀取 KeySchema 加 AttributeDefinitions,然後讓請求的 Key 逐名稱、逐型別相符。複合鍵表格在每個以項目為基礎的呼叫上都需要 partition key 與 sort 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 官方文件。