基于spark中条件的联合数据帧(scala)
我有一个文件夹,其中包括4个子文件夹,其中包含拼花文件 文件夹->A.parquet、B.parquet、C.parquet、D.parquet(子文件夹)。我的要求是根据我提供给方法的文件名来联合数据帧。 我是用代码做的基于spark中条件的联合数据帧(scala),scala,apache-spark,Scala,Apache Spark,我有一个文件夹,其中包括4个子文件夹,其中包含拼花文件 文件夹->A.parquet、B.parquet、C.parquet、D.parquet(子文件夹)。我的要求是根据我提供给方法的文件名来联合数据帧。 我是用代码做的 val df=ListDirectoriesGatewandFile(folderPath,sqlContext,A,B) def ListDirectoriesGatewandFile(folderPath:String,sqlContext:sqlContext,str
val df=ListDirectoriesGatewandFile(folderPath,sqlContext,A,B)
def ListDirectoriesGatewandFile(folderPath:String,sqlContext:sqlContext,str1:String,str2:String):数据帧={
var df:DataFrame=null
val sb=新的StringBuilder
sb.setLength(0)
var done=false
val路径=新路径(folderPath)
if(fileSystem.isDirectory(path)){
var files=fileSystem.listStatus(路径)
对于(file如果我理解您的问题,您可以简单地执行以下操作:
def listDirectoriesGetWantedFile(path: String,
sqlContext: SQLContext,
folder1: String,
folder2: String): DataFrame = {
val df1 = sqlContext.read.parquet(s"$path/$folder1")
val df2 = sqlContext.read.parquet(s"$path/$folder2")
df1.union(df2)
}
编辑
通过使用Hadoop文件系统,您可以检查文件夹上的路径是否存在。因此,您可以尝试以下操作:
def listDirectoriesGetWantedFile(path: String, sqlContext: SQLContext, folders: Seq[String]): DataFrame = {
val conf = new Configuration()
val fs = FileSystem.get(conf)
val existingFolders = folders
.map(folder => new Path(s"$path/$folder"))
.filter(fs.exists(_))
.map(_.toString)
if (existingFolders.isEmpty) {
sqlContext.emptyDataFrame
} else {
sqlContext.read.parquet(existingFolders: _*)
}
}
我需要验证某些时候folder1或Folder2可能不存在,那么读取拼花地板文件将导致错误
def listDirectoriesGetWantedFile(path: String, sqlContext: SQLContext, folders: Seq[String]): DataFrame = {
val conf = new Configuration()
val fs = FileSystem.get(conf)
val existingFolders = folders
.map(folder => new Path(s"$path/$folder"))
.filter(fs.exists(_))
.map(_.toString)
if (existingFolders.isEmpty) {
sqlContext.emptyDataFrame
} else {
sqlContext.read.parquet(existingFolders: _*)
}
}