使用架构中的所有键(包括空列)将spark数据集写入json [英] write a spark Dataset to json with all keys in the schema, including null columns

查看:146
本文介绍了使用架构中的所有键(包括空列)将spark数据集写入json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下方法将数据集写入json:

I am writing a dataset to json using:

ds.coalesce(1).write.format("json").option("nullValue",null).save("project/src/test/resources")

对于包含具有空值列的记录,json文档根本不会写入该键.

For records that have columns with null values, the json document does not write that key at all.

有没有一种方法可以对json输出强制使用null值键?

Is there a way to enforce null value keys to the json output?

这是必需的,因为我使用此json将其读取到另一个数据集(在测试用例中),并且如果某些文档在case类中没有所有键,则无法强制执行架构(我通过放置json进行读取资源文件夹下的文件,然后通过RDD [String]转换为数据集,如下所述:

This is needed since I use this json to read it onto another dataset (in a test case) and cannot enforce a schema if some documents do not have all the keys in the case class (I am reading it by putting the json file under resources folder and transforming to a dataset via RDD[String], as explained here: https://databaseline.bitbucket.io/a-quickie-on-reading-json-resource-files-in-apache-spark/)

推荐答案

我同意@philantrovert.

I agree with @philantrovert.

ds.na.fill("")
  .coalesce(1)
  .write
  .format("json")
  .save("project/src/test/resources")

由于DataSets是不可变的,因此您无需更改ds中的数据,您可以在以下任何代码中对其进行处理(包括空值和所有值).您只是在保存的文件中用空字符串替换空值.

Since DataSets are immutable you are not altering the data in ds and you can process it (complete with null values and all) in any following code. You are simply replacing null values with an empty string in the saved file.

这篇关于使用架构中的所有键(包括空列)将spark数据集写入json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆