如何通过Boto3按名称或ID获取AWS Athena指定查询的执行详情?
Athena查询与执行记录关联的解决方案
目前Boto3确实没有提供直接通过查询名称/ID获取对应执行记录的API,不过可以通过以下几种方式实现查询与执行记录的清晰关联:
1. 给查询执行记录添加自定义标签
提交查询时,在获取到QueryExecutionId后,立刻调用add_tags()给该执行记录打上包含查询名称/自定义ID的标签,后续就能通过标签筛选关联的执行记录。
示例代码:
import boto3 athena = boto3.client('athena') region = athena._client_config.region_name account_id = athena._client_config.account_id # 提交查询 exec_response = athena.start_query_execution( QueryString='SELECT * FROM sales_db.daily_sales', QueryExecutionContext={'Database': 'sales_db'}, ResultConfiguration={'OutputLocation': 's3://my-athena-results/'} ) exec_id = exec_response['QueryExecutionId'] # 打标签关联自定义查询标识 athena.add_tags( ResourceARN=f'arn:aws:athena:{region}:{account_id}:query-execution/{exec_id}', Tags=[ {'Key': 'QueryName', 'Value': '每日销售统计'}, {'Key': 'CustomQueryID', 'Value': 'SQ-001'} ] )
后续筛选时,可先通过list_query_executions()获取所有执行ID,再批量调用list_tags_for_resource()获取标签,筛选出带有目标标识的执行ID,最后用get_query_execution()或batch_get_query_execution()获取详情。
2. 结合命名查询(Named Queries)标记
如果你的查询是通过create_named_query()保存的命名查询,执行时可以把命名查询的ID作为标签打在执行记录上,直接关联命名查询与执行记录:
# 获取命名查询详情 named_query = athena.get_named_query(NamedQueryId='nq-123456789') # 执行命名查询 exec_response = athena.start_query_execution( QueryString=named_query['NamedQuery']['QueryString'], QueryExecutionContext={'Database': 'sales_db'}, ResultConfiguration={'OutputLocation': 's3://my-athena-results/'} ) # 关联命名查询ID athena.add_tags( ResourceARN=f'arn:aws:athena:{region}:{account_id}:query-execution/{exec_response["QueryExecutionId"]}', Tags=[{'Key': 'NamedQueryId', 'Value': 'nq-123456789'}] )
3. 通过CloudTrail日志回溯关联
AWS CloudTrail会记录所有StartQueryExecution的API请求,日志中会包含提交的查询内容、命名查询ID(若执行命名查询)以及对应的QueryExecutionId。你可以筛选CloudTrail日志中eventName为StartQueryExecution的记录,直接提取查询与执行记录的关联关系,再去获取执行详情。
内容的提问来源于stack exchange,提问作者anon_39
相关产品推荐
相关产品推荐

