如何在Python中动态更新DynamoDB中的记录?
Python实现DynamoDB动态字段更新
核心思路
通过动态构建UpdateExpression和ExpressionAttributeValues,接收包含待更新字段的字典参数,无需硬编码列名,实现灵活的多字段更新。
修改后的函数代码
def update_column_info(host_name, host_id, update_data): table = self.client.Table(my_test_table) try: # 动态生成更新表达式和属性值映射 update_expr_segments = [] expr_attr_values = {} for col_name, col_value in update_data.items(): # 为每个字段创建唯一占位符 placeholder = f":{col_name}" update_expr_segments.append(f"{col_name}={placeholder}") expr_attr_values[placeholder] = col_value # 拼接完整的更新表达式 update_expression = "SET " + ", ".join(update_expr_segments) response = table.update_item( Key={ PARTITION_KEY: str(host_name), SORT_KEY: str(host_id) }, UpdateExpression=update_expression, ExpressionAttributeValues=expr_attr_values ) return response except Exception as e: print("更新失败", e)
使用示例
如果需要同时更新hostClass和column5:
update_column_info( "app-host-01", "host-007", {"hostClass": "application-server", "column5": "2024-05-20"} )
关键说明
update_data是字典类型,键为表中列名,值为对应新值,支持单次更新1个或多个字段- 动态生成的表达式会自动适配传入的字段,无需手动修改
UpdateExpression - 占位符与列名绑定,避免字段名与DynamoDB保留字冲突,同时保证语法合规
内容的提问来源于stack exchange,提问作者VIPIN KUMAR
相关产品推荐
相关产品推荐

