【问题标题】:Change output CSV file name of AWS Athena queries更改 AWS Athena 查询的输出 CSV 文件名
【发布时间】:2020-09-26 03:00:19
【问题描述】:

我想通过 AWS Lambda 运行我的 Athena 查询,但还将输出 CSV 文件的名称从查询执行 ID 更改为 my-bucket/folder/my-preferred-string.csv

我尝试在网上搜索结果,但找不到 lambda 函数的确切代码。

我是一名数据科学家,也是 AWS 的初学者。这对我来说是一次性的,所以寻找一个快速的解决方案或修补程序。

【问题讨论】:

    标签: amazon-athena


    【解决方案1】:

    这个问题已经发布here

    client = boto3.client('athena')
    s3 = boto3.resource("s3")
    
    # Run query
    queryStart = client.start_query_execution(
        # PUT_YOUR_QUERY_HERE
        QueryString = '''
            SELECT *
            FROM "db_name"."table_name"
            WHERE value > 50
        ''',
        QueryExecutionContext = {
            # YOUR_ATHENA_DATABASE_NAME
            'Database': "covid_data"
        },
        ResultConfiguration = {
            # query result output location you mentioned in AWS Athena
            "OutputLocation": "s3://bucket-name-X/folder-Y/"
        }
    )
    
    # Executes query and waits 3 seconds
    queryId = queryStart['QueryExecutionId']
    time.sleep(3)
    
    # Copies newly generated csv file with appropriate name
    # query result output location you mentioned in AWS Athena
    queryLoc = "bucket-name-X/folder-Y/" + queryId + ".csv"
    
    # Destination location and file name
    s3.Object("bucket-name-A", "report-2018.csv").copy_from(CopySource = queryLoc)
    
    # Deletes Athena generated csv and it's metadata file
    response = s3.delete_object(
        Bucket='bucket-name-A',
        Key=queryId+".csv"
    )
    response = s3.delete_object(
        Bucket='bucket-name-A',
        Key=queryId+".csv.metadata"
    )
    print('{file-name} csv generated')
    

    【讨论】:

    • 有效!从来不知道我可以在 5 分钟内运行我的 lambda 代码,我被困了几个小时。感谢您及时的回复。现在,每次我想要更改查询结果的名称时,是否需要手动运行我的 Lambda 函数?
    • 您可以通过为您的函数设置适当的触发器来做到这一点。请参考docs.aws.amazon.com/lambda/latest/dg/lambda-invocation.html
    • 谢谢,我希望我的 lambda 函数每天在某个时间运行三次。你有什么快速解决办法吗?
    • 你可以通过 cron 表达式来做到这一点。参考stackoverflow.com/a/56601973/13676851
    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 2018-12-08
    • 2019-04-19
    • 2023-03-30
    • 2020-09-12
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多