简体   繁体   English

在 DynamoDB 中按日期获取项目导致 ValidationException

[英]GetItem by date in DynamoDB results in ValidationException

I need a data filtered by date but I am getting an error我需要按日期过滤的数据,但出现错误

Error ValidationException: The provided key element does not match the schema错误 ValidationException:提供的关键元素与模式不匹配

My table has a primary key (only partition key) of id .我的表有一个主键(只有分区键) id

async function fetchDatafromDatabase() {  // get method fetch data from dynamodb
    var date = todayDate();
    var params = {
        TableName: table,
        Key: {
            "date": date
        }
    };

    let queryExecute = new Promise((res, rej) => {
        dynamoDB.get(params, function (err, data) {
            if (err) {
                console.log("Error", err);
                rej(err);
            } else {
                console.log("Success! get method fetch data from dynamodb");
                res(JSON.stringify(data, null, 2));
            }
        });
    });
    const result = await queryExecute;
    console.log(result);
}

For getting an item from DynamoDB, we must pass primary key, in this case, its just partition key 'id' (assuming it is numeric and storing epoc date)要从 DynamoDB 获取项目,我们必须传递主键,在本例中,它只是分区键“id”(假设它是数字并存储 epoc 日期)

var documentClient = new AWS.DynamoDB.DocumentClient();
var date = Date.now();
console.log("date", date);
var params = {
  TableName: "test2",
  Key: {
    id: date,
  },
};
documentClient.get(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});

Complete Example to put an item and get it.完成示例以放置物品并获得它。

var documentClient = new AWS.DynamoDB.DocumentClient();
var date = Date.now();
documentClient.put(
  {
    TableName: "test2",
    Key: {
      id: date,
    },
  },
  function (err, data) {
    if (err) console.log("err", err);
    if (data) {
      documentClient.get(
        {
          TableName: "test2",
          Key: {
            id: date,
          },
        },
        function (errGet, dataGet) {
          if (errGet) {
            console.log("Error", errGet);
          } else {
            console.log("Success", dataGet);
          }
        }
      );
    }
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM