如何在Apache Spark中读取包含多个文件的zip

Abh*_*ary 7 scala apache-spark pyspark

我有一个包含多个文本文件的Zipped文件.我想读取每个文件并构建一个包含每个文件内容的RDD列表.

val test = sc.textFile("/Volumes/work/data/kaggle/dato/test/5.zip")
Run Code Online (Sandbox Code Playgroud)

将只是整个文件,但如何遍历zip的每个内容,然后使用Spark将其保存在RDD中.

我对Scala或Python很好.

Python中使用Spark的可能解决方案 -

archive = zipfile.ZipFile(archive_path, 'r')
file_paths = zipfile.ZipFile.namelist(archive)
for file_path in file_paths:
    urls = file_path.split("/")
    urlId = urls[-1].split('_')[0]
Run Code Online (Sandbox Code Playgroud)

Ata*_*ais 7

Apache Spark默认压缩支持

我在其他答案中写了所有必要的理论,你可能想参考:https://stackoverflow.com/a/45958182/1549135

读取包含多个文件的zip

我遵循@Herman给出的建议并使用了ZipInputStream.这给了我这个解决方案,它返回RDD[String]了zip内容.

import java.io.{BufferedReader, InputStreamReader}
import java.util.zip.ZipInputStream
import org.apache.spark.SparkContext
import org.apache.spark.input.PortableDataStream
import org.apache.spark.rdd.RDD

implicit class ZipSparkContext(val sc: SparkContext) extends AnyVal {

    def readFile(path: String,
                 minPartitions: Int = sc.defaultMinPartitions): RDD[String] = {

      if (path.endsWith(".zip")) {
        sc.binaryFiles(path, minPartitions)
          .flatMap { case (name: String, content: PortableDataStream) =>
            val zis = new ZipInputStream(content.open)
            Stream.continually(zis.getNextEntry)
                  .takeWhile {
                      case null => zis.close(); false
                      case _ => true
                  }
                  .flatMap { _ =>
                      val br = new BufferedReader(new InputStreamReader(zis))
                      Stream.continually(br.readLine()).takeWhile(_ != null)
                  }
        }
      } else {
        sc.textFile(path, minPartitions)
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

只需通过导入隐式类并在SparkContext上调用readFile方法来使用它:

import com.github.atais.spark.Implicits.ZipSparkContext
sc.readFile(path)
Run Code Online (Sandbox Code Playgroud)

  • 在我的例子中,@Atais Spark 没有关闭流。我尝试从 S3 读取数千个文件,但由于连接线程池耗尽而失败,但一旦我关闭代码中的流,它就可以工作。无论如何,及时清理总是一个好主意。 (2认同)

小智 4

如果您正在读取二进制文件,请使用sc.binaryFiles. 这将返回一个包含文件名和PortableDataStream. 您可以将后者输入到ZipInputStream.