8

I have a list of nested dictionaries, e.g. ds = [{'a': {'b': {'c': 1}}}] and want to create a spark DataFrame from it while inferring schema of nested dictionaries. Using sqlContext.createDataFrame(ds).printSchema() gives me following schema

root
 |-- a: map (nullable = true)
 |    |-- key: string
 |    |-- value: map (valueContainsNull = true)
 |    |    |-- key: string
 |    |    |-- value: long (valueContainsNull = true)

but what I need is this

root
 |-- a: struct (nullable = true)
 |    |-- b: struct (nullable = true)
 |    |    |-- c: long (nullable = true)

The second schema can be created by first converting dictionaries to JSON and then load it with jsonRDD like this sqlContext.jsonRDD(sc.parallelize([json.dumps(ds[0])])).printSchema(). But this would be quite cumbersome for large files.

I thought about converting dictionaries to pyspark.sql.Row() objects hoping that dataframe will infer the schema, but it didn't work when dictionaries had different schemas (e.g. first was missing some key).

Is there any other way to do this? Thanks!

1 Answer 1

2

I think this will help.

import json
ds = [{'a': {'b': {'c': 1}}}]
ds2 = [json.dumps(item) for item in ds]
df = sqlCtx.jsonRDD(sc.parallelize(ds2))
df.printSchema()

Then,

root
|-- a: struct (nullable = true)
|    |-- b: struct (nullable = true)
|    |    |-- c: long (nullable = true)
2
  • I wanted to avoid that (see my question). I was hoping there is a way to do it without having to create RDD from dictionaries just to get it's schema.
    – Marigold
    Jun 18, 2015 at 19:05
  • 2
    Sorry for missing your middle paragraph.Unfortunately, 'infer schema from dictionary' feature deprecated now, I hope there is another way too.
    – hyim
    Jun 18, 2015 at 22:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.