Adding StructType columns to Spark DataFrames

StructType objects define the schema of Spark DataFrames. StructType objects contain a list of StructField objects that define the name, type, and nullable flag for each column in a DataFrame.

Let’s start with an overview of StructType objects and then demonstrate how StructType columns can be added to DataFrame schemas (essentially creating a nested schema).

StructType columns are a great way to eliminate order dependencies from Spark code.

StructType overview

The DataFrame schema method returns a StructType object.

StructField(num, IntegerType, true),
StructField(letter, StringType, true)

Let’s lookat another example to see how StructType columns can be appended to DataFrames.

Appending StructType columns

Let’s take a look at the schema.

StructField(animal_interpretation, StructType(
), false)

The animal_interpretation column has a StructType type - this DataFrame has a nested schema.

It’s easier to view the schema with the printSchema method.

actualDF.printSchema() root
|-- weight: double (nullable = true)
|-- animal_type: string (nullable = true)
|-- animal_interpretation: struct (nullable = false)
| |-- is_large_animal: boolean (nullable = true)
| |-- is_mammal: boolean (nullable = true)

We can flatten the DataFrame as follows.

Using StructTypes to eliminate order dependencies

Let’s consider three custom transformations that add is_teenager, has_positive_mood, and what_to_do columns to a DataFrame.

Notice that both the withIsTeenager and withHasPositiveMood transformations must be run before the withWhatToDo transformation can be run. The functions have an order dependency because they must be run in a certain order for the code to work.

Let’s build a DataFrame and execute the functions in the right order so the code will run.

Let’s use the struct function to append a StructType column to the DataFrame and remove the order depenencies from this code.

Order dependencies can be a big problem in large Spark codebases

You might need to figure out how to call 20 functions in exactly the right order to get the desired result.

StructType columns are one way to eliminate order dependencies from your code. I’ll discuss other strategies in more detail in a future blog post!

Originally published at on January 17, 2018.