首页 > 解决方案 > 如何使用 python 中的 lambda 函数在通过 S3 连接的 AWS 雅典娜中进行查询

问题描述

我将 .csv 文件保存在 S3 存储桶中。我可以使用 AWS Athena 查询 S3 的数据。有什么方法可以将 lambda 函数连接到 athena 并从 lambda 函数查询数据。请帮忙

谢谢

标签: pythonamazon-web-servicesamazon-s3boto3amazon-athena

解决方案


就像 Chris Pollard 所说,您可以使用 boto3 从 Lambda 函数中查询 Athena。

http://boto3.readthedocs.io/en/latest/reference/services/athena.html

初始化 Athena 客户端:

import boto3
client = boto3.client('athena')

然后,您将执行您的查询:

queryStart = client.start_query_execution(
    QueryString = 'SELECT * FROM myTable',
    QueryExecutionContext = {
        'Database': 'myDatabase'
    }, 
    ResultConfiguration = { 'OutputLocation': 's3://your-bucket/key'}
)

如果您想在 Lambda 中检索结果(可能使用第二个函数,由于时间限制 - 请参阅文档- 另请注意,您按 100 毫秒运行时间付费),您将使用get_query_execution来确定查询的状态:

queryExecution = client.get_query_execution(QueryExecutionId=queryStart['QueryExecutionId'])

您将需要解析返回的对象以获取该QueryExecution.Status.State字段的值。使用 继续更新对象,get_query_execution()直到结果为Succeeded.

注意:请不要get_query_execution()连续循环调用。相反,使用指数退避算法来防止被该 API 限制。您应该将此方法用于所有 API 调用。

然后您可以使用get_query_results()检索结果进行处理:

results = client.get_query_results(QueryExecutionId=queryStart['QueryExecutionId'])

推荐阅读