-1

I want to update the below current_date value in dynamodb (last_run_date) column based on following conditions:

current_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')

conditions:

  1. kpi_id = KPI038
  2. metric_id = 'NA'

Table name: CONFIG

partition key: kpi_id

sort key: metric_id

I want to function to update an item in python using boto3.

The code which I tried:

current_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
kpi_id = 'KPI038'
metric_id = 'NA'
return_value = "UPDATED_NEW"
table_name = "kpi_metastore_config"  
table = dynamodb.Table(table_name)

def update_dynamodb():

    try:
        response = table.update_item(
            Key={
            'kpi_id': kpi_id,
            'metric_id': metric_id
        },
        UpdateExpression="set last_run_date = :r",
        ConditionExpression=("kpi_id = :num") & ("metric_id = :number"),
        ExpressionAttributeValues={
                ':r' :  current_date,
                ':num': kpi_id,
                ':number': metric_id
            },
        ReturnValues=return_value
        )
        return response
    except Exception as error:
        logger.error(error)
        
def lambda_handler(event, context):
    response = update_dynamodb()
        
         
if __name__ == '__main__':
    lambda_handler(event,context)


Mahilan
  • 153
  • 1
  • 9
  • What have you tried and what is the problem you have encountered? – Pierre D Dec 30 '21 at 13:15
  • @PierreD I've tried the above code but not able to update the values in dynamo – Mahilan Dec 30 '21 at 13:34
  • what happens? Do you get an exception? Do you see an error message in `response`? – Pierre D Dec 30 '21 at 13:36
  • I was not sure whether my conditional expression is right or not... error: { "errorMessage": "Syntax error in module 'lambda_function': invalid syntax (lambda_function.py, line 65)", "errorType": "Runtime.UserCodeSyntaxError", "stackTrace": [ " File \"/var/task/lambda_function.py\" Line 65\n ':number': metric_id\n" ] @PierreD – Mahilan Dec 30 '21 at 13:40
  • @PierreD. Solved and I've updated the code below. Thanks!! – Mahilan Dec 30 '21 at 15:38

1 Answers1

0

ANSWER: This works

dt = datetime.now()
current_date = int(dt.strftime("%Y%m%d%H%M%S"))
kpi_id = 'KPI038'
metric_id = 'NA'
return_value = "UPDATED_NEW"

def lambda_handler(event, context):
    response = table.update_item(
        Key={
            'kpi_id': kpi_id,
            'metric_id': metric_id
        },
        UpdateExpression= "set last_run_date = :r",
        ConditionExpression= "kpi_id = :kpi AND metric_id = :metr",
        ExpressionAttributeValues={
            ':r' :  current_date,
            ':kpi': kpi_id,
            ':metr': metric_id
        },
        ReturnValues="UPDATED_NEW"
    )
    return response
Mahilan
  • 153
  • 1
  • 9