Apache spark 如何使(Spark1.6)saveAsTextFile附加现有文件?
在SparkSQL中,我使用DF.wirte.mode(SaveMode.Append).json(xxxx),但是这个方法像Apache spark 如何使(Spark1.6)saveAsTextFile附加现有文件?,apache-spark,apache-spark-sql,spark-streaming,spark-dataframe,Apache Spark,Apache Spark Sql,Spark Streaming,Spark Dataframe,在SparkSQL中,我使用DF.wirte.mode(SaveMode.Append).json(xxxx),但是这个方法像 文件名太复杂且随机,我无法使用api获取。因此我想使用saveAstextfile,因为文件名不复杂且不规则,但我不知道如何在同一目录中追加文件?感谢您的时间。在Spark 1.5上工作,我认为这是正确的用法 dataframe.write().mode(SaveMode.Append).format(FILE_FORMAT).**partitionBy**("para
文件名太复杂且随机,我无法使用api获取。因此我想使用saveAstextfile,因为文件名不复杂且不规则,但我不知道如何在同一目录中追加文件?感谢您的时间。在Spark 1.5上工作,我认为这是正确的用法
dataframe.write().mode(SaveMode.Append).format(FILE_FORMAT).**partitionBy**("parameter1", "parameter2").save(path);
由于spark使用HDFS,这是它产生的典型输出。您可以使用
FileUtil
将文件合并回一个文件。这是一个有效的解决方案,因为它不需要spark通过将数据划分为1来将整个数据收集到单个内存中。这就是我所遵循的方法
import org.apache.hadoop.fs.{FileSystem, FileUtil, Path}
val hadoopConf = sqlContext.sparkContext.hadoopConfiguration
val hdfs = FileSystem.get(hadoopConf)
val mergedPath = "merged-" + filePath + ".json"
val merged = new Path(mergedPath)
if (hdfs.exists(merged)) {
hdfs.delete(merged, true)
}
df.wirte.mode(SaveMode.Append).json(filePath)
FileUtil.copyMerge(hdfs, path, hdfs, merged, false, hadoopConf, null)
您可以使用
mergedPath
location读取单个文件。希望对你有所帮助。你可以试试我在某处找到的这个方法。
谢谢,我想实现这一点,例如,在HDFS中,我有3个文件,如part-00000、part-00001、part-00002,我的要求是将这些文件转换为part-00000,所以我可以使用copyMerge转换为现有文件吗?我不太清楚你的问题。如果您询问是否可以将part-00000、part-00001、part-00002合并为part-00000,则上述代码就是这样做的。您只需要按照自己的意愿制定mergedPath。这就是你要找的吗?Spark中有
coalesce
函数,可以将所有内容合并到一个文件中。即使我面临同样的问题@yixiyixI,你是否已经修复了它?我想你忘了导入:“import org.apache.hadoop.conf.Configuration”
import org.apache.hadoop.fs.{ FileSystem, FileUtil, Path }
def saveAsTextFileAndMerge[T](hdfsServer: String, fileName: String, rdd: RDD[T]) = {
val sourceFile = hdfsServer + "/tmp/"
rdd.saveAsTextFile(sourceFile)
val dstPath = hdfsServer + "/final/"
merge(sourceFile, dstPath, fileName)
}
def merge(srcPath: String, dstPath: String, fileName: String): Unit = {
val hadoopConfig = new Configuration()
val hdfs = FileSystem.get(hadoopConfig)
val destinationPath = new Path(dstPath)
if (!hdfs.exists(destinationPath)) {
hdfs.mkdirs(destinationPath)
}
FileUtil.copyMerge(hdfs, new Path(srcPath), hdfs, new Path(dstPath + "/" + fileName), false, hadoopConfig, null)
}