java—从spark中的压缩读取全文文件

kxxlusnw  于 2021-05-29  发布在  Hadoop
关注(0)|答案(2)|浏览(435)

我有以下问题:假设我有一个包含压缩目录的目录,其中包含多个文件,存储在hdfs上。我想创建一个rdd,它包含一些t类型的对象,即:

context = new JavaSparkContext(conf);
JavaPairRDD<String, String> filesRDD = context.wholeTextFiles(inputDataPath);

JavaPairRDD<String, String> filesRDD = context.wholeTextFiles(inputDataPath);
JavaRDD<T> processingFiles = filesRDD.map(fileNameContent -> {
    // The name of the file
    String fileName = fileNameContent._1();
    // The content of the file
    String content = fileNameContent._2();

    // Class T has a constructor of taking the filename and the content of each
    // processed file (as two strings)
    T t = new T(content, fileName);

    return t;
});

现在什么时候 inputDataPath 是一个包含文件的目录,它工作得非常好,例如:

String inputDataPath =  "hdfs://some_path/*/*/"; // because it contains subfolders

但是,当一个tgz包含多个文件时,文件内容( fileNameContent._2() )给我一些无用的二进制字符串(很期待)。我发现了一个类似的问题,但情况不同,因为解决方案是,每次压缩只包含一个文件,而在我的情况下,还有许多其他文件,我想作为整个文件单独读取。我还发现了一个关于 wholeTextFiles ,但这在我的情况下不起作用。
你知道怎么做吗?
编辑:
我试着从这里测试阅读器(试着从这里测试阅读器,就像在函数中一样) testTarballWithFolders() )但每当我打电话

TarballReader tarballReader = new TarballReader(fileName);

我得到了 NullPointerException :

java.lang.NullPointerException
    at java.util.zip.InflaterInputStream.<init>(InflaterInputStream.java:83)
    at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:77)
    at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:91)
    at utils.TarballReader.<init>(TarballReader.java:61)
    at main.SparkMain.lambda$0(SparkMain.java:105)
    at main.SparkMain$$Lambda$18/1667100242.call(Unknown Source)
    at org.apache.spark.api.java.JavaPairRDD$$anonfun$toScalaFunction$1.apply(JavaPairRDD.scala:1015)
    at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
    at scala.collection.Iterator$class.foreach(Iterator.scala:727)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
    at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:48)
    at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:103)
    at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:47)
    at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:273)
    at scala.collection.AbstractIterator.to(Iterator.scala:1157)
    at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:265)
    at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1157)
    at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:252)
    at scala.collection.AbstractIterator.toArray(Iterator.scala:1157)
    at org.apache.spark.rdd.RDD$$anonfun$collect$1$$anonfun$12.apply(RDD.scala:927)
    at org.apache.spark.rdd.RDD$$anonfun$collect$1$$anonfun$12.apply(RDD.scala:927)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

第105行 MainSpark 是我在编辑文章的时候在上面显示的,第61行 TarballReader

GZIPInputStream gzip = new GZIPInputStream(in);

为输入流提供一个空值 in 在上面一行:

InputStream in = this.getClass().getResourceAsStream(tarball);

我走的路对吗?如果是,我如何继续?为什么要得到这个空值,如何修复它?

cwxwcias

cwxwcias1#

一种可能的解决方案是使用 binaryFiles 手动提取内容。
斯卡拉:

import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import org.apache.spark.input.PortableDataStream
import scala.util.Try
import java.nio.charset._

def extractFiles(ps: PortableDataStream, n: Int = 1024) = Try {
  val tar = new TarArchiveInputStream(new GzipCompressorInputStream(ps.open))
  Stream.continually(Option(tar.getNextTarEntry))
    // Read until next exntry is null
    .takeWhile(_.isDefined)
    // flatten
    .flatMap(x => x)
    // Drop directories
    .filter(!_.isDirectory)
    .map(e => {
      Stream.continually {
        // Read n bytes
        val buffer = Array.fill[Byte](n)(-1)
        val i = tar.read(buffer, 0, n)
        (i, buffer.take(i))}
      // Take as long as we've read something
      .takeWhile(_._1 > 0)
      .map(_._2)
      .flatten
      .toArray})
    .toArray
}

def decode(charset: Charset = StandardCharsets.UTF_8)(bytes: Array[Byte]) = 
  new String(bytes, StandardCharsets.UTF_8)

sc.binaryFiles("somePath").flatMapValues(x => 
  extractFiles(x).toOption).mapValues(_.map(decode()))
libraryDependencies += "org.apache.commons" % "commons-compress" % "1.11"

java的完整使用示例:https://bitbucket.org/zero323/spark-multifile-targz-extract/src
Python:

import tarfile
from io import BytesIO

def extractFiles(bytes):
    tar = tarfile.open(fileobj=BytesIO(bytes), mode="r:gz")
    return [tar.extractfile(x).read() for x in tar if x.isfile()]

(sc.binaryFiles("somePath")
    .mapValues(extractFiles)
    .mapValues(lambda xs: [x.decode("utf-8") for x in xs]))
odopli94

odopli942#

在公认的答案基础上稍加改进就是改变 Option(tar.getNextTarEntry)Try(tar.getNextTarEntry).toOption.filter( _ != null) 处理格式错误/截断的 .tar.gz 以一种健壮的方式。
顺便问一下,缓冲区数组的大小有什么特别的吗?如果它更接近平均文件大小(在我的例子中可能是500k),平均速度会更快吗?或者我看到的经济放缓更可能是 Stream 相对于 while 我想那更像是 java 语。

相关问题