【问题标题】:Update dynamoDB column using condition expression使用条件表达式更新 dynamoDB 列
【发布时间】:2019-07-30 14:53:53
【问题描述】:

我想使用相当于 sql 的 like (%) 条件的条件更新 dynamoDB 表的现有项

opIdUserId 状态

  • 123-U1 进行中
  • 345-U2 进行中
  • 123-U3 暂停

我的 dynamodb 中的 opIdUserId 是 主分区键。我想将 opIdUserId 字段值从 123 开始或包含 123 的状态更新为 COMP。

这是我目前正在尝试的,但经过研究发现我无法使用 KeyConditionExpression 进行更新。

const AWS = require('aws-sdk'); 
 const docClient = new AWS.DynamoDB.DocumentClient({region: 'eu-west-1'}); 
 var table = "tablename";

exports.handler = function(event, context, callback){
    var params = {
    TableName: table,

    KeyConditionExpression: "begins_with(opIdUserId, :i)",
    UpdateExpression: "set operationStatus = :o",
    ExpressionAttributeValues:{
        ":o":"COMP",
        ":i":"123-"
    },
    ReturnValues:"UPDATED_NEW"
};
docClient.update(params, function(err, data) {
    if (err) {

         callback(err, null);
    } else {
         callback(null,data); 

    }
});
 } 

请建议我如何在特定条件下更新我在 dynamoDB 中的项目。

【问题讨论】:

  • 您应该扫描与您的关键条件表达式匹配的所有项目,然后逐项更新它们。

标签: amazon-web-services lambda aws-lambda amazon-dynamodb dynamodb-queries


【解决方案1】:

您应该使用KeyConditionExpression 在表上为以123 开头的项目创建queryquery

var params = {
  TableName: table,
  KeyConditionExpression: "id = :id AND begins_with(opIdUserId, :opIdUserId)",
  UpdateExpression: "set operationStatus = :operationStatus",
  ExpressionAttributeValues:{
    ":opIdUserId":"123-",
    ":id": "something"
  }
};

var documentClient = new AWS.DynamoDB.DocumentClient();

documentClient.query(params, function(err, data) {
   if (err) console.log(err);
   else console.log(data);
});

请记住,您不能在partition key 上使用BEGINS_WITH 运行查询,只能在sort key 上运行。

然后,您可以使用partition and sort key 对每个单独的元素使用update 方法,更新operationStatus

如果您向我提供有关您的DynamoDB 表的信息,我可以帮助您创建GSI

【讨论】:

    猜你喜欢
    • 2016-04-13
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多