【Spark Java API】Action(6)—saveAsTextFile最蕾、saveAsObjectFile

saveAsTextFile


官方文檔描述:

Save this RDD as a text file, using string representations of elements.

函數(shù)原型:

def saveAsTextFile(path: String): Unit
def saveAsTextFile(path: String, codec: Class[_ <: CompressionCodec]): Unit

saveAsTextFile用于將RDD以文本文件的格式存儲到文件系統(tǒng)中依溯。

源碼分析:

def saveAsTextFile(path: String): Unit = withScope {  
  // https://issues.apache.org/jira/browse/SPARK-2075  //  
  // NullWritable is a `Comparable` in Hadoop 1.+, so the compiler cannot find an implicit  
  // Ordering for it and will use the default `null`. However, it's a `Comparable[NullWritable]`  
  // in Hadoop 2.+, so the compiler will call the implicit `Ordering.ordered` method to create an  
  // Ordering for `NullWritable`. That's why the compiler will generate different anonymous  
  // classes for `saveAsTextFile` in Hadoop 1.+ and Hadoop 2.+.  
  //  
  // Therefore, here we provide an explicit Ordering `null` to make sure the compiler generate  
  // same bytecodes for `saveAsTextFile`.  
  val nullWritableClassTag = implicitly[ClassTag[NullWritable]]  
  val textClassTag = implicitly[ClassTag[Text]]  
  val r = this.mapPartitions { iter =>    
    val text = new Text()    
    iter.map { x =>      
      text.set(x.toString)      
      (NullWritable.get(), text)    
    }  
  }  
  RDD.rddToPairRDDFunctions(r)(nullWritableClassTag, textClassTag, null)    
    .saveAsHadoopFile[TextOutputFormat[NullWritable, Text]](path)
}
/** 
* Output the RDD to any Hadoop-supported file system, using a Hadoop `OutputFormat` class 
* supporting the key and value types K and V in this RDD. 
*/
def saveAsHadoopFile(    
      path: String,    
      keyClass: Class[_],    
      valueClass: Class[_],    
      outputFormatClass: Class[_ <: OutputFormat[_, _]],    
      conf: JobConf = new JobConf(self.context.hadoopConfiguration),    
      codec: Option[Class[_ <: CompressionCodec]] = None): Unit = self.withScope {  
  // Rename this as hadoopConf internally to avoid shadowing (see SPARK-2038).  
  val hadoopConf = conf  
  hadoopConf.setOutputKeyClass(keyClass)  
  hadoopConf.setOutputValueClass(valueClass)  
  // Doesn't work in Scala 2.9 due to what may be a generics bug  
  // TODO: Should we uncomment this for Scala 2.10?  
  // conf.setOutputFormat(outputFormatClass)  
  hadoopConf.set("mapred.output.format.class", outputFormatClass.getName)  
  for (c <- codec) {    
    hadoopConf.setCompressMapOutput(true)    
    hadoopConf.set("mapred.output.compress", "true")    
    hadoopConf.setMapOutputCompressorClass(c)    
    hadoopConf.set("mapred.output.compression.codec", c.getCanonicalName)    
    hadoopConf.set("mapred.output.compression.type", CompressionType.BLOCK.toString)  
   }  
   // Use configured output committer if already set  
   if (conf.getOutputCommitter == null) {    
      hadoopConf.setOutputCommitter(classOf[FileOutputCommitter])  
   }  
  FileOutputFormat.setOutputPath(hadoopConf,   
    SparkHadoopWriter.createPathFromString(path, hadoopConf))  
  saveAsHadoopDataset(hadoopConf)
}

/** 
* Output the RDD to any Hadoop-supported storage system, using a Hadoop JobConf object for 
* that storage system. The JobConf should set an OutputFormat and any output paths required 
* (e.g. a table name to write to) in the same way as it would be configured for a Hadoop 
* MapReduce job. 
*/
def saveAsHadoopDataset(conf: JobConf): Unit = self.withScope {  
  // Rename this as hadoopConf internally to avoid shadowing (see SPARK-2038).  
  val hadoopConf = conf  
  val wrappedConf = new SerializableConfiguration(hadoopConf)  
  val outputFormatInstance = hadoopConf.getOutputFormat  
  val keyClass = hadoopConf.getOutputKeyClass  
  val valueClass = hadoopConf.getOutputValueClass  
  if (outputFormatInstance == null) {    
    throw new SparkException("Output format class not set")  
  }  
  if (keyClass == null) {    
    throw new SparkException("Output key class not set")  
  }  
  if (valueClass == null) {    
    throw new SparkException("Output value class not set")  
  }  
  SparkHadoopUtil.get.addCredentials(hadoopConf)  
  logDebug("Saving as hadoop file of type (" + keyClass.getSimpleName + ", " +    valueClass.getSimpleName + ")")  
  if (isOutputSpecValidationEnabled) {    
    // FileOutputFormat ignores the filesystem parameter    
    val ignoredFs = FileSystem.get(hadoopConf)    
    hadoopConf.getOutputFormat.checkOutputSpecs(ignoredFs, hadoopConf)  
  }  
  val writer = new SparkHadoopWriter(hadoopConf)  
  writer.preSetup()  
  val writeToFile = (context: TaskContext, iter: Iterator[(K, V)]) => {    
    val config = wrappedConf.value    
    // Hadoop wants a 32-bit task attempt ID, so if ours is bigger than Int.MaxValue, roll it    
    // around by taking a mod. We expect that no task will be attempted 2 billion times.    
    val taskAttemptId = (context.taskAttemptId % Int.MaxValue).toInt    
    val (outputMetrics, bytesWrittenCallback) = initHadoopOutputMetrics(context)    writer.setup(context.stageId, context.partitionId, taskAttemptId)    
    writer.open()    
    var recordsWritten = 0L    
    Utils.tryWithSafeFinally {      
      while (iter.hasNext) {        
        val record = iter.next()        
        writer.write(record._1.asInstanceOf[AnyRef], record._2.asInstanceOf[AnyRef])        
        // Update bytes written metric every few records        
        maybeUpdateOutputMetrics(bytesWrittenCallback, outputMetrics, recordsWritten)        
        recordsWritten += 1      
  }    
} {      
  writer.close()    
}    
  writer.commit()    
  bytesWrittenCallback.foreach { fn => outputMetrics.setBytesWritten(fn()) }    
  outputMetrics.setRecordsWritten(recordsWritten)  }  
  self.context.runJob(self, writeToFile)  
  writer.commitJob()
}

從源碼中可以看到,saveAsTextFile函數(shù)是依賴于saveAsHadoopFile函數(shù)瘟则,由于saveAsHadoopFile函數(shù)接受PairRDD黎炉,所以在saveAsTextFile函數(shù)中利用rddToPairRDDFunctions函數(shù)轉(zhuǎn)化為(NullWritable,Text)類型的RDD,然后通過saveAsHadoopFile函數(shù)實現(xiàn)相應(yīng)的寫操作醋拧。

實例:

List<Integer> data = Arrays.asList(5, 1, 1, 4, 4, 2, 2);
JavaRDD<Integer> javaRDD = javaSparkContext.parallelize(data,5);
javaRDD.saveAsTextFile("/user/tmp");

savaAsObjectFile


官方文檔描述:

Save this RDD as a SequenceFile of serialized objects.

函數(shù)原型:

def saveAsObjectFile(path: String): Unit

saveAsObjectFile用于將RDD中的元素序列化成對象慷嗜,存儲到文件中淀弹。

源碼分析:

def saveAsObjectFile(path: String): Unit = withScope {  
  this.mapPartitions(iter => iter.grouped(10).map(_.toArray))    
    .map(x => (NullWritable.get(), new BytesWritable(Utils.serialize(x))))    
    .saveAsSequenceFile(path)
}

def saveAsSequenceFile(    
    path: String,    
    codec: Option[Class[_ <: CompressionCodec]] = None): Unit = self.withScope {  
  def anyToWritable[U <% Writable](u: U): Writable = u  
  // TODO We cannot force the return type of `anyToWritable` be same as keyWritableClass and  
  // valueWritableClass at the compile time. To implement that, we need to add type parameters to  
  // SequenceFileRDDFunctions. however, SequenceFileRDDFunctions is a public class so it will be a  
  // breaking change.  
  val convertKey = self.keyClass != keyWritableClass  
  val convertValue = self.valueClass != valueWritableClass  
  logInfo("Saving as sequence file of type (" + keyWritableClass.getSimpleName + "," +    valueWritableClass.getSimpleName + ")" )  
  val format = classOf[SequenceFileOutputFormat[Writable, Writable]]  
  val jobConf = new JobConf(self.context.hadoopConfiguration)  
  if (!convertKey && !convertValue) {    
    self.saveAsHadoopFile(path, keyWritableClass, valueWritableClass, format, jobConf, codec)  
  } else if (!convertKey && convertValue) {    
    self.map(x => (x._1, anyToWritable(x._2))).saveAsHadoopFile(      
      path, keyWritableClass, valueWritableClass, format, jobConf, codec)  
  } else if (convertKey && !convertValue) {    
    self.map(x => (anyToWritable(x._1), x._2)).saveAsHadoopFile(      
      path, keyWritableClass, valueWritableClass, format, jobConf, codec)  
  } else if (convertKey && convertValue) {    
    self.map(x => (anyToWritable(x._1), anyToWritable(x._2))).saveAsHadoopFile(      
      path, keyWritableClass, valueWritableClass, format, jobConf, codec)  
  }
}

從源碼中可以看出,saveAsObjectFile函數(shù)是依賴于saveAsSequenceFile函數(shù)實現(xiàn)的庆械,將RDD轉(zhuǎn)化為類型為<NullWritable,BytesWritable>的PairRDD薇溃,然后通過saveAsSequenceFile函數(shù)實現(xiàn)。在spark的java版的api中沒有實現(xiàn)saveAsSequenceFile函數(shù)缭乘,該函數(shù)類似于saveAsTextFile函數(shù)痊焊。

實例:

List<Integer> data = Arrays.asList(5, 1, 1, 4, 4, 2, 2);
JavaRDD<Integer> javaRDD = javaSparkContext.parallelize(data,5);
javaRDD.saveAsObjectFile("/user/tmp");
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市忿峻,隨后出現(xiàn)的幾起案子薄啥,更是在濱河造成了極大的恐慌,老刑警劉巖逛尚,帶你破解...
    沈念sama閱讀 206,723評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件垄惧,死亡現(xiàn)場離奇詭異,居然都是意外死亡绰寞,警方通過查閱死者的電腦和手機到逊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來滤钱,“玉大人觉壶,你說我怎么就攤上這事〖祝” “怎么了铜靶?”我有些...
    開封第一講書人閱讀 152,998評論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長他炊。 經(jīng)常有香客問我争剿,道長,這世上最難降的妖魔是什么痊末? 我笑而不...
    開封第一講書人閱讀 55,323評論 1 279
  • 正文 為了忘掉前任蚕苇,我火速辦了婚禮,結(jié)果婚禮上凿叠,老公的妹妹穿的比我還像新娘涩笤。我一直安慰自己,他們只是感情好盒件,可當(dāng)我...
    茶點故事閱讀 64,355評論 5 374
  • 文/花漫 我一把揭開白布蹬碧。 她就那樣靜靜地躺著,像睡著了一般履恩。 火紅的嫁衣襯著肌膚如雪锰茉。 梳的紋絲不亂的頭發(fā)上呢蔫,一...
    開封第一講書人閱讀 49,079評論 1 285
  • 那天切心,我揣著相機與錄音飒筑,去河邊找鬼。 笑死绽昏,一個胖子當(dāng)著我的面吹牛协屡,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播全谤,決...
    沈念sama閱讀 38,389評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼肤晓,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了认然?” 一聲冷哼從身側(cè)響起补憾,我...
    開封第一講書人閱讀 37,019評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎卷员,沒想到半個月后盈匾,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,519評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡毕骡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,971評論 2 325
  • 正文 我和宋清朗相戀三年削饵,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片未巫。...
    茶點故事閱讀 38,100評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡窿撬,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出叙凡,到底是詐尸還是另有隱情劈伴,我是刑警寧澤,帶...
    沈念sama閱讀 33,738評論 4 324
  • 正文 年R本政府宣布握爷,位于F島的核電站宰啦,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏饼拍。R本人自食惡果不足惜赡模,卻給世界環(huán)境...
    茶點故事閱讀 39,293評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望师抄。 院中可真熱鬧漓柑,春花似錦、人聲如沸叨吮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,289評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽茶鉴。三九已至锋玲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間涵叮,已是汗流浹背惭蹂。 一陣腳步聲響...
    開封第一講書人閱讀 31,517評論 1 262
  • 我被黑心中介騙來泰國打工伞插, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人盾碗。 一個月前我還...
    沈念sama閱讀 45,547評論 2 354
  • 正文 我出身青樓媚污,卻偏偏與公主長得像,于是被迫代替她去往敵國和親廷雅。 傳聞我的和親對象是個殘疾皇子耗美,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,834評論 2 345

推薦閱讀更多精彩內(nèi)容