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



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

谢谢

就像 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'])

是的!您可以使用 boto3 与 Athena 互动。

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

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

最简单的方法是将 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
)

您可以使用 boto3 客户端查询 Athena 表。

您可以在此处阅读有关它的更多信息:使用 boto3 在 python 中查询 Amazon Athena 的简单方法

最新更新