Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
856 views
in Technique[技术] by (71.8m points)

node.js - How to insert to DynamoDb just if the key does not exist

I want to add id + some values to a DynamoDb just once. If the id exists already it should do nothing or update

I can go with

search 

if not found > insert

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

But hopfully there is a better way to do it. The id should be the key to check for.

That's the code in node:

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);
      });  

I use this in yml. Don't know if there are options to set this up in 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}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do the whole thing with a single UpdateItem operation:

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);
    }
}

If you only want to do insert if not exists, you can easily do that with 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);
    }
}

You can come up with more complex ways how to set or update attributes in an item by combining the condition expressions and update expressions.

Note I have not fully tested the code, so please comment if there's any error, but it should work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...