I have dynamodb table: tablename: mytable
Case 1
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
don't create
new itemDo 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)
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
.