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)定址 — 名稱與型別在建立表格時固定。GetItemDeleteItemUpdateItem 與批次中的每個 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 中有多餘的屬性Key map 必須_只_含鍵屬性,別無其他。

如何修正

  1. 檢查表格的 key schemaDescribeTableKeySchema + AttributeDefinitions),然後讓請求的 Key 逐名稱、逐型別相符。DynoTable 的表格統計面板一眼就能看到同樣的 key schema — partition key、sort key 及其型別。
  2. 修正數字/字串不符。 若鍵是 N,傳入 JS 數字(Document Client 會 marshal 它);用低階用戶端則使用 {N: '123'},而非 {S: '123'}
  3. 提供完整的複合鍵。 複合鍵表格在每個以項目為基礎的呼叫上都需要 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 並讀取 KeySchemaAttributeDefinitions,然後讓請求的 Key 逐名稱、逐型別相符。複合鍵表格在每個以項目為基礎的呼叫上都需要 partition key 與 sort key。

相關錯誤

參考資料

最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。

不必透過主控台就能操作 DynamoDB

一款快速的 DynamoDB 桌面用戶端,可執行 DynamoDB 無法執行的真正 SQL — JOINs、GROUP BY、聚合 — 並支援視覺化編輯與使用你自己的 Bedrock 金鑰的 AI 代理。

30 天免費試用,無需信用卡 — 之後為無時間限制的免費方案。