Spark存储与读取文件方法小结

来源:互联网 发布:逆战刷箱子淘宝 编辑:程序博客网 时间:2024/06/04 19:42

http://blog.csdn.net/buring_/article/details/42424477   mark

一:Spark中常常面临这RDD的存储问题,记录一下常常面临的几种情况。saveAsObjectFile, SequenceFile, mapFile, textFile我就不说了。

首先:在写文件的时候,经常输出的目录以及存在,需要一个删掉目录以及存在的情况。大致功能如下

[java] view plain copy
  1. def checkDirExist(sc:SparkContext,outpath:String) = {  
  2.   logInfo("check output dir is exists")  
  3.   val hdfs = FileSystem.get(new URI("hdfs://hdfs_host:port"),sc.hadoopConfiguration)  
  4.   try{  
  5.     hdfs.delete(new Path(outpath),true//这里已经new 目录了,删除再说,总之是删了  
  6.     logInfo("输出目录存在,删除掉:%s".format(outpath))  
  7.   } catch {  
  8.     case _:Throwable => logWarning("输出目录不存在,不用删除"//永远不会来吧  
  9.   }  
  10. }  

1)存取对象,saveAsObjectFile ,十分方便,类似于python的cPickle.主要用法如下:
比如有一个

[java] view plain copy
  1. val rdd:RDD[(Long,Array[Double])]  
  2. rdd.saveAsObjectFile(outpath)  
  3.   
  4. 读取对象文件,需要指定类型  
  5. val input:RDD[(Long,Array[Double])] = sc.objectFile[(Long,Array[Double])](outpath)  

2)有时候需要节约空间,这样就需要存储序列化文件。如

[java] view plain copy
  1. val rdd: RDD[(Long, Array[Byte])]  
  2. new SequenceFileRDDFunctions(rdd).saveAsSequenceFile(outpath)  
  3. 这里需要注意序列化时候,Long,Array都需要一个隐式转换函数,如下:  
  4. implicit def arrayBytetoBytesArray(bytes:Array[Byte]):BytesWritable = new BytesWritable(bytes)  
  5. implicit  def long2LongWritable(ll:Long):LongWritable = new LongWritable(ll)  
  6.   
  7. 读取序列化文件:  
  8. val rdd = sc.sequenceFile(dir+"/svd",classOf[LongWritable],classOf[BytesWritable]).map{case(uid,sessions)=>  
  9.   sessions.setCapacity(sessions.getLength)  
  10.   (uid.get(),sessions.getBytes.clone())  
  11. }  
这里需要注意的是,读取序列化文件,默认复用了同样的Writable object for each record, 也就导致了返回的RDD将会创建许多引用到同一个对象,我被这个坑了好久。因此这里需要将Array[Byte] 拷贝出来,不然所以的数据都是一样的,Long不是引用对象不需要。

3)有时候需要存储mapFile,用来根据key 快速索引。实践发现,索引的确很快,而且节约存储空间。
存储mapFile文件,需要注意是现要排序以后才能输出,为了快速索引,排序也是可以理解的嘛。

[java] view plain copy
  1. val temp: RDD[(Long, Array[Byte])]  
  2. val mapfile = temp.toArray().sortBy(e => e._1)  
  3. var writer: MapFile.Writer = null  
  4. val conf = sc.hadoopConfiguration  
  5. val fs = FileSystem.get(URI.create(dir+"/merge"),conf)  
  6. val key = new LongWritable()  
  7. val value = new BytesWritable()  
  8. try{  
  9.   writer = new Writer(conf,fs,dir+"/merge",classOf[LongWritable],classOf[BytesWritable])  
  10.   //这里不知道设置多少比较合适,感觉都ok  
  11.   writer.setIndexInterval(1024)  
  12.   for(ele <-mapfile){  
  13.     key.set(ele._1)  
  14.     value.set(ele._2)  
  15.     writer.append(key,value)  
  16.   }  
  17. }finally {  
  18.   IOUtils.closeStream(writer)  
  19. }  
  20.   
  21. 快捷根据key 来检索value  
  22. val reader = new Reader(FileSystem.get(sc.hadoopConfiguration),  
  23.   dir,sc.hadoopConfiguration)  
  24.   
  25. val key = new LongWritable(args(1).toLong)  
  26. val value = new BytesWritable()  
  27.   
  28. reader.get(key,value)  
  29. value.setCapacity(value.getLength)  
  30. val bytes = value.getBytes  
原创粉丝点击