Lambda读取CSV写入DynamoDB时仅部分行被处理问题排查
问题根因
代码中return语句的缩进位置错误是导致问题的核心原因:你将返回语句写在了else分支的内部逻辑中,只要循环处理到第一条jump_type既不是CMJ也不是Free的行,执行完DepthJump表写入操作后就会直接终止Lambda函数返回,剩下的所有CSV行都不会被执行,和超时配置无关。
修复方案
调整return语句的缩进层级,将其移到for循环的外部,等所有CSV行都处理完成后再返回结果即可。
修正后的核心代码片段
# Read each row in the file rowCount = 0 for row in reader: rowCount += 1 # Show the row in the debug log print(row['athlete_id'], row['athlete_name'], row['jump_id'], row['date_time'], row['jump_type'], row['jump_tc'], row['jump_height'], row['jump_RSI']) # Insert Athlete ID and Name into Athlete DynamoDB table athleteTable.put_item( Item={ 'AthleteID': row['athlete_id'], 'AthleteName': row['athlete_name']}) # Insert CMJ details into Countermovement Jump DynamoDB table if ((row['jump_type'] == "CMJ") | (row['jump_type'] == "Free")) : countermovementTable.put_item( Item={ 'AthleteID': row['athlete_id'], 'AthleteName': row['athlete_name'], 'DateTime': row['date_time'], 'JumpType': row['jump_type'], 'JumpID': row['jump_id'], 'Height': row['jump_height']}) else : # Insert Depth Jump details into Depth Jump DynamoDB table depthTable.put_item( Item={ 'AthleteID': row['athlete_id'], 'AthleteName': row['athlete_name'], 'DateTime': row['date_time'], 'JumpType': row['jump_type'], 'JumpID': row['jump_id'], 'ContactTime': row['jump_tc'], 'Height': row['jump_height'], 'RSI': row['jump_RSI']}) # 将return移到for循环外部,所有行处理完成后再返回 return "%d data inserted" % rowCount
可选优化建议
- 可以给DynamoDB的
put_item操作增加异常捕获逻辑,避免单条数据格式错误导致整个函数中断,同时打印异常行数据方便排查问题 - 若CSV行数较多,可改用DynamoDB的
batch_write_item批量写入接口,减少网络IO次数,提升函数执行效率
内容的提问来源于stack exchange,提问作者Aaron
相关产品推荐
相关产品推荐

