簡體   English   中英

如何使用 python 中的 lambda 函數在通過 S3 連接的 AWS athena 中進行查詢

[英]How to query in AWS athena connected through S3 using lambda functions in python

我將 my.csv 文件保存在 S3 存儲桶中。 我可以使用 AWS Athena 查詢 S3 的數據。 有什么辦法可以將lambda function連接到athena並查詢lambda function的數據。請幫忙

謝謝

就像 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(queryStart.QueryExecutionId)

您將需要為QueryExecution.Status.State字段的值解析返回的對象。 繼續使用get_query_execution()更新對象,直到結果為Succeeded

注意:請不要在連續循環中調用get_query_execution() 相反,使用 指數退避算法來防止被該 API 限制。 您應該對所有 API 調用使用這種方法。

然后您可以使用get_query_results()檢索結果進行處理:

results = client.get_query_execution(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 的簡單方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM