2016-12-02 53 views
0

以下是我用于将数据帧写入JSON的代码。我从飞艇上运行此代码:无法将火花数据帧写入json文件

val df = Seq((2012, 8, "Batman", 9.8), (2012, 8, "Hero", 8.7), (2012, 7, "Robot", 5.5), (2011, 7, "Git", 2.0)).toDF("year", "month", "title", "rating") 
df.write.json("/tmp/out.json") 

我想到的是写在/tmp/out.json文件数据帧的数据。然而,它是创建名称为“/tmp/out.json”目录里面,我觉得以下两个文件:

_SUCCESS 
._SUCCESS.crc 

这些文件都不是有JSON数据。我在这里错过了什么?

+1

是你运行一个集群还是只在本地?如果集群是否检查了执行程序上的输出目录,而不是在驱动程序机器上? – ImDarrenG

+0

@ImDarrenG我可以在执行器上看到json数据。它被分割成执行者。有没有办法让一个json文件中的所有json数据? –

+0

是的,有可能,请参阅:http://stackoverflow.com/a/40594798/7098262 – Mariusz

回答

0

你有一些选择:

  • 写入共享位置,(不使用星火办合并)
  • df.rdd.collect()数据到驱动器合并文件,并写入文件。您将使用标准的Scala io库,因此不会有任何分区。这有一个缺点,就是不得不将所有数据从执行程序提取到驱动程序,根据数据量和驱动程序资源的不同,速度可能很慢或不可行。
  • 比收集整个数据集更好的方法是收集反过来每个分区和流数据到一个文件上的驱动程序

如:

val rdd = df.rdd 
for (p <- rdd.partitions) { 
    val idx = p.index 
    val partRdd = rdd.mapPartitionsWithIndex(a => if (a._1 == idx) a._2 else Iterator(), true) 
    //The second argument is true to avoid rdd reshuffling 
    val data = partRdd.collect //data contains all values from a single partition 
           //in the form of array 
    //Now you can do with the data whatever you want: iterate, save to a file, etc. 
} 

https://stackoverflow.com/a/21801828/4697497