In the previous lesson you saw where the files of a Big Data platform are stored: in a distributed file system or an object store. Now it is time to look inside those files. The same data can be written in very different ways, and the choice is no minor technical detail: it determines how much space the data takes up (which in HDFS is paid for three times over), how long a query takes and how much each analysis costs in the cloud.

In this lesson you will compare the text formats you already know, CSV and JSON, with the three binary formats native to Big Data: Avro, Parquet and ORC. You will understand the difference between storing data by rows and by columns, what compression brings and, at the end, you will convert NovaMarket's files to Parquet to measure the result on your own machine.

Why the format matters

Think of the question Marc asks himself every day: "how many purchases were made from each type of device?". Answering it takes only two of the seven fields in web_events: event_type and device. With the JSON file, however, there is no choice but to read all 37 MB, line by line, parse each object and throw nearly everything away.

At practice scale it makes no difference. At real scale, a year of events is 2.79 TB, and reading all of it to use a small part is a waste of time and money. A good format acts on four factors:

Factor What it means
Size How many bytes the same data takes up
Read speed Whether you can read only what you need or have to go through everything
Schema Whether the file knows which columns it contains and what type they are
Parallelism Whether several processes can read different pieces of the file at once

Text formats: CSV and JSON Lines

These are the formats of your files in ~/novamarket/data/. They have real virtues: they are human-readable, every tool understands them and they are the natural format in which data arrives from other systems. That is why they still reign supreme for data exchange.

But as a format for storage and analysis at scale they have serious limits:

Limitation CSV JSON Lines
No types Everything is text: 1353.13 could be a number or a string; you have to guess or declare it on every read Distinguishes numbers, strings, booleans and null, but not dates, nor integers from decimals with any precision
No reliable schema The header, if there is one, only gives names Each line can have different fields
Bulky Numbers are written as text, character by character On top of that, it repeats the name of every field on every line
Full read All the columns have to be read even if only one is of interest The same
Ambiguities Separator, quotes, line breaks inside a field, encoding, empty values Fewer, but parsing is slow

Two examples with your data. In orders.csv, an empty total_amount: is it a zero, an empty string or a missing value? The file does not say. And in web_events.json, the text "event_time": is written out 200,500 times: a considerable share of the 37 MB is repeated field names.

Row orientation and column orientation

This is the central idea of the lesson. Let's take three orders:

order_id customer_id total_amount channel
1 799 1353.13 app
2 86 601.58 web
3 412 89.90 web

A row-oriented format writes one complete record after another to disk:

[1, 799, 1353.13, app] [2, 86, 601.58, web] [3, 412, 89.90, web]

A column-oriented (or columnar) format writes all the values of one column, then all those of the next, and so on:

order_id:     [1, 2, 3]
customer_id:  [799, 86, 412]
total_amount: [1353.13, 601.58, 89.90]
channel:      [app, web, web]

The difference looks cosmetic, but it has two huge consequences for analysis:

  • Only what is needed gets read. To add up total_amount, a columnar format goes straight to the stretch of the file where that column lives and does not touch the others. With 6 columns that saves a good part of the read; with the 200 columns of a real analytical table, nearly all of it.
  • It compresses much better. The values in a single column resemble one another: channel contains only web and app; order_id is an increasing sequence. Similar, adjacent data compresses very well.

In return, writing or reading one complete record is more laborious in a columnar format, because its values are scattered around the file.

Row-oriented Column-oriented
Writing records one at a time Fast and simple Costly: it writes in large batches
Reading one complete record Fast Slower
Reading a few columns from many rows Slow: it reads everything Very fast
Compression Good Excellent
Typical use Ingestion, messaging, transactions Analysis, data lakes, data warehouses
Formats CSV, JSON, Avro Parquet, ORC

The rule that follows is simple: rows for writing, columns for analysing.

Avro: rows with a schema

Apache Avro is a row-oriented binary format. It stores complete records one after another, like CSV, but solves CSV's problems:

  • It carries a schema: the description of the fields and their types, written in JSON, which travels with the data.
  • It is compact: since the schema already says which fields there are and in what order, the data is stored in binary without repeating the names.
  • It is splittable: the file is organised into independent blocks, so several processes can read it in parallel even when it is compressed.

This is what the Avro schema for a NovaMarket web event would look like:

{
  "type": "record",
  "name": "WebEvent",
  "fields": [
    {"name": "event_id",    "type": "string"},
    {"name": "customer_id", "type": ["null", "long"], "default": null},
    {"name": "session_id",  "type": "string"},
    {"name": "event_type",  "type": "string"},
    {"name": "product_id",  "type": ["null", "long"], "default": null},
    {"name": "event_time",  "type": "string"},
    {"name": "device",      "type": ["null", "string"], "default": null}
  ]
}
  • "type": "record" indicates that a record with several fields is being described.
  • Each field has a name and a type. The type ["null", "long"] means "null or long integer": it is the way to declare that a field is optional. It fits what you know about the data: customer_id is null for anonymous visitors and product_id is null for searches.
  • "default": null is the value that will be used if the field is not present. You will see why that matters in a moment.

Avro is the format of choice when data is written record by record and travels between systems: ingestion and, above all, messaging systems such as Kafka (lesson 03-05). In NovaMarket's architecture, the events the website sends to the messaging layer would be Avro messages.

Parquet and ORC: columnar formats

Apache Parquet and Apache ORC are the two major columnar binary formats. Their internal differences are matters of detail; the idea is the same.

How a Parquet file is organised

Parquet file
├── Row group 1  (e.g. the first million rows)
│   ├── Column event_id     → encoded and compressed values + statistics (min, max, nulls)
│   ├── Column event_type   → encoded and compressed values + statistics
│   └── ...
├── Row group 2
│   └── ...
└── File footer: full schema + position and statistics of each chunk
  • The rows are divided into large row groups. Within each group, the data is stored column by column.
  • Before being compressed, each column is encoded intelligently. With dictionary encoding, for example, a column such as event_type does not store the texts product_view, search… 200,000 times over, but a small dictionary with the four values and, for each row, a number from 0 to 3.
  • The file footer contains the schema and, for each column chunk, its statistics: minimum value, maximum value and number of nulls.

Column pruning and predicate pushdown

That structure enables two optimisations that engines such as Spark apply automatically:

  • Column pruning: if the query only uses event_type and device, the engine reads from the footer where those two columns are and skips the other five.
  • Predicate pushdown: if the query asks for total_amount > 1000 and the statistics of a row group say its maximum is 800, the engine discards the whole group without reading it. The filter is "pushed down" to the file itself, instead of being applied after the data has been loaded.

An analogy: looking something up in a book with an index. You do not read every page (rows) or all the text on each page (columns); the index tells you which chapters might contain what you are after and you go straight to them.

Parquet or ORC

Parquet ORC
Origin Twitter and Cloudera The Apache Hive project
Natural ecosystem Spark, most engines and cloud services, table formats (lesson 02-05) Hive and platforms descended from Hadoop
Performance and compression Excellent Excellent, very similar
Recommendation The default choice today Fine if your platform already uses it

In this course we will use Parquet, which is Spark's default format and the most widespread.

Embedded schema and schema evolution

Avro, Parquet and ORC share a property that CSV lacks: they are self-describing. The schema travels inside the file. Whoever reads it has nothing to guess: they know that total_amount is a decimal number and order_date a date with a time, and that a missing value is a null and not an empty string.

But data changes. Suppose the web team decides to add a browser field to the events. Yesterday's files do not have it; tomorrow's will. A format's ability to live with these changes is called schema evolution.

Change Is it safe? Why
Adding an optional field (with a default value) Yes Old data is read with the default value or null
Removing a field nobody uses Usually yes New readers ignore it
Widening a type (integer → long integer) Usually yes No information is lost
Renaming a field No, not without special care To the format it is "delete one and add another"
Changing a type incompatibly (text → number) No The old data cannot be interpreted
  • Avro is the strongest in this area: it distinguishes between the schema a piece of data was written with and the schema you want to read it with, and reconciles them using precise rules. Hence the "default": null in the earlier example.
  • Parquet and ORC have no trouble with added columns: when old and new files are read together, the missing columns are filled with nulls.

A practical rule for NovaMarket: adding optional fields is cheap; renaming or changing types is expensive. It pays to think the names through properly from the start.

Compression codecs

A codec is an algorithm that compresses and decompresses data. They all trade the same things: how much they shrink (ratio) against how long they take (speed, that is, CPU).

Codec Compression ratio Speed Typical use
gzip High Slow Archiving, exchange files; data that is rarely read
snappy Moderate Very fast The classic default in Parquet; frequently used data
lz4 Moderate The fastest Temporary data, streams, when latency is what counts
zstd High (similar to or better than gzip) Fast A good all-round balance; increasingly common as the default

Splittable files

There is a third factor, unique to distributed processing. A file is splittable if several processes can start reading it from different points, each taking its own part.

An uncompressed CSV is: you just jump to a position and move forward to the next line break. But if you compress that whole CSV with gzip, it no longer is: to decompress byte one million you must have decompressed all the ones before it. A 50 GB events.json.gz file can only be read by one process, from start to finish, however many nodes the cluster has.

Combination Splittable?
Uncompressed CSV or JSON Lines Yes
CSV or JSON Lines compressed whole with gzip or snappy No
Avro, Parquet or ORC, with any codec Yes

The binary formats solve this because they compress on the inside: each block (Avro) or each column chunk (Parquet, ORC) is compressed separately, and the file keeps its structure. That is another weighty reason to prefer them.

Hands-on: from CSV and JSON to Parquet with PySpark

You are going to convert orders.csv and web_events.json to Parquet and measure the difference. The results will go into a scratch folder, ~/novamarket/lake_scratch/, which you can delete afterwards.

We will use Spark, which is explained in depth in lesson 03-02. Here it is enough to read each line as "read this file" or "write this table in this format".

Go to ~/novamarket, activate the virtual environment and create convert_to_parquet.py:

from pathlib import Path
from pyspark.sql import SparkSession

BASE = Path.home() / "novamarket"
DATA_DIR = BASE / "data"
SCRATCH_DIR = BASE / "lake_scratch"


def size_mb(path):
    """Adds up the size of a file or of all the files in a folder."""
    path = Path(path)
    files = [path] if path.is_file() else [f for f in path.rglob("*") if f.is_file()]
    return sum(f.stat().st_size for f in files) / 1_000_000


spark = (
    SparkSession.builder
    .master("local[*]")
    .appName("convert_to_parquet")
    .getOrCreate()
)
spark.sparkContext.setLogLevel("ERROR")

# 1. Reading the text files
orders = spark.read.csv(str(DATA_DIR / "orders.csv"), header=True, inferSchema=True)
events = spark.read.json(str(DATA_DIR / "web_events.json"))

orders.printSchema()
events.printSchema()

# 2. Writing to Parquet (snappy compression, the default)
orders.write.mode("overwrite").parquet(str(SCRATCH_DIR / "orders_parquet"))
events.write.mode("overwrite").parquet(str(SCRATCH_DIR / "events_parquet"))

# 3. The same events with other codecs and as compressed JSON
events.write.mode("overwrite").option("compression", "zstd").parquet(str(SCRATCH_DIR / "events_parquet_zstd"))
events.write.mode("overwrite").option("compression", "none").parquet(str(SCRATCH_DIR / "events_parquet_uncompressed"))
events.write.mode("overwrite").option("compression", "gzip").json(str(SCRATCH_DIR / "events_json_gzip"))

# 4. Size comparison
print(f"{'Dataset':<34}{'MB':>8}")
for name, path in [
    ("orders.csv", DATA_DIR / "orders.csv"),
    ("orders_parquet (snappy)", SCRATCH_DIR / "orders_parquet"),
    ("web_events.json", DATA_DIR / "web_events.json"),
    ("events_json_gzip", SCRATCH_DIR / "events_json_gzip"),
    ("events_parquet_uncompressed", SCRATCH_DIR / "events_parquet_uncompressed"),
    ("events_parquet (snappy)", SCRATCH_DIR / "events_parquet"),
    ("events_parquet_zstd", SCRATCH_DIR / "events_parquet_zstd"),
]:
    print(f"{name:<34}{size_mb(path):>8.2f}")

spark.stop()

The essentials of each part:

  • size_mb is ordinary Python: it adds up the size of all the files in a folder. It is needed because, as you will see, Spark does not write a file but a folder.
  • setLogLevel("ERROR") cuts down Spark's informational messages so that the output is easier to read.
  • spark.read.csv(..., header=True, inferSchema=True): you already used header=True in lesson 01-05. inferSchema=True asks Spark to read the file and work out the type of each column; without that option, they would all be text. This is precisely CSV's shortcoming: the types have to be guessed.
  • spark.read.json(...) reads JSON Lines and infers the schema by examining the objects.
  • printSchema() shows the columns and types of a table.
  • .write.mode("overwrite").parquet(path) writes the table in Parquet. mode("overwrite") replaces the contents if the folder already exists, which lets you run the script several times.
  • .option("compression", ...) chooses the codec.

Run it with python convert_to_parquet.py. First you will see the two schemas:

root
 |-- order_id: integer (nullable = true)
 |-- customer_id: integer (nullable = true)
 |-- order_date: timestamp (nullable = true)
 |-- total_amount: double (nullable = true)
 |-- status: string (nullable = true)
 |-- channel: string (nullable = true)

root
 |-- customer_id: long (nullable = true)
 |-- device: string (nullable = true)
 |-- event_id: string (nullable = true)
 |-- event_time: string (nullable = true)
 |-- event_type: string (nullable = true)
 |-- product_id: long (nullable = true)
 |-- session_id: string (nullable = true)

Spark has worked out that order_date is a date with a time (timestamp) and total_amount a decimal (double). In the events, the columns appear in alphabetical order and event_time has been left as text: schema inference is convenient, but not infallible. As soon as you write to Parquet, these types are recorded in the file and will never have to be inferred again.

Next comes the table of sizes. A real run produced this (your figures may vary slightly depending on the version of Spark):

Dataset                                 MB
orders.csv                            1.04
orders_parquet (snappy)               0.42
web_events.json                      37.77
events_json_gzip                      2.79
events_parquet_uncompressed           8.78
events_parquet (snappy)               3.09
events_parquet_zstd                   1.66

There is a lot to read in these seven lines:

  • Uncompressed Parquet already takes up four times less than the JSON (8.78 against 37.77 MB). That is the effect of not repeating the field names and of the encodings, such as dictionary encoding.
  • With snappy, twelve times less; with zstd, twenty-three times less. Applied to NovaMarket: the year of events that in the previous lesson demanded around 11 TB of raw disk in HDFS would come down to about 1 TB.
  • The gzip-compressed JSON is small (2.79 MB), but it is deceptive: it is not splittable, it still has no types and it has to be decompressed and read in full for any query.
  • For orders the gain is smaller (from 1.04 to 0.42 MB). CSV does not repeat field names, so it started out with less fat than the JSON.

What Spark has written

Look inside one of the folders:

ls lake_scratch/events_parquet
_SUCCESS
part-00000-a4082b09-468a-4850-8503-d7951778de7e-c000.snappy.parquet
part-00001-a4082b09-468a-4850-8503-d7951778de7e-c000.snappy.parquet
...

Spark treats a table as a folder of files. Each part-... was written by a different task, in parallel; you will have more or fewer depending on your machine's cores, and the identifiers will be different. The empty _SUCCESS file indicates that the write finished successfully. To read the table you point to the folder, not to a specific file.

Reading only some columns

Now for Marc's question. Create read_columns.py:

from pathlib import Path
from pyspark.sql import SparkSession

SCRATCH_DIR = Path.home() / "novamarket" / "lake_scratch"

spark = (
    SparkSession.builder
    .master("local[*]")
    .appName("read_columns")
    .getOrCreate()
)
spark.sparkContext.setLogLevel("ERROR")

events = spark.read.parquet(str(SCRATCH_DIR / "events_parquet"))

# We only need two of the seven columns and one event type
purchases = (
    events
    .select("event_type", "device")
    .where("event_type = 'purchase'")
)

purchases.groupBy("device").count().orderBy("count", ascending=False).show()

# The physical plan shows what Spark is actually going to read
purchases.explain()

spark.stop()
  • spark.read.parquet(folder) needs neither header nor inferSchema: the schema is in the files.
  • .select(...) chooses columns and .where(...) filters rows.
  • .groupBy("device").count() counts rows per device, and .show() prints the result.
  • .explain() shows the plan Spark is going to execute.
+-------+-----+
| device|count|
+-------+-----+
| mobile| 4882|
|desktop| 2536|
| tablet|  639|
|   NULL|   31|
+-------+-----+

The four figures add up to 8,088, the number of purchase events you already knew (it includes the duplicates, which we have not yet removed, and 31 purchases with the device missing). In the plan, which is long, the line of interest is the one beginning with FileScan parquet, and within it two fragments:

PushedFilters: [IsNotNull(event_type), EqualTo(event_type,purchase)]
ReadSchema: struct<device:string,event_type:string>
  • ReadSchema is column pruning: Spark is only going to read device and event_type from disk. The other five columns are not touched.
  • PushedFilters is predicate pushdown: the condition event_type = 'purchase' has been sent to the Parquet reader, which can use the statistics to skip entire chunks.

You did not have to ask for either of them: the format makes them possible and the engine applies them by itself.

Which format for what

Situation Recommended format Reason
Exchanging data with another company or exporting for a spreadsheet CSV Universal and readable
Receiving data from an API or logs from an application JSON Lines The natural format at source; flexible
Messages in a messaging system; record-by-record ingestion Avro Rows, compact, a schema with robust evolution
Tables in a data lake or lakehouse for analysis Parquet Columnar, highly compressed, pruning and pushdown
A Hive-based platform that already uses ORC ORC Equivalent to Parquet in that ecosystem
An as-is copy of the source data, for safekeeping The original format (compressed if it is large) Fidelity to the source: covered in lesson 02-04

For NovaMarket, the journey looks like this: events are born as JSON on the website, travel as Avro through the messaging layer and are stored for analysis as Parquet. Orders leave the shop's database as CSV in the daily load and are likewise converted to Parquet.

Common Mistakes and Tips

  • Analysing straight from CSV or JSON "because they are already there". Converting to Parquet once pays for itself in the first week of queries.
  • Compressing large text files with gzip and expecting parallelism. They are not splittable: a single process will have to read them in full. If there is no alternative, make it many medium-sized files rather than one giant one.
  • Always trusting inferSchema. It forces the file to be read one more time just to work out types, and it can get them wrong (a postcode starting with zero turned into a number, for example). In production jobs the schema is declared explicitly; you will do that in Module 3.
  • Looking for "the" Parquet file. The table is the folder. Do not rename or delete the part-... files by hand.
  • Using Parquet to write records one at a time. A columnar format needs large batches; row by row it produces thousands of tiny files (the small files problem from lesson 02-01). That is what Avro is for.
  • Renaming columns lightly. It breaks the joint reading of old and new files.
  • Tip: if you are torn between codecs for Parquet, snappy and zstd are the two sensible options; measure with your own data, as you have just done.

Exercises

Exercise 1: choosing a format

Say which format you would use in each case and why:

  1. The payments service sends the data platform one message per transaction, thousands a second, and adds new fields from time to time.
  2. Marc needs a table with two years of order lines to calculate sales by category and month.
  3. The finance department asks for a monthly extract of orders to open in its spreadsheet.

Exercise 2: converting order_lines

Write a script that converts data/order_lines.csv to Parquet in lake_scratch/lines_parquet and shows its schema and the two sizes. Which types has Spark inferred? By how much does the size shrink?

Exercise 3: interpreting a plan

On lake_scratch/events_parquet, write a query that counts how many add_to_cart events there are per device. Before running .explain(), predict what will appear in ReadSchema and in PushedFilters.

Solutions

Exercise 1

  1. Avro. It is written record by record, at high speed, and the schema evolves: the home ground of a row format with robust schema evolution.
  2. Parquet. An analytical query that uses a few columns from a huge number of rows: column pruning, predicate pushdown and good compression.
  3. CSV. The recipient is a person with a spreadsheet; compatibility comes first. The volume is small and it is not going to be analysed at scale.

Exercise 2

from pathlib import Path
from pyspark.sql import SparkSession

BASE = Path.home() / "novamarket"
SOURCE = BASE / "data" / "order_lines.csv"
TARGET = BASE / "lake_scratch" / "lines_parquet"

spark = SparkSession.builder.master("local[*]").appName("lines_parquet").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")

lines = spark.read.csv(str(SOURCE), header=True, inferSchema=True)
lines.printSchema()
lines.write.mode("overwrite").parquet(str(TARGET))

mb_csv = SOURCE.stat().st_size / 1_000_000
mb_parquet = sum(f.stat().st_size for f in TARGET.rglob("*") if f.is_file()) / 1_000_000
print(f"CSV: {mb_csv:.2f} MB | Parquet: {mb_parquet:.2f} MB")

spark.stop()

Spark infers three integer columns (order_id, product_id, quantity) and one decimal (unit_price). The size goes from 0.95 MB to about 0.28 MB: a little over three times smaller.

Common mistake: forgetting inferSchema=True. The script works just the same, but all four columns are stored as text in Parquet and the error spreads to everything that reads that table.

Exercise 3

cart = events.select("event_type", "device").where("event_type = 'add_to_cart'")
cart.groupBy("device").count().show()
cart.explain()

The result is 13,042 for mobile, 6,991 for desktop, 1,822 for tablet and 114 with no device (21,969 in total). In the plan, ReadSchema contains only device and event_type, and PushedFilters includes EqualTo(event_type,add_to_cart). It is the same pattern as the example in the lesson: the filter value changes, not the mechanism.

Conclusion

A file's format decides how much space it takes up and how much it costs to query. CSV and JSON are readable and universal, ideal for exchanging data, but they lack reliable types, take up a lot of space and force you to read everything. Avro stores data by rows with a schema that evolves safely, and is the format for ingestion and messaging. Parquet and ORC store it by columns, with statistics that enable column pruning and predicate pushdown, and are the standard for analysis. All three binary formats carry an embedded schema and remain splittable even when compressed, which is not true of a text file compressed with gzip. On your own machine you have seen the difference: NovaMarket's events go from 37.8 MB in JSON to 3.1 MB in Parquet with snappy.

So far we have talked about files: data that is written once and read straight through to be analysed. But NovaMarket's website also needs to store and retrieve specific pieces of data in milliseconds: a customer's cart, a product page, their latest events. A Parquet file is no use for that, and a traditional relational database falls short when volume or variety grows. In the next lesson, NoSQL Databases, you will see the four types that exist and practise with MongoDB and Redis.

© Copyright 2026. All rights reserved