【问题标题】:Update DynamoDB item via GSI通过 GSI 更新 DynamoDB 项目
【发布时间】:2017-11-22 19:50:07
【问题描述】:

我想通过 node.js 更新 AWS DynamoDB 中的现有项目。我只有要更新的项目的二级索引值。我无法访问主索引...

Id: primary index
CallId: global secondary index
CallStatus: normal field

我想只使用 CallId(不使用密钥)来更新 CallStatus。

我尝试了不同的方法,例如:

  • 扫描项目,然后使用获取的主键进行更新
  • 通过 GSI 查询然后更新
  • 有条件的更新

但是这些方法都不适合我。我假设,因为我没有正确使用它们。任何帮助表示赞赏:-)。

“扫描和更新”方法的代码示例:

  var docClient = new aws.DynamoDB.DocumentClient();
  var params = {
    TableName: 'myTable',
    FilterExpression: 'CallId = :c',
    ExpressionAttributeValues: {
      ':c': callSid
    }
  };

  docClient.scan(params, function (err, result) {
    if (err) {
      console.error("Unable to query item. Error JSON:", JSON.stringify(err));
    } else {
      console.log(result);

      // Update call status
      var params = {
        TableName: "myTable",
        Key: {
          "Id": result.Items[0].Id
        },
        UpdateExpression: "set CallStatus = :s",
        ExpressionAttributeValues: {
          ":s": callStatus
        },
        ReturnValues: "UPDATED_NEW"
      };

      docClient.update(params, function (err, data) {
        if (err) {
          console.error("Unable to update item. Error JSON:", JSON.stringify(err));
        } else {
          console.log("Update item succeeded:", JSON.stringify(data));
        }
      });
    }
  });

【问题讨论】:

  • 您是否遇到任何错误? “键:主索引”是什么意思?分区键属性名称是“Key”还是“Id”?
  • @notionquest 遗憾的是没有错误消息,主键名为 Id,我在上面的问题中更改了它,

标签: node.js amazon-dynamodb


【解决方案1】:

好的,我发现了我的错误。上述更新后的调用应该会关闭 AWS Lambda 会话,因此 DynamoDB 的异步更新从未发生...

现在工作的代码如下:

  var params = {
    TableName: 'table',
    IndexName: 'CallId-index',
    KeyConditionExpression: 'CallId = :id',
    ExpressionAttributeValues: {
      ':id': callSid
    }
  };

  docClient.query(params, function (err, result) {
    if (err) {
      console.log("Unable to query item. Error JSON:", JSON.stringify(err));
    } else {
      var params = {
        TableName: "table",
        Key: {
          "Id": result.Items[0].Id
        },
        UpdateExpression: "set CallStatus = :s",
        ExpressionAttributeValues: {
          ":s": callStatus
        },
        ReturnValues: "UPDATED_NEW"
      };
      docClient.update(params, function (err, data) {
        if (err) {
          console.log("Unable to update item. Error JSON:", JSON.stringify(err));
        } else {
          // do sth. else
        }
      });
    }
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 2022-01-20
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2019-01-08
    相关资源
    最近更新 更多