Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 25

Spark and Parquet: Reading and Writing Data

This lesson is built with resources from spark.apache.org and datacamp.com.

Hello! Welcome back.

In our last lesson, we explored the "why" behind columnar file formats, establishing that Apache Parquet's design offers massive I/O efficiency through column pruning, better compression, and predicate pushdown. As a data architect, understanding this theory is the first step. The second, equally crucial step, is putting it into practice.

Today's lesson bridges that gap. Your learning outcome is to read from and write to Parquet files using Spark. We will move from the conceptual advantages to the concrete commands and configurations you'll use daily to build performant and reliable data pipelines.

The Foundation: Reading and Writing Parquet in Spark

Apache Spark's integration with Parquet is seamless because they are both foundational technologies in the modern data stack. Spark has built-in, highly optimized readers and writers for Parquet, making it the default and recommended file format for most analytical workloads.

The basic syntax is straightforward and intuitive. Let's look at the official Spark documentation for the core commands.

Parquet Files - Spark 4.1.0 Documentation

The official Spark documentation provides the authoritative source for data source operations. This section shows the fundamental code for reading and writing Parquet files.

Please review the short introduction and then focus on the code examples under the heading "Loading Data Programmatically". You can focus on the Python example. Notice how the schema is automatically preserved when writing and then reading the file back.

As you saw in the documentation, the core operations are methods on the DataFrameReader (spark.read) and DataFrameWriter (df.write).

Let's assume you have a DataFrame named sales_df.

Writing a DataFrame to Parquet:

# The simplest way to write a DataFrame to a Parquet file
sales_df.write.parquet("path/to/your/output/sales.parquet")

Reading a Parquet file into a DataFrame:

# Spark reads the Parquet file(s) and infers the schema automatically
read_sales_df = spark.read.parquet("path/to/your/output/sales.parquet")

One of Parquet's key features, as mentioned in the docs, is that it is a self-describing format. The schema (column names, data types) is stored in the file's metadata. This means you don't need to define the schema when you read the data, which is a significant improvement in both convenience and reliability over formats like CSV.


Essential Writing Options for Architects

Simply writing a file is often not enough. In a real-world architectural design, you need to control how data is written to ensure your pipelines are robust, efficient, and maintainable. This is done using various options with the DataFrameWriter.

1. Save Modes: Handling Existing Data

What should happen if you try to write to a location that already contains data? The mode() option lets you define this behavior. The most common modes are:

  • "overwrite": Deletes the existing data at the location and replaces it with the new data. Essential for jobs that perform full daily refreshes.
  • "append": Adds the new data to the existing data. Useful for incrementally adding new records.
  • "ignore": If data already exists at the location, do nothing. The write operation is skipped.
  • "errorifexists" (or "error"): The default mode. If data exists, an exception is thrown and the job fails. This is a safety feature to prevent accidental data loss.

Example:

# This will completely replace the content at the path if it exists
sales_df.write.mode("overwrite").parquet("path/to/output")

2. Partitioning: Optimizing for Read Performance

In the last lesson, we discussed how predicate pushdown allows Spark to skip reading data. You can proactively design for this by partitioning your data when you write it. The partitionBy() method creates a subdirectory structure based on the unique values in the specified column(s).

When you later read this data with a filter on a partition column, Spark can skip entire directories, leading to a massive reduction in I/O.

Example:

# Write the data, creating subdirectories for each unique country and sale_date
sales_df.write.mode("overwrite").partitionBy("country", "sale_date").parquet("path/to/partitioned_sales")

This would create a directory structure like:

path/to/partitioned_sales/
├── country=USA/
│   ├── sale_date=2024-10-26/
│   │   └── part-00000-....snappy.parquet
│   └── sale_date=2024-10-27/
│       └── part-00000-....snappy.parquet
└── country=CAN/
    └── sale_date=2024-10-26/
        └── part-00000-....snappy.parquet

A query like spark.read.parquet("...").where("country = 'USA'") would then completely ignore the country=CAN directory.

3. Compression: Balancing Speed and Size

As we know, Parquet's columnar nature allows for great compression. You can specify the compression codec using the option() method. Common choices include:

  • "snappy": (Default) Good balance between compression ratio and speed. Fast to compress and decompress.
  • "gzip": Higher compression ratio (smaller files) but more CPU-intensive. Good for "cold" data that is infrequently accessed.
  • "zstd": A modern codec that often provides better compression than Snappy at similar speeds.

Example:

# Write the data using gzip compression for maximum space savings
sales_df.write.option("compression", "gzip").mode("overwrite").parquet("path/to/output")
Test your understanding!

You are designing a data pipeline that creates a summary table of user events. The job runs every hour to completely replace the previous hour's summary. The primary use case for this summary table is to power a dashboard that allows users to filter by event_type (e.g., 'click', 'purchase').

Which Spark write command would be most appropriate for this scenario? Explain your choice of methods and options.

Show answer

The most appropriate command would be:

events_summary_df.write.mode("overwrite").partitionBy("event_type").parquet("path/to/event_summary")

Explanation:

  1. mode("overwrite"): This is necessary because the job runs every hour to completely replace the previous summary. Using "overwrite" ensures the old data is cleared out.
  2. partitionBy("event_type"): Since the main query pattern is filtering by event_type, partitioning by this column is the single most effective optimization. It will allow queries for a specific event type to skip reading the data for all other types, making the dashboard much faster.

Advanced Reading: Handling Schema Evolution

In a dynamic business environment, data schemas change. A new column might be added to a source system, or an existing one removed. As an architect, you must design pipelines that can handle this gracefully. Parquet and Spark provide a powerful feature for this called schema merging.

Imagine one job run writes Parquet files with schema (id, name). The next day, the schema changes to (id, name, email). Now your directory contains Parquet files with two different structures. By default, Spark will pick the schema from one of the files and ignore the other, which can lead to missing data.

By enabling the mergeSchema option, you can instruct Spark to scan all the files and create a unified schema that includes all columns from all files.

Let's see how this works in the official documentation.

Parquet Files - Spark 4.1.0 Documentation

This section of the Spark docs provides a practical example of how to handle evolving schemas.

Read the section "Schema Merging". Pay attention to the example where two DataFrames with different columns (double, triple) are written to the same parent directory. Notice how using .option("mergeSchema", "true") allows the final DataFrame to contain all three columns (single, double, triple).

The syntax is simple but the concept is critical for building resilient systems:

# Read from a directory containing Parquet files with different schemas
merged_df = spark.read.option("mergeSchema", "true").parquet("path/to/data_with_evolving_schema")

# The resulting merged_df will have a schema that is the union of all columns.
# For rows from files that lack a certain column, the value will be null.
merged_df.printSchema()

Putting It All Together

Let's look at one more resource that provides a clean, end-to-end example of reading and writing Parquet with Spark, reinforcing what we've just covered.

Apache Parquet Explained: A Guide for Data Professionals

This article from Datacamp provides a friendly, hands-on walkthrough of using Parquet with PySpark.

Scroll down to the heading "Integrate with big data frameworks". Review the simple code snippets that show creating a Spark DataFrame, writing it to Parquet, and reading it back.

This simple example encapsulates the core workflow: create or transform your data in a DataFrame, then persist it efficiently using write.parquet().


Conclusion

You have now moved from the theory of why Parquet is efficient to the practice of how to use it with Spark. This is a fundamental skill for any data professional in the Spark ecosystem.

Key Takeaways:

  • The basic commands are spark.read.parquet("path") and df.write.parquet("path").
  • Parquet is self-describing, so Spark automatically infers the schema on read.
  • Writing options are key for architecture:
    • mode() controls how to handle existing data (e.g., "overwrite", "append").
    • partitionBy() physically organizes data to optimize read queries.
    • option("compression", ...) allows you to tune the trade-off between file size and CPU usage.
  • Reading options handle real-world complexity:
    • option("mergeSchema", "true") allows you to build robust pipelines that can adapt to schema changes over time.

In our next lesson, we'll continue our focus on performance. While Parquet optimizes I/O from disk, we will learn how to use caching and persistence to speed up iterative or multi-stage Spark jobs by intelligently keeping data in memory, avoiding the need to read it from disk repeatedly.