Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}

like image 875
Tobi Avatar asked Mar 11 '19 16:03

Tobi


People also ask

Can we query DynamoDB table without primary key?

Hash key in DynamoDB The primary reason for that complexity is that you cannot query DynamoDB without the hash key. So, it's not allowed to query the entire database. That means you cannot do what you would call a full table scan in other databases.

How do I add items to DynamoDB?

In Amazon DynamoDB, you can use either the DynamoDB API, or PartiQL, a SQL-compatible query language, to add an item to a table. With the DynamoDB API, you use the PutItem operation to add an item to a table. The primary key for this table consists of Artist and SongTitle. You must specify values for these attributes.

Is Range key mandatory in DynamoDB?

There are two types of indexes in DynamoDB, a Local Secondary Index (LSI) and a Global Secondary Index (GSI). In an LSI, a range key is mandatory, while for a GSI you can have either a hash key or a hash+range key.

Can we create DynamoDB without primary key?

Primary keys are used for uniquely identifying each item in a table. No two-item can have the same primary key. In DynamoDB the primary key must be specified along with the table name while creating a table.


1 Answers

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.

like image 156
Milan Cermak Avatar answered Oct 22 '22 13:10

Milan Cermak