以下是我用来将数据帧写入JSON的代码。我从zeppelin运行此代码:
conn.connection string="Persist Security Info=True;User Id=xx;Password=xx;Data Source=Server2;Initial Catalog=database2"
我期望在/tmp/out.json文件中写入数据帧数据。但是它创建的目录名为" /tmp/out.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")
这些文件都没有JSON数据。我在这里缺少什么?
答案 0 :(得分:0)
你有一些选择:
df.rdd.collect()
将数据发送给驱动程序并写入文件。您将使用标准的scala io库,因此不会进行任何分区。这样做的缺点是必须将所有数据从执行程序提取到驱动程序,这可能很慢或不可行,具体取决于数据量和驱动程序资源。e.g:
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.
}