使用多条件表达式的 AWS DynamoDB 更新项目

AWS DynamoDB update item using multiple condition expression

我有一个 DynamoDB Table,我希望使用多条件表达式更新特定值。我们能做到吗? 我的代码:-

        dynamodb = session.resource('dynamodb')
        table = dynamodb.Table('gold-images')
        response = table.update_item(
            Key={
                    'AccountRegionOS' : AccOs,
                    'CreationDate' : cred
                },
            UpdateExpression="set is_active = :r",
            ConditionExpression="CreationDate < :num",
            ExpressionAttributeValues={
                ':num' : last_month,
                ':r': "No"
            },
            ReturnValues="UPDATED_NEW"

我希望条件表达式为

        dynamodb = session.resource('dynamodb')
        table = dynamodb.Table('gold-images')
        response = table.update_item(
            Key={
                    'AccountRegionOS' : AccOs,
                    'CreationDate' : cred
                },
            UpdateExpression="set is_active = :r",
            ConditionExpression=("CreationDate < :num") & ("AMIID = :ami"),
            ExpressionAttributeValues={
                ':num' : last_month,
                ':r': "No",
                ':ami' : i
            },
            ReturnValues="UPDATED_NEW"

条件表达式为字符串,逻辑运算符为ANDORNOT。因此,您需要删除外括号并将 & 替换为 AND:

ConditionExpression = "CreationDate < :num AND AMIID = :ami"

参见Condition Expressions

对于那些使用 AWS lambda 来更新他们的 DynamoDB table 的人,这里有一个例子:

const AWS = require('aws-sdk');
const documentClient = new AWS.DynamoDB.DocumentClient();

const proxyResponseBody = ((statusCode, result) => {
  let response = {
    statusCode: statusCode,
    body: JSON.stringify({ result: result }),
    headers: { "Access-Control-Allow-Origin": "*" }
  }
  return response;
})

exports.handler = async (event) => {
  // TODO implement
  console.log(event);
  const jsonData = JSON.parse(event.body)
  const userId = event.requestContext.authorizer.claims.sub
  const params = {
    TableName : "Some_Table_Name",
    Key: {
      "ID": jsonData.tableKeyId,
    },
    UpdateExpression: "set someField = :newValue",
    ConditionExpression: "userId = :userId",
    ExpressionAttributeValues: {
      ":newValue": jsonData.newValue,
      ":userId": userId,
    },
  }
  console.log(params)
  let result = null
  let statusCode = null
  result = await documentClient.update(params, function(err, data) {
    if (err) {
      console.log(err)
      statusCode = 500
      return err
    }else {
      console.log(data);
      statusCode = 200
      return data
    }
  }).promise();
  return proxyResponseBody(statusCode, result)
};

table 由分区键“ID”、“userId”和“fieldName”组成。此功能是更新具有匹配用户ID的行的“fieldName”的值。