Athena 查询因 boto3 而失败(S3 位置无效)

Athena query fails with boto3 (S3 location invalid)

我正尝试在 Athena 中执行查询,但失败了。

代码:

client.start_query_execution(QueryString="CREATE DATABASE IF NOT EXISTS db;",
                           QueryExecutionContext={'Database': 'db'},
                           ResultConfiguration={
                                     'OutputLocation': "s3://my-bucket/",
                                     'EncryptionConfiguration': {
                                             'EncryptionOption': 'SSE-S3'
                                             }
                                     })

但它引发了以下异常:

botocore.errorfactory.InvalidRequestException: An error occurred (InvalidRequestException) 
when calling the StartQueryExecution operation: The S3 location provided to save your 
query results is invalid. Please check your S3 location is correct and is in the same 
region and try again. If you continue to see the issue, contact customer support 
for further assistance.

但是,如果我转到 Athena 控制台,转到“设置”并输入相同的 S3 位置(例如):

查询运行正常。

我的代码有什么问题?我已经成功地使用了其他几个服务(例如 S3)的 API,但是在这个服务中我相信我传递了一些不正确的参数。谢谢

Python:3.6.1。 Boto3:1.4.4

编辑:正如 Justin 所建议的,AWS 后来通过向存储桶添加 athena 前缀来增加对 Athena 的支持。请为他的回答点赞。


已接受的答案

为保存您的查询结果而提供的 S3 位置无效。 请检查您的 S3 位置是否正确且位于同一区域,然后重试。

由于它在您使用控制台时有效,因此存储桶可能位于与您在 Boto3 中使用的区域不同的区域。确保在构建 Boto3 客户端时使用正确的区域(在控制台中工作的区域)。默认情况下,Boto3 将使用凭证文件中配置的区域。

或者尝试 boto3.client('athena', region_name = '<region>')

运行 进入同样的问题,需要在客户端指定 S3 存储桶。

我必须向我的存储桶添加 'athena-' 前缀才能使其正常工作。例如,代替:

"s3://my-bucket/"

尝试:

"s3://athena-my-bucket/"

在我的例子中,IAM 角色没有 S3 存储桶的所有权限。我授予 IAM 角色以下 Athena 结果存储桶的权限。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:GetObject",
                "s3:ListBucket",
                "s3:PutObject",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::athena_results_bucket",
                "arn:aws:s3:::athena_results_bucket"
            ],
            "Effect": "Allow"
        }
    ]
}

我收到了 OP 错误,尝试了 Justin 的回答,但得到了以下错误

SYNTAX_ERROR: line 1:15: Schema TableName does not exist

这意味着它无法找到我之前通过 AWS Athena 创建的表 UI。

简单的解决方案是改用 dclaze 的答案。这两个答案不能同时使用,否则会返回初始(OP)错误。