concept date in category spark

appears as: date, date, dates
Spark in Action, Second Edition

This is an excerpt from Manning's book Spark in Action, Second Edition.

Transformations are operations you perform on data, such as extracting a year from a date, combining two fields, normalizing data, and so on. In this chapter, you’ll learn how to use dataframe-specific functions to perform transformations, as well as methods directly attached to the dataframe API. You will merge two dataframes into one by using a SQL union-like operation. You’ll also see the difference between a dataset and a dataframe, and how to go from one to the other.

So, let’s convert the dataset back to a dataframe to study this part of the mechanism. You will study an interesting case with the date, as the date is split in a nested structure. The following listing shows the output.

Listing 3.5 Output and schema
*** Books are back in a dataframe
+--------+---+-------------+-------------+-------------+-----------------+
|authorId| id| link        | releaseDate | title       |releaseDateAsDate|
+--------+---+-------------+-------------+-------------+-----------------+
| 1      | 1 |http://amz...|[18, 0, 0,...|Fantastic ...| 2016-11-18      |
| 1      | 2 |http://amz...|[6, 0, 0, ...|Harry Pott...| 2015-10-06      |
...
only showing top 5 rows
 
root
  |-- authorId: integer (nullable = true)
  |-- id: integer (nullable = true)
  |-- link: string (nullable = true)
  |-- releaseDate: struct (nullable = true)
  |   |-- date: integer (nullable = true)
  |   |-- hours: integer (nullable = true)
  |   |-- minutes: integer (nullable = true)
  |   |-- month: integer (nullable = true)
  |   |-- seconds: integer (nullable = true)
  |   |-- time: long (nullable = true)
  |   |-- year: integer (nullable = true)
  |-- title: string (nullable = true)
   |-- releaseDateAsDate: date (nullable = true) #1

You are now ready to convert the dataset to a dataframe, and then perform a few transformations, such as changing the date from this abominable structure to a date column in your dataframe:

Dataset<Row> df2 = bookDs .toDF();

Okay, that wasn’t hard, right? To convert a dataset to a dataframe, you simply use the toDF() method. However, you still have this strange date format, so let’s correct that. The first step is to transform the date to a string with a representation of the date. In this situation, you will use the ANSI/ISO format: YYYY - MM - DD , as in 1971-10-05.

Remember that years in Java start in 1900, so 1971 is 71, while 2004 is 104. Similarly, months start at 0, making October, the tenth month of the year, month 9. Using the Java methods to build the date would require using a mapping function as you did in listing 3.3. This is the way to build a dataset or a dataframe through iteration over the data. You could also use UDFs, defined in chapter 16: