Hi I am writing a lambda function that will update the DynamoDb using boto3. In this code employee_id
is auto-generated but you have to provide last_name
or first_name
. I am doing it with if-else
. If the attribute tends to increase so does the checks. I can't keep on going with if condition. How can I tackle this what changes should I make
import boto3
import json
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Employee')
def lambda_handler(event, context):
employee_id = event['employee_id']
if 'first_name' in event and 'last_name' not in event:
first_name = event['first_name']
UpdateExpression = 'SET first_name = :val1'
ExpressionAttributeValues = {':val1': first_name }
elif 'last_name' in event and 'first_name' not in event:
last_name = event['last_name']
UpdateExpression = 'SET last_name = :val1'
ExpressionAttributeValues = {':val1': last_name}
elif 'first_name' in event and 'last_name' in event:
last_name = event['last_name']
first_name= event['first_name']
UpdateExpression = 'SET last_name = :val1, first_name = :val2'
ExpressionAttributeValues = {
':val1': last_name,
':val2': first_name
}
else:
raise ValueError("first_name and last_name not given")
update = table.update_item(
Key={
'employee_id': employee_id
},
ConditionExpression= 'attribute_exists(employee_id)',
UpdateExpression=UpdateExpression,
ExpressionAttributeValues=ExpressionAttributeValues
)
The code that I came up with but is not working
import boto3
import json
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Employee')
def lambda_handler(event, context):
employee_id = event['employee_id']
last_name= event['last_name']
first_name= event['first_name']
column = [first_name,last_name]
for i in range(0,len(column):
query = 'SET {} = :val1,:val2'.format(column[i])
response = table.update_item(
Key={
'employee_id': employee_id
},
ConditionExpression= 'attribute_exists(employee_id)',
UpdateExpression = query,
ExpressionAttributeValues={
':val1': first_name,
':val2': last_name
},
ReturnValues="UPDATED_NEW"
)