Caching and persistence help keep data ready in memory or disk so Spark can use it faster next time.
Caching and persistence in Apache Spark
dataframe.cache()
dataframe.persist(StorageLevel.MEMORY_AND_DISK)
# To remove cached data:
dataframe.unpersist()cache() is shorthand for persist(StorageLevel.MEMORY_ONLY).
You can choose different storage levels like MEMORY_ONLY, DISK_ONLY, or MEMORY_AND_DISK.
df.cache()
from pyspark import StorageLevel df.persist(StorageLevel.MEMORY_ONLY)
df.unpersist()
This program creates a DataFrame, caches it, counts rows to trigger caching, then persists it with MEMORY_ONLY storage, shows the data, and finally unpersists it to free memory.
from pyspark.sql import SparkSession from pyspark import StorageLevel spark = SparkSession.builder.appName('CachingExample').getOrCreate() # Create a simple DataFrame data = [(1, 'apple'), (2, 'banana'), (3, 'cherry')] df = spark.createDataFrame(data, ['id', 'fruit']) # Cache the DataFrame print('Caching DataFrame...') df.cache() # Perform an action to trigger caching print('Count:', df.count()) # Persist with MEMORY_ONLY print('Persisting DataFrame with MEMORY_ONLY...') df.persist(StorageLevel.MEMORY_ONLY) # Perform another action print('Show DataFrame:') df.show() # Unpersist to free cache print('Unpersisting DataFrame...') df.unpersist() spark.stop()
Caching only happens after an action like count() or show() is called.
Persisting lets you pick storage type; caching is a common default.
Unpersist frees memory and disk space used by cached data.
Caching and persistence speed up repeated data use by storing data in memory or disk.
Use cache() for simple caching, persist() to choose storage.
Always unpersist when done to save resources.
Practice
cache() in Apache Spark?Solution
Step 1: Understand what caching means in Spark
Caching stores data in memory to speed up repeated operations on the same data.Step 2: Identify the role of
Thecache()cache()method specifically stores the DataFrame or RDD in memory for quick access.Final Answer:
To store data in memory for faster repeated access -> Option CQuick Check:
Caching = store in memory [OK]
- Thinking cache saves data permanently on disk
- Confusing cache with deleting data
- Assuming cache changes data format
df with disk storage level in Spark?Solution
Step 1: Recall the correct method to specify storage level
To persist with a specific storage level, usepersist()with a StorageLevel object.Step 2: Check the syntax for disk-only persistence
The correct syntax isdf.persist(StorageLevel.DISK_ONLY). Thecache()method does not accept parameters.Final Answer:
df.persist(StorageLevel.DISK_ONLY) -> Option AQuick Check:
persist + StorageLevel object = correct syntax [OK]
- Using cache() with parameters
- Passing storage level as string instead of StorageLevel object
- Using persist() without StorageLevel
val df = spark.read.csv("data.csv")
df.cache()
df.count()
df.count()What is the effect of calling
df.count() twice after caching?Solution
Step 1: Understand caching behavior on first action
The first action (count()) triggers loading data and caches it in memory.Step 2: Effect on second action
The secondcount()uses the cached data, so it runs faster without reloading from disk.Final Answer:
The first count triggers data loading and caching; the second count uses cached data for faster result -> Option BQuick Check:
First action caches, second uses cache [OK]
- Assuming cache happens before first action
- Thinking both counts reload from disk
- Believing second count triggers caching
val df = spark.read.json("data.json")
df.persist(StorageLevel.MEMORY_AND_DISK)
df.unpersist()What is the main issue with this code?
Solution
Step 1: Understand the effect of
Thepersist()persist()call stores the DataFrame in memory and disk as specified.Step 2: Effect of immediate
Callingunpersist()unpersist()right after removes the cached data, negating the persistence benefit.Final Answer:
Callingunpersist()immediately removes cached data, so persistence is ineffective -> Option AQuick Check:
Immediate unpersist clears cache [OK]
- Thinking persist needs string argument
- Believing cache must be called before persist
- Assuming syntax error due to parentheses
df used multiple times in your Spark job. You want to cache it but ensure it uses memory first and spills to disk if memory is full. Which persistence level should you use and why?Solution
Step 1: Identify persistence levels for memory and disk
StorageLevel.MEMORY_AND_DISKstores data in memory and spills to disk if memory is insufficient.Step 2: Compare with other options
cache()only stores in memory and may fail if memory is full;DISK_ONLYavoids memory;unpersist()removes cached data.Final Answer:
Usedf.persist(StorageLevel.MEMORY_AND_DISK)to store in memory and spill to disk if needed -> Option DQuick Check:
MEMORY_AND_DISK = memory first, then disk spill [OK]
- Assuming cache spills to disk automatically
- Choosing DISK_ONLY to save memory but slower
- Using unpersist to keep data cached
Ready to prove it?
Pass the test and this pattern moves unknown
