通过aws dynamodb上的分区键获取行

get row by partition key on aws dynamodb

我正在尝试 return 一行 ID(分区键)

  var db = new AWS.DynamoDB.DocumentClient();
  const id = "123";
  var queryParams = {
    TableName: "students",
    IndexName: "id",
    KeyConditionExpression: "id = :id",
    ExpressionAttributeValues: {
      ":id": id,
    },
  };

  const query = db.query(queryParams).promise();

但是抛出了这个错误:

ValidationException: 1 validation error detected: Value 'id' at 'indexName' failed to satisfy constraint: Member must have length greater than or equal to 3

分区键不够获取记录吗?我很困惑分区键与索引名称不同?

我也试过

  var db = new AWS.DynamoDB.DocumentClient();
  var queryParams = {
    TableName: "students",
    Key: {
      id: "123",
    },
  };

  const query = db.get(queryParams).promise();

它return什么都没有

您实际上没有名为 id 的索引。查询分区键时不需要提供索引。只需删除这一行:

IndexName: "id",

另外请注意,table 和索引名称的长度都必须为 3-255 个字符(含),这解释了您看到的错误消息。

以下代码(查询和获取)对我来说工作正常:

const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-east-1' });
const db = new AWS.DynamoDB.DocumentClient();

const ID = "123";
const TABLE_NAME = "students";

const getParams = {
  TableName: TABLE_NAME,
  Key: {
    id: ID,
  },
};

const queryParams = {
  TableName: TABLE_NAME,
  KeyConditionExpression: "id = :id",
  ExpressionAttributeValues: {
    ":id": ID,
  },
};

(async () => {
  const rc1 = await db.get(getParams).promise();
  console.log('get rc:', rc1);

  const rc2 = await db.query(queryParams).promise();
  console.log('query rc:', rc2);
})();