如何使用boto3从s3读取拼花地板文件



我在s3 bucket(s3://mybucket/my/path/(中有一些镶木地板文件。我想使用boto3将其读取到spark数据帧中。

由于现有的安全性,我无法将其直接读取为spark.read.parquet("3://mybucket/my/path/'"(。因此,需要使用boto3进行阅读。

在尝试使用以下代码读取单个parquet文件(s3://mybucket/my/path/myfile1.parquet(时,我遇到了错误。

res = autorefresh_session.resource('s3')
bucket = res.Bucket(name=mybucket)
obj = bucket.objects.filter(prefix=/my/path)
body = io.BytesIO(obj.get()['Body'].read())
spark.read.parquet(body).show()

Py4JJavaError:调用xyz.parquet时出错。:java.lang.ClassCastException:java.util.ArrayList无法强制转换为java.lang.String网址:org.apache.spark.sql.DataFrameReader.preprocessDeltaLoading(DataFrameReader.scala:282(

有人能告诉我如何使用boto3读取单个文件和完整的文件夹吗?

我可以使用上述方法成功读取csv文件,但不能读取拼花地板文件。我可以将单个文件读取到pandas-df中,然后再进行spark,但这不是一种有效的读取方式

您可以使用以下步骤。

步骤-01:读取您的镶木地板s3位置并转换为熊猫数据帧。参考

import pyarrow.parquet as pq
import s3fs
s3 = s3fs.S3FileSystem()
pandas_dataframe = pq.ParquetDataset('s3://your-bucket/', filesystem=s3).read_pandas().to_pandas()

步骤02:将panda数据帧转换为spark数据帧:

# Spark to Pandas
df_pd = df.toPandas()
# Pandas to Spark
df_sp = spark_session.createDataFrame(df_pd)

最新更新