如何使用python中的lambda函数在通过S3连接的AWS athena中进行查询

Vip*_*ngh 4 python amazon-s3 amazon-web-services boto3 amazon-athena

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

谢谢

Tyr*_*321 17

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

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

初始化 Athena 客户端:

import boto3
client = boto3.client('athena')
Run Code Online (Sandbox Code Playgroud)

然后您将执行您的查询:

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

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

queryExecution = client.get_query_execution(queryStart.QueryExecutionId)

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

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

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

import boto3
client = boto3.client('athena')
Run Code Online (Sandbox Code Playgroud)

  • 命令 client.get_query_execution(queryStart.QueryExecutionId) 给出错误 AttributeError: 'dict' 对象没有属性 'QueryExecutionId'。我不得不更改为 client.get_query_execution(QueryExecutionId=queryStart['QueryExecutionId']) (3认同)

Chr*_*ard 7

是的!您可以使用 boto3 与 Athena 进行交互。

特别是,您可能需要 start_query_execution 方法。

http://boto3.readthedocs.io/en/latest/reference/services/athena.html#Athena.Client.start_query_execution


Dav*_*veR 6

最简单的方法是使用awscrawler及其用于 aws lambda 的自定义层

import awswrangler as wr
sql = "select * from my_table"
df = wr.athena.read_sql_query(
    sql=sql, database="my_table", ctas_approach=True
)
Run Code Online (Sandbox Code Playgroud)