【问题标题】:How to insert to DynamoDb just if the key does not exist仅当密钥不存在时如何插入到 DynamoDb
【发布时间】:2023-04-07 05:23:01
【问题描述】:

我只想向 DynamoDb 添加 id + 一些值。如果 id 已经存在,它应该什么都不做或更新

我可以去

search 

if not found > insert

if found > do nothing or update (for now do nothing is fine)

但希望有更好的方法来做到这一点。 id 应该是检查的关键。

这是节点中的代码:

const dynamodbParams = {
        TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
        Item: {
          id: userId,
          createdAt: timestamp
        },
      };

      dynamoDb.put(dynamodbParams).promise()
      .then(data => {
        console.log('saved: ', dynamodbParams);
      })
      .catch(err => {
        console.error(err);
      });  

我在 yml 中使用它。不知道yml中是否有设置这个选项

resources:
  Resources:
    DynamoDbTableExpenses:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          -
            AttributeName: id
            AttributeType: S
          -  
            AttributeName: createdAt
            AttributeType: N
        KeySchema:
          -
            AttributeName: id
            KeyType: HASH
          -
            AttributeName: createdAt
            KeyType: RANGE            
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.DYNAMODB_TABLE_BLICKANALYTICS}

【问题讨论】:

    标签: node.js amazon-web-services amazon-dynamodb


    【解决方案1】:

    您可以通过一个 UpdateItem 操作完成所有操作:

    const dynamodbParams = {
        TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
        Key: {id: userId},
        UpdateExpression: 'SET createdAt = if_not_exists(createdAt, :ca)',
        ExpressionAttributeValues: {
            ':ca': {'S': timestamp}
        }
    };
    dynamoDb.updateItem(params, function(err, data) {
        if (err) {
            console.log(err, err.stack);
        } else {
            console.log(data);
        }
    }
    

    如果您只想在不存在的情况下进行插入,您可以使用PutItem 轻松做到这一点:

    const dynamodbParams = {
        TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
        Item: {
            id: userId,
            createdAt: timestamp
        },
        ConditionExpression: 'attribute_not_exists(id)'
    };
    dynamodb.putItem(params, function(err, data) {
        if (err) {
            console.log(err, err.stack);
        } else {
            console.log(data);
        }
    }
    

    通过组合condition expressionsupdate expressions,您可以想出更复杂的方法来设置或更新项目中的属性。

    注意我还没有完全测试代码,所以如果有任何错误请评论,但它应该可以工作。

    【讨论】:

    • 感谢更新似乎是我正在寻找的东西。在我的情况下,我不得不使用 dynamoDb.put(dynamodbParams).promise() 因为“TypeError:dynamoDb.putItem 不是函数”。用 put 就可以了。如果数据库中已有条目,我现在会收到“ConditionalCheckFailedException:条件请求失败”。
    • 可以提一下,这是一种标准的数据库方法,叫做“upsert”。它位于 Postgres 等较旧的数据库中。
    • 我建议编辑它并让人们知道如果 ConditionExpression 解析为 false,查询将返回 400 错误
    猜你喜欢
    • 2019-09-16
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 2017-04-21
    • 2016-05-07
    相关资源
    最近更新 更多