如何将 printSchema 的结果保存到 PySpark 中的文件中

2023-12-20

我用过df.printSchema()在 pyspark 中,它为我提供了具有树结构的模式。现在我需要将其保存在变量或文本文件中。

我尝试过以下保存方法,但没有成功。

v = str(df.printSchema())  
print(v) 
#and
df.printSchema().saveAsTextFile(<path>)

我需要以下格式保存的架构

|-- COVERSHEET: struct (nullable = true)                              
 |    |-- ADDRESSES: struct (nullable = true)
 |    |    |-- ADDRESS: struct (nullable = true)
 |    |    |    |-- _VALUE: string (nullable = true)
 |    |    |    |-- _city: string (nullable = true)
 |    |    |    |-- _primary: long (nullable = true)
 |    |    |    |-- _state: string (nullable = true)
 |    |    |    |-- _street: string (nullable = true)
 |    |    |    |-- _type: string (nullable = true)
 |    |    |    |-- _zip: long (nullable = true)
 |    |-- CONTACTS: struct (nullable = true)
 |    |    |-- CONTACT: array (nullable = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- _VALUE: string (nullable = true)
 |    |    |    |    |-- _name: string (nullable = true)
 |    |    |    |    |-- _type: string (nullable = true)

你需要treeString(由于某种原因,我在 python API 中找不到)

#v will be a string
v = df._jdf.schema().treeString()

您可以将其转换为 RDD 并使用saveAsTextFile

sc.parallelize([v]).saveAsTextFile(...)

或者使用 Python 特定的 API 将字符串写入文件。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 printSchema 的结果保存到 PySpark 中的文件中 的相关文章

随机推荐