I would like to know what is the best practice for reading a newline delimited JSON file into a dataframe. Critically, one of the (required) fields in each record maps to an object that is not guaranteed to have the same sub-fields (ie the schema is non-uniform across all the records).
For example, an input file might look like:
{"id": 1, "type": "foo", "data": {"key0": "foo", "key2": "meh"}}
{"id": 2, "type": "bar", "data": {"key2": "poo", "key3": "pants"}}
{"id": 3, "type": "baz", "data": {"key3": "moo"}}
In this case the fields id, type, and data will be present in all records, but the struct mapped to by data will have a heterogeneous schema.
I have two approaches for dealing wi the non-uniformity of the data column:
- let spark infer the schema:
df = spark.read.options(samplingRatio=1.0).json('s3://bucket/path/to/newline_separated_json.txt')
The obvious issue with this approach is the need to sample every record to determine the super-set of fields/schemas that will be the final schema. This may be prohibitively expensive given a dataset in the low 100s of millions of records? Or...
- Tell spark to coerce the data field into a JSON string, and then just have a schema comprised of three top-level string fields,
id,type,data. And here I'm not really sure the best way to proceed. For example I am assuming just declaring thedatafield to be a string as in the following, will not work because it is not explicitly doing the equivalent ofjson.dumps?
schema = StructType([
StructField("id", StringType(), true),
StructField("type", StringType(), true),
StructField("data", StringType(), true)
])
df = spark.read.json('s3://bucket/path/to/newline_separated_json.txt', schema=schema)
If I want to avoid the cost of scanning the full dataset incurred by option 1, what is the best way to ingest this file and keep the data field as a JSON string?
Thank you