在RDD使用schema和RDD的Row转成DataFrame再写到hive时,中间遇到一个坑,
我的写入代码是这样
// 创建schema
val schema: types.StructType = StructType(
Seq(
StructField("capture_time",IntegerType,true),
StructField("color_id",IntegerType,true),
StructField("location_id",LongType,true),
StructField("license_plate",StringType,true)
)
)
// 数据转为Row
val rowRDD: RDD[Row] = dataRDD.map(data => {
val seq = Seq(data.getIntValue("capture_time"),
data.getIntValue("color_id"),
data.getLongValue("location_id"),
data.getString("license_plate"))
Row.fromSeq(seq)
})
// 转df
val carDF = sparkSession.createDataFrame(rowRDD,schema)
// 写库
carDF.write
.mode(SaveMode.Append)
.save()
写hive一定要注意,df的字段顺序一定要和hive建表顺序一致,也就是在创建schema的时候就要保证顺序和hive的建表顺序一致,否则会出现hive的数据错乱的情况,字段和值对应不上。而且很坑的是即使类型错了,spark也不报错,还是继续往hive写。
hive的分区表,往往分区字段在最后一个字段,所以也要保证这里分区字段在schema的最后一个