【问题标题】:how to update a value in dynamodb table based on condition using python and boto3?如何使用python和boto3根据条件更新dynamodb表中的值?
【发布时间】:2021-12-30 10:56:15
【问题描述】:

我想根据以下条件更新 dynamodb (last_run_date) 列中的以下 current_date 值:

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

条件:

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

表名:CONFIG

分区键:kpi_id

排序键:metric_id

我想使用 boto3 更新 python 中的项目。

我试过的代码:

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)


【问题讨论】:

  • 你尝试了什么,遇到了什么问题?
  • @PierreD 我已经尝试了上面的代码,但无法更新发电机中的值
  • 会发生什么?你有例外吗?您是否在 response 中看到错误消息?
  • 我不确定我的条件表达式是否正确......错误:{“errorMessage”:“模块'lambda_function'中的语法错误:无效语法(lambda_function.py,第65行)” , "errorType": "Runtime.UserCodeSyntaxError", "stackTrace": [" File \"/var/task/lambda_function.py\" Line 65\n ':number': metric_id\n" ] @PierreD
  • @PierreD。解决了,我已经更新了下面的代码。谢谢!!

标签: python python-3.x amazon-dynamodb boto3 dynamodb-queries


【解决方案1】:

回答:这行得通

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 2020-12-16
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2016-10-16
    • 2019-11-01
    相关资源
    最近更新 更多