我想在foreachPartition
中使用SparkContext和SQLContext,但由于序列化错误无法完成。我知道,无论对象是不可序列化,但我认为foreachPartition
在主服务器,其中两个星火语境和SQLContext可供执行..如何在foreachPartition中使用SQLContext和SparkContext
符号:
`msg -> Map[String,String]`
`result -> Iterable[Seq[Row]]`
这是我当前的代码(UtilsDM是extends Serializable
的对象)。代码失败的部分从val schema =...
开始,我想将result
写入DataFrame
,然后将其保存到Parquet。也许我组织代码的方式效率不高,那么我想在这里提出你的建议。谢谢。
// Here I am creating df from parquet file on S3
val exists = FileSystem.get(new URI("s3n://" + bucketNameCode), sc.hadoopConfiguration).exists(new Path("s3n://" + bucketNameCode + "/" + pathToSentMessages))
var df: DataFrame = null
if (exists) {
df = sqlContext
.read.parquet("s3n://bucket/pathToParquetFile")
}
UtilsDM.setDF(df)
// Here I process myDStream
myDStream.foreachRDD(rdd => {
rdd.foreachPartition{iter =>
val r = new RedisClient(UtilsDM.getHost, UtilsDM.getPort)
val producer = UtilsDM.createProducer
var df = UtilsDM.getDF
val result = iter.map{ msg =>
// ...
Seq(msg("key"),msg("value"))
}
// HERE I WANT TO WRITE result TO S3, BUT IT FAILS
val schema = StructType(
StructField("key", StringType, true) ::
StructField("value", StringType, true)
result.foreach { row =>
val rdd = sc.makeRDD(row)
val df2 = sqlContext.createDataFrame(rdd, schema)
// If the parquet file is not created, then create it
var df_final: DataFrame = null
if (df != null) {
df_final = df.unionAll(df2)
} else {
df_final = df2
}
df_final.write.parquet("s3n://bucket/pathToSentMessages)
}
}
})
编辑:
我使用星火1.6.2和Scala 2.10.6。
这火花的版本? – mrsrinivas
@MRSrinivas:我使用Spark 1.6.2和Scala 2.10.6。对不起,不提。 – duckertito