Search code examples
pythonamazon-web-servicesamazon-dynamodbboto3

How to make update table if exists otherwise create


I have dynamodb table: tablename: mytable

  • schema: {'primary_key': 'name'}

Case 1

  • Insert document {'name':'john', 'age': 24} if not exists in the table otherwise update the item

Do i need to get the item from dynamo and check whether 'name exists' in the beginning to do the operation?

import boto3

def lambda_handler(event, context):
    client = boto3.resource('dynamodb')
    table = client.Table("mytable")
    try:
        table.put_item(Item= {'name':'john', 'age': 24})
    except:
        table.update_item(Item= {'name':'john', 'age': 24})

Case 2

  • update the document {'name':'john', 'age': 24} exists in the table otherwise don't create new item

Do I need to get the item from dynamo and check whether 'name exists' in the beginning to do the operation?

import boto3
def lambda_handler(event, context):
    client = boto3.resource('dynamodb')
    table = client.Table("mytable")
    try:
        table.update_item(Item= {'name':'john', 'age': 24})
    except Exception as e:
        print (e)

Solution

  • Understanding the nature of UpdateItem will help you here:

    Edits an existing item's attributes, or adds a new item to the table if it does not already exist.

    Case 1, is handled by default when using UpdateItem, as it will update if item exists and if it does not it will create a new one.

    Case 2, you will need to use a ConditionExpression where you state attribute_exists meaning if it exists the item will be updated, if it does not exist the update will fail with ConditionCheckFailedException.