我使用以下命令在数据砖中读取 S3 的镶木地板文件
df = sqlContext.read.parquet('s3://path/to/parquet/file')
我想读取数据帧的架构,可以使用以下命令执行此操作:
df_schema = df.schema.json()
但是我无法将df_schama
对象写入 S3 上的文件。注意:我愿意不创建 json 文件。我只想将数据帧的架构保存到 AWS S3 中的任何文件类型(可能是文本文件(。
我尝试编写 json 架构如下,
df_schema.write.csv("s3://path/to/file")
或
a.write.format('json').save('s3://path/to/file')
他们都给了我以下错误:
AttributeError: 'str' object has no attribute 'write'
下面是保存架构并将其应用于新 csv 数据的工作示例:
# funcs
from pyspark.sql.functions import *
from pyspark.sql.types import *
# example old df schema w/ long datatype
df = spark.range(10)
df.printSchema()
df.write.mode("overwrite").csv("old_schema")
root
|-- id: long (nullable = false)
# example new df schema we will save w/ int datatype
df = df.select(col("id").cast("int"))
df.printSchema()
root
|-- id: integer (nullable = false)
# get schema as json object
schema = df.schema.json()
# write/read schema to s3 as .txt
import json
with open('s3:/path/to/schema.txt', 'w') as F:
json.dump(schema, F)
with open('s3:/path/to/schema.txt', 'r') as F:
saved_schema = json.load(F)
# saved schema
saved_schema
'{"fields":[{"metadata":{},"name":"id","nullable":false,"type":"integer"}],"type":"struct"}'
# construct saved schema object
new_schema = StructType.fromJson(json.loads(saved_schema))
new_schema
StructType(List(StructField(id,IntegerType,false)))
# use saved schema to read csv files ... new df has int datatype and not long
new_df = spark.read.csv("old_schema", schema=new_schema)
new_df.printSchema()
root
|-- id: integer (nullable = true)
df.schema.json()
结果string
对象和string
对象将没有.write
方法。
In RDD Api:
df_schema = df.schema.json()
并行化df_schema
变量以创建rdd
,然后使用.saveAsTextFile
方法将架构写入 S3。
sc.parallelize([df_schema]).saveAsTextFile("s3://path/to/file")
(或(
In Dataframe Api:
from pyspark.sql import Row
df_schema = df.schema.json()
df_sch=sc.parallelize([Row(schema=df_schema)]).toDF()
df_sch.write.csv("s3://path/to/file")
df_sch.write.text("s3://path/to/file") //write as textfile