我想在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