如果键不存在,如何插入到 DynamoDb

Tob*_*obi 19 amazon-web-services node.js amazon-dynamodb

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

我可以去

search 

if not found > insert

if found > do nothing or update (for now do nothing is fine)
Run Code Online (Sandbox Code Playgroud)

但希望有更好的方法来做到这一点。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);
      });  
Run Code Online (Sandbox Code Playgroud)

我在 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}

Run Code Online (Sandbox Code Playgroud)

Mil*_*mak 45

您可以使用单个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您只想在不存在的情况下插入,您可以使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

通过组合条件表达式更新表达式,您可以想出更复杂的方法来设置或更新项目中的属性。

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

  • 谢谢,更新似乎是我正在寻找的东西。我必须使用 dynamoDb.put(dynamodbParams).promise() 因为在我的情况下“TypeError:dynamoDb.putItem 不是函数”。用 put 就可以了。如果数据库中已有条目,我现在会收到“ConditionalCheckFailedException:条件请求失败”。 (2认同)
  • 我建议编辑此内容并让人们知道如果 ConditionExpression 解析为“false”,查询将返回 400 错误 (2认同)