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

使用AWS DynamoDB JS SDK仅通过分区键查询数据报错问题

解决DynamoDB仅按分区键查询的报错问题

问题原因

GetCommand的作用是获取单条完全匹配主键的数据,你的表定义了分区键+排序键的复合主键,必须同时提供两个键的取值才能匹配,只传分区键不符合主键结构,因此会报"The provided key element does not match the schema"错误。

正确解决方案

如果要查询某个分区键下的所有数据,应该使用QueryCommand替代GetCommand,修改代码如下:

case "GET /items/{id}":
        const queryResult = await dynamo.send(
          new QueryCommand({
            TableName: tableName,
            KeyConditionExpression: "id = :idVal",
            ExpressionAttributeValues: {
              ":idVal": event.pathParameters.id
            }
          })
        );
        body = queryResult.Items; // 返回该id对应的所有数据列表
        break;

补充说明

  • 如果确实需要获取单条数据,必须在Key中同时传入分区键和排序键的具体值,示例如下:
    new GetCommand({
      TableName: tableName,
      Key: {
        id: event.pathParameters.id,
        timestamp: "2024-05-20T12:00:00" // 替换为目标数据的实际排序键值
      }
    })
    
  • QueryCommand会返回对应分区键下的所有数据,完全匹配你“仅通过分区键查询”的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:02:09