首页 > 解决方案 > Athena 查询可在控制台中使用,但不适用于 sagemaker 中的 boto3 客户端(将 csv 转换为表格)

问题描述

我正在尝试将 s3 中的 csv 文件转换为 Athena 中的表。当我在 Athena 控制台上运行查询时,它可以工作,但是当我在带有 boto3 客户端的 Sagemaker Jupyter 笔记本上运行它时,它返回:

"**InvalidRequestException**: An error occurred (InvalidRequestException) when calling the StartQueryExecution operation: line 1:8: no viable alternative at input 'CREATE EXTERNAL'"

这是我的代码

def run_query(query):
    client = boto3.client('athena')
    response = client.start_query_execution(
        QueryString=query,
        ResultConfiguration={
            'OutputLocation': 's3://path/to/s3output',
            }
        )
    print('Execution ID: ' + response['QueryExecutionId'])
    return response

createTable = \
"""CREATE EXTERNAL TABLE TestTable (
    ID string,
    CustomerId string, 
    Ip string,
    MessageFilename string

)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
   'separatorChar' = ',',
   'quoteChar' = '\"',
   'escapeChar' = '\\'
 )
STORED AS TEXTFILE
LOCATION 's3://bucket_name/results/csv/'
TBLPROPERTIES ("skip.header.line.count"="1")"""

response = run_query(createTable, s3_output)
print(response)

我已经通过 boto3 客户端以 json 格式运行查询(因此,使用 ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe')运行良好,但不知何故这没有。我尝试过更改名称、语法、引号,但这似乎不起作用。

任何建议将不胜感激,谢谢!

标签: pythonjupyter-notebookboto3amazon-athenaamazon-sagemaker

解决方案


感谢分享完整的例子。问题在于SERDEPROPERTIES. createTable如下修改后即可工作

createTable = \
"""CREATE EXTERNAL TABLE testtable (
    `id` string,
    `customerid` string, 
    `ip` string,
    `messagefilename` string
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
  'separatorChar' = ',', 
  'quoteChar' = '\\\"', 
  'escapeChar' = '\\\\' )
STORED AS TEXTFILE
LOCATION 's3://bucket_name/results/csv/'
TBLPROPERTIES ("skip.header.line.count"="1");"""

推荐阅读