在EMR中使用Spark Scala获取S3对象大小(文件夹,文件)

Dic*_*nus 3 scala amazon-s3 amazon-web-services apache-spark

我正在尝试scala 从命令行EMR 获取某些S3文件夹的文件夹大小。

我在S3中将JSON数据存储为GZ文件。我发现我可以计算文件中JSON记录的数量:

spark.read.json("s3://mybucket/subfolder/subsubfolder/").count
Run Code Online (Sandbox Code Playgroud)

但是现在我需要知道数据占多少GB。

我正在寻找一些选项来获取不同文件的大小,而不是整个文件夹的大小。

Ram*_*ram 5

我正在寻找一些选项来获取不同文件的大小,而不是整个文件夹的大小。

解决方案:


选项1:

通过FileSystem获得s3访问

    val fs = FileSystem.get(new URI(ipPath), spark.sparkContext.hadoopConfiguration)
Run Code Online (Sandbox Code Playgroud)

注意 :

1) new URI否则很重要,它将连接到s3文件系统(object store :-))路径的hadoop文件系统路径。使用新的URI,您可以在s3:// 此处提供方案。

2)org.apache.commons.io.FileUtils.byteCountToDisplaySize将以GB MB等给出文件系统的显示大小...

      /**
    * recursively print file sizes
    *
    * @param filePath
    * @param fs
    * @return
    */
@throws[FileNotFoundException]
@throws[IOException]
  def getDisplaysizesOfS3Files(filePath: org.apache.hadoop.fs.Path, fs: org.apache.hadoop.fs.FileSystem): scala.collection.mutable.ListBuffer[String] = {
    val fileList = new scala.collection.mutable.ListBuffer[String]
    val fileStatus = fs.listStatus(filePath)
    for (fileStat <- fileStatus) {
      println(s"file path Name : ${fileStat.getPath.toString} length is  ${fileStat.getLen}")
      if (fileStat.isDirectory) fileList ++= (getDisplaysizesOfS3Files(fileStat.getPath, fs))
      else if (fileStat.getLen > 0 && !fileStat.getPath.toString.isEmpty) {
        println("fileStat.getPath.toString" + fileStat.getPath.toString)
        fileList += fileStat.getPath.toString
        val size = fileStat.getLen
        val display = org.apache.commons.io.FileUtils.byteCountToDisplaySize(size)
        println(" length zero files \n " + fileStat)
        println("Name    = " + fileStat.getPath().getName());
        println("Size    = " + size);
        println("Display = " + display);
      } else if (fileStat.getLen == 0) {
        println(" length zero files \n " + fileStat)

      }
    }
    fileList
  }
Run Code Online (Sandbox Code Playgroud)

根据您的要求,您可以修改代码...您可以汇总所有不同的文件。

选项2:使用简单又香脆getContentSummary

implicit val spark = SparkSession.builder().appName("ObjectSummary").getOrCreate()
  /**
    * getDisplaysizesOfS3Files 
    * @param path
    * @param spark [[org.apache.spark.sql.SparkSession]]
    */
  def getDisplaysizesOfS3Files(path: String)( implicit spark: org.apache.spark.sql.SparkSession): Unit = {
    val filePath = new org.apache.hadoop.fs.Path(path)
    val fileSystem = filePath.getFileSystem(spark.sparkContext.hadoopConfiguration)
    val size = fileSystem.getContentSummary(filePath).getLength
    val display = org.apache.commons.io.FileUtils.byteCountToDisplaySize(size)
    println("path    = " + path);
    println("Size    = " + size);
    println("Display = " + display);
  } 
Run Code Online (Sandbox Code Playgroud)

注意:以上显示的任何选项也适用于本地或hdfs或s3