Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Row-based Mapping and Filtering on DataFrames in Spark

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Comments

Spark DataFrame is an alias to Dataset[Row]. Even though a Spark DataFrame is stored as Rows in a Dataset, built-in operations/functions (in org.apache.spark.sql.functions) for Spark DataFrame are Column-based. Sometimes, there might be transformations on a DataFrame that is hard to express as Column expressions but rather evey convenient to express as Row expressions. The traditional way to resolve this issue is to wrap the row-based function into a UDF. It is worthing knowing that Spark DataFrame supports map/flatMap APIs which works on Rows. They are still experimental as Spark 2.4.3. It is suggested that you stick to Column-based operations/functions until the Row-based methods mature.

Loading...
Loading...
org.apache.spark.sql.SparkSession$implicits$@33a3ab71
+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
|   1|   a| foo| 3.0|
|   2|   b| bar| 4.0|
|   3|   c| foo| 5.0|
|   4|   d| bar| 7.0|
+----+----+----+----+

null

Filter

+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
|   1|   a| foo| 3.0|
|   2|   b| bar| 4.0|
+----+----+----+----+

+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
|   1|   a| foo| 3.0|
|   3|   c| foo| 5.0|
+----+----+----+----+

Map

<console>:112: error: Unable to find encoder for type stored in a Dataset.  Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.
       df.map {
              ^
+----+-------+
| age|   name|
+----+-------+
|null|Michael|
|  30|   Andy|
|  19| Justin|
+----+-------+

+-------+
|  value|
+-------+
|Michael|
|   Andy|
| Justin|
+-------+

+-----+
|value|
+-----+
|   30|
|   19|
+-----+

Apply Operation to All Columns

+---+---+---+
|  x|  y|  z|
+---+---+---+
|  a|  B|  c|
|  D|  e|  F|
+---+---+---+

+---+---+---+
|  x|  y|  z|
+---+---+---+
|  A|  B|  C|
|  D|  E|  F|
+---+---+---+