我是一个新的Spark和Python用户,遇到了以下问题:如何从元数据文件构建模式,以便可以应用于我的数据文件。 场景:数据文件(csv格式)的元数据文件包含列及其类型,例如:
id,int,10,"","",id,"","",TRUE,"",0
created_at,timestamp,"","","",created_at,"","",FALSE,"",0
我已成功将其转换为一个类似于以下数据框的数据:
+--------------------+---------------+
| name| type|
+--------------------+---------------+
| id| IntegerType()|
| created_at|TimestampType()|
| updated_at| StringType()|
但是当我尝试使用以下方法将其转换为StructField格式时
fields = schemaLoansNew.map(lambda l:([StructField(l.name, l.type, 'true')]))
或者
schemaList = schemaLoansNew.map(lambda l: ("StructField(" + l.name + "," + l.type + ",true)")).collect()
然后稍后将其转换为StructType,使用
schemaFinal = StructType(schemaList)
我遇到了以下错误:Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/mapr/spark/spark-1.4.1/python/pyspark/sql/types.py", line 372, in __init__
assert all(isinstance(f, DataType) for f in fields), "fields should be a list of DataType"
AssertionError: fields should be a list of DataType
由于我对数据框架的知识不足,我卡住了,您能否请指教以下如何继续。一旦我的模式准备好,我想使用createDataFrame将其应用于我的数据文件。这个过程必须针对许多表进行,因此我不想硬编码类型,而是使用元数据文件来构建模式然后应用于RDD。
提前感谢。
Row.asDict
,但仍需要一个映射。 - zero323