如果密钥不存在,如何插入DynamoDb

问题描述 投票:0回答:2

我想将id +一些值添加到DynamoDb一次。如果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
2个回答
3
投票

你可以用一个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,提出更复杂的方法来设置或更新项目中的属性。

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


0
投票

尝试使用GetItem请求查看是否已指定userId - 如果存在,则不需要dynamoDb.put(dynamodbParams).promise()调用

© www.soinside.com 2019 - 2024. All rights reserved.