【问题标题】:Timestamp based folder creation in scala sparkscala spark中基于时间戳的文件夹创建
【发布时间】:2017-07-14 02:26:02
【问题描述】:

我正在尝试读取基于时间戳的文件夹结构。如果我传递时间戳,那么它会根据输入路径读取文件夹结构。同样,我需要创建一个基于时间戳的文件夹结构来编写输出路径。

This is my input path 
/Desktop/user/outFiles6/test1/2017/06/09/15

Similarly my output path should be created.

我试过这样

  def buildPaths(date_key: DateTime, sc:SparkContext): (Path,Path) = {
  val (year, month, day,hour) = (date_key.toString("YYYY"), date_key.toString("MM"), date_key.toString("dd"),date_key.toString("HH"))
  val inpath_tag = new Path(
    makePath("/", Some("") :: Some("/home/user/Desktop/SparK-op/") :: Some(year) :: Some(month) :: Some(day) :: Some(hour) :: Nil)
  )

  val outpath = new Path(
    makePath("/", Some("") :: Some("/home/user/Desktop/SparK-op/") :: Some(year) :: Some(month) :: Some(day) ::  Some(hour) :: Nil)
  )
  //queryHDFS(sc, inpath_tag);
  //queryHDFS(sc, inpath_sens);
  (inpath_tag, outpath)
   }
  def makePath(char:String, components: List[Option[String]]) = components.flatten mkString char;

  } 
  }

我不知道如何继续。任何构建逻辑的帮助将不胜感激。

【问题讨论】:

  • 您遇到的具体问题是什么? Path 来自哪里?例如。如果是java.nio.file.Path,则不能用new创建,应使用Paths.get
  • 它的hadoop路径...

标签: scala apache-spark


【解决方案1】:

您需要导入库 File 才能工作。基本上需要创建您的目录并检查是否已经存在任何目录。下面是递归创建目录的代码。

import java.io.File

def makePath(char:String, components: List[Option[String]]) = {
   var path = ""
   var pathstring = components.flatten mkString char
   var pathArray = pathstring.split("/")
   for (directory <- pathArray) {
         if( directory != ""){
             path += directory 
             //Check if path present else create
             var file = new File(path)
             if(!file.exists){
                file.mkdir
                path += "/" // separator for creating next directory
             }
        }
    }
}

希望对你有帮助!

【讨论】:

    【解决方案2】:

    我假设您使用 Spark SQL 的 Dataset/DataFrame,并且没有严格限制输出文件夹结构的外观。如果是这样,您可以简单地使用标准 Spark/Hive 方式进行分区

      df.write.partitionBy("year", "month", "day").format("parquet").save(outPath)
    

    Yoy 会将您的输出文件保存在 outPath/year=2017/month=12/day=10 下的文件中。

    【讨论】:

      猜你喜欢
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 2018-09-26
      相关资源
      最近更新 更多