2

我使用以下命令从数据块中的 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'

4

2 回答 2

3

这是保存模式并将其应用于新 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)

于 2019-06-21T19:00:27.437 回答
0

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=df1)]).toDF()
df_sch.write.csv("s3://path/to/file")
df_sch.write.text("s3://path/to/file") //write as textfile
于 2019-06-21T18:36:34.193 回答