Python 通过修改以前的值更新Dynamodb中的值
我创建了一个dynamodb表,并使用lambda函数更新dynamodb表中的值。我的函数用于更新值,而不是修改dynamodb中已经存在的旧值,它只是覆盖了这些值。 用于更新Dynamodb表中数据项的我的代码段:Python 通过修改以前的值更新Dynamodb中的值,python,amazon-web-services,aws-lambda,amazon-dynamodb,Python,Amazon Web Services,Aws Lambda,Amazon Dynamodb,我创建了一个dynamodb表,并使用lambda函数更新dynamodb表中的值。我的函数用于更新值,而不是修改dynamodb中已经存在的旧值,它只是覆盖了这些值。 用于更新Dynamodb表中数据项的我的代码段: def push_record_daily_table(date,time,total_records): table = dynamodb.Table('daily-metrics') try: table.update_item(
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
}
)
这里的键是日期。我正在处理具有多条记录的多个文件,因此每次调用此函数时,文件总数将增加1DynamoDB更新表达式不支持
+=
运算符。您应该使用格式为SET count=count+:incr
的更新表达式,而不是SET count+=:incr
您没有指出任何错误消息(您应该始终包含错误消息),但尝试增加总文件
列将失败,原因是:
botocore.exceptions.ClientError:
An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression:
Syntax error; token: "files", near: "total files +"
如果您纠正了这一点,通过为总文件
使用#totalfiles
的表达式名称映射,您的代码将失败,因为不支持+=
:
botocore.exceptions.ClientError:
An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression:
Syntax error; token: "+", near: "#totalfiles +="
下面是一个工作示例,使用一个简单的属性名(文件
)和一个包含空格的属性名(总文件
)
通常您可以这样递增值:
“SET count=count+:incr”
。我不确定是否支持+=
(可能支持,但我没有立即在文档中看到)。此外,您的列名中是否有空格,例如“last timestamp”?SET count=count+:incr我也尝试过,但它不起作用。
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"
}
)