如何创建或更新相同的 DynamoDb 项目?

How to create or update the same DynamoDb item?

我正在使用节点 aws-sdk,我已经实现了一种在 DynamoDb 中创建或更新项目的方法。

它基于密钥 (Id) 运行良好,并且将创建或更新项目。

我的参数如下:

  let params = {
    TableName: TableName,
    Key: {
      key: args.key
    },
    UpdateExpression: `set 
        userKey = :userKey,
        content = :content`,
    ExpressionAttributeValues: {
      ':userKey': args.userKey,
      ':content': args.content
    },
    ExpressionAttributeNames: { 
    }
  };

从那以后我意识到我需要有条件地检查更新的辅助密钥以确保 userKey 匹配。

所以我补充说:

    ConditionExpression: 'userKey = :userKey',

现在创建不工作,因为它不符合条件,在一个语句中执行创建和条件更新的正确方法是什么?

我的table定义如下:

AttributeDefinitions:
      - AttributeName: key
        AttributeType: S
      - AttributeName: userKey
        AttributeType: S
      - AttributeName: timestamp
        AttributeType: N
    KeySchema:
      - AttributeName: key
        KeyType: HASH

你有两个选择-

如果您 userKey 实际上是 table 的排序键 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html),那么您可以这样更改您的参数:

Key: {
  key: args.key
  userKey: args.userKey
}

但是,如果 userKey 只是另一个属性,那么您可以这样扩展条件表达式:

ConditionExpression: 'userKey = :userKey OR attribute_not_exists(userKey)'

这将需要 userKey 符合您的预期,或者根本没有设置(upsert 就是这种情况) ).

注意 - 此 允许您更新具有 key 而没有 userKey 的项目。如果您担心这一点,那么您可以将条件扩展到:

ConditionExpression: 'userKey = :userKey OR(attribute_not_exists(key) AND attribute_not_exists(userKey))'