You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

boto3 get_query_runtime_statistics缺失Rows字段时能否默认输出行数为0?

问题描述

我有一个Lambda函数,用来判断已执行的Athena查询是否返回数据。我使用boto3的get_query_runtime_statistics函数提取其中的"Rows"数据:

response = athena_client.get_query_runtime_statistics(QueryExecutionId=query_id)

row_count = response["QueryRuntimeStatistics"]["Rows"]["OutputRows"]

但之前一次执行时,响应对象未包含"Rows"数据,直接抛出了KeyError。我知道可以用.get("Rows", {}).get("OutputRows")来规避该错误。

我在Athena控制台重新执行了完全相同的查询(返回0行),然后使用该查询ID获取运行时统计信息,此次响应中包含"Rows"数据。也就是说,同一个查询字符串的行为并不一致;但针对原查询执行获取统计信息时,响应始终不包含"Rows"数据。

核心疑问:每当"Rows"数据不存在时,是否可以认为输出行数为0?

我在AWS文档中未找到关于"Rows"可能不总是出现在API响应中的解释。

PS. 以下是boto3定义的响应schema:

{
    'QueryRuntimeStatistics': {
        'Timeline': {
            'QueryQueueTimeInMillis': 123,
            'QueryPlanningTimeInMillis': 123,
            'EngineExecutionTimeInMillis': 123,
            'ServiceProcessingTimeInMillis': 123,
            'TotalExecutionTimeInMillis': 123
        },
        'Rows': {
            'InputRows': 123,
            'InputBytes': 123,
            'OutputBytes': 123,
            'OutputRows': 123
        },
        'OutputStage': {
            'StageId': 123,
            'State': 'string',
            'OutputBytes': 123,
            'OutputRows': 123,
            'InputBytes': 123,
            'InputRows': 123,
            'ExecutionTime': 123,
            'QueryStagePlan': {
                'Name': 'string',
                'Identifier': 'string',
                'Children': [
                    {'... recursive ...'},
                ],
                'RemoteSources': [
                    'string',
                ]
            },
            'SubStages': [
                {'... recursive ...'},
            ]
        }
    }
}
回答

可以认为当"Rows"字段不存在时输出行数为0,但需要结合查询执行状态做验证:

  • 首先通过get_query_execution接口确认查询状态为SUCCEEDED,只有成功执行的查询,统计数据缺失才等价于0行输出。如果查询失败或被取消,此时"Rows"字段缺失是正常情况,不能直接判定为0行。
  • 从你的测试结果来看,返回0行的查询在重新执行时API会返回OutputRows:0的"Rows"字段,原查询执行时的缺失大概率是Athena在边缘场景下的统计数据生成延迟或遗漏,但从业务逻辑角度,只要查询成功且无"Rows"数据,即可等价于输出0行。

推荐的代码实现:

# 先获取查询执行状态
execution_response = athena_client.get_query_execution(QueryExecutionId=query_id)
status = execution_response['QueryExecution']['Status']['State']

if status == 'SUCCEEDED':
    stats_response = athena_client.get_query_runtime_statistics(QueryExecutionId=query_id)
    row_count = stats_response.get("QueryRuntimeStatistics", {}).get("Rows", {}).get("OutputRows", 0)
else:
    # 根据业务需求处理失败/取消场景,比如抛出异常或返回特定值
    row_count = None

内容的提问来源于stack exchange,提问作者jonesn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 02:10:16