通过修改以前的值更新 Dynamodb 中的值

Update values in Dynamodb by modifying the previous values

我创建了一个 dynamodb table,我正在使用 lambda 函数更新 dynamodb table 中的值。我的函数更新值的问题,不是修改 dynamodb 中已经存在的旧值,它只是覆盖值。 我在 Dynamodb table:

中更新数据项的代码片段
def push_record_daily_table(date,time,total_records):
    table = dynamodb.Table('daily-metrics')
    try:
        table.update_item(
                Key={'date':date},
                UpdateExpression = "SET last timestamp = :label",
                ExpressionAttributeValues={
                    ':label':time
                }
            )
        table.update_item(
                Key={'date':date},
                UpdateExpression = "SET total files +=  :incr",
                ExpressionAttributeValues={
                    ":incr":1
                }
            )
        table.update_item(
                Key={'date':date},
                UpdateExpression = "SET total records += :label",
                ExpressionAttributeValues={
                    ":label": total_records
                }
            )

这里 Keydate。我正在处理具有多个记录的多个文件,因此每次调用此函数时 文件总数 将增加 1

DynamoDB 更新表达式不支持 += 运算符。您应该使用 SET count = count + :incr 形式的更新表达式而不是 SET count += :incr.

您没有指出任何错误消息(您应该始终包括错误消息)但是您尝试增加 total files 列将会失败:

botocore.exceptions.ClientError:
An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression:
Syntax error; token: "files", near: "total files +"

如果您通过将 #totalfiles 的表达式名称映射用于 total files 来更正该错误,您的代码将失败并显示以下内容,因为 += 不受支持:

botocore.exceptions.ClientError:
An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression:
Syntax error; token: "+", near: "#totalfiles +="

下面是一个工作示例,具有一个简单的属性名称 (files) 和一个包含空格的属性名称 (total files)。

def push_record_daily_table_corrected(date):
    table.update_item(
        Key={'date':date},
        UpdateExpression = "SET files = files + :incr",
        ExpressionAttributeValues={
            ":incr": 1
        }
    )
    table.update_item(
        Key={'date':date},
        UpdateExpression = "SET #totalfiles = #totalfiles + :incr",
        ExpressionAttributeValues={
            ":incr": 1
        },
        ExpressionAttributeNames={
            "#totalfiles": "total files"
        }
    )