无法使用 Python 从 AWS Glue 数据库/表读取数据

我的要求是使用 python 脚本将数据从 AWS Glue 数据库读取到数据帧中。当我进行研究时,我与图书馆进行了斗争 - “awswrangler”。我使用以下代码来连接和读取数据:


import awswrangler as wr


profile_name = 'aws_profile_dev'

REGION = 'us-east-1'


#Retreiving credentials to connect to AWS

ACCESS_KEY_ID, SECRET_ACCESS_KEY,SESSION_TOKEN = get_profile_credentials(profile_name)


session = boto3.session.Session(

    aws_access_key_id=ACCESS_KEY_ID,

    aws_secret_access_key=SECRET_ACCESS_KEY,

    aws_session_token=SESSION_TOKEN

)


my_df= wr.athena.read_sql_table(table= 'mytable_1', database= 'shared_db', boto3_session=session)

然而,当我运行上面的代码时,我收到以下错误 - “ValueError:year 0 is out of range”


或者,我尝试使用另一个库 - “pyathena”。我尝试使用的代码是:


from pyathena import connect

import pandas as pd


conn = connect(aws_access_key_id=ACCESS_KEY_ID,

                 aws_secret_access_key=SECRET_ACCESS_KEY,

                 aws_session_token=SESSION_TOKEN,

                 s3_staging_dir='s3://my-sample-bucket/',

                 region_name='us-east-1')

df = pd.read_sql("select * from AwsDataCatalog.shared_db.mytable_1 limit 1000", conn)

使用它,我可以检索数据,但它仅在我使用限制时才有效。即,如果我只是无限制地运行查询,即“select * from AwsDataCatalog.shared_db.mytable_1”,则会出现错误 - ValueError:year 0 is out of range


奇怪的行为- 例如,如果我运行:


df = pd.read_sql("select * from AwsDataCatalog.shared_db.mytable_1 limit 1200", conn)

有时它会给出相同的错误,如果我只是减小限制值并运行(例如限制 1199),稍后当我使用限制 1200 运行它时它会起作用。但如果我尝试读取超过 1300 行,这将不起作用。我的表中共有 2002 行。我需要阅读整个表格。


白板的微信
浏览 175回答 2
2回答

喵喵时光机

在 python 中使用以下代码来获取您正在寻找的数据。    import boto3    query = "SELECT * from table_name"    s3_resource = boto3.resource("s3")    s3_client = boto3.client('s3')    DATABASE = 'database_name'    output='s3://output-bucket/output-folder'        athena_client = boto3.client('athena')            # Execution        response = athena_client.start_query_execution(            QueryString=query,            QueryExecutionContext={                'Database': DATABASE            },            ResultConfiguration={                'OutputLocation': output,            }        )            queryId = response['QueryExecutionId']

回首忆惘然

我找到了一种使用 awswrangler 直接从 Athena 查询数据到本地计算机上的 pandas 数据帧的方法。这不需要我们提供 S3 上的输出位置。profile_name = 'Dev-AWS'REGION = 'us-east-1'#this automatically retrieves credentials from your aws credentials file after you run aws configure on command-lineACCESS_KEY_ID, SECRET_ACCESS_KEY,SESSION_TOKEN = get_profile_credentials(profile_name)session = boto3.session.Session(    aws_access_key_id=ACCESS_KEY_ID,    aws_secret_access_key=SECRET_ACCESS_KEY,    aws_session_token=SESSION_TOKEN)wr.athena.read_sql_query("select * from table_name", database="db_name", boto3_session=session)或者,如果您不想查询 Athena,但想读取整个粘合表,则可以使用:my_df = wr.athena.read_sql_table(table= 'my_table', database= 'my_db', boto3_session=session)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python