快取

Python Spark SQL 入門

Mark Plutowski

Data Scientist

什麼是快取?

  • 將資料留在記憶體中
  • Spark 會積極釋放記憶體
Python Spark SQL 入門

逐出策略

  • 最近最少使用(LRU)
  • 逐出在每個 worker 上各自進行
  • 取決於每個 worker 可用的記憶體
Python Spark SQL 入門

快取 dataframe

快取 dataframe:
df.cache()
取消快取:
df.unpersist()
Python Spark SQL 入門

如何判斷 dataframe 是否已快取

df.is_cached
False
df.cache()
df.is_cached
True
Python Spark SQL 入門

取消 dataframe 快取

df.unpersist()
df.is_cached()
False
Python Spark SQL 入門

儲存層級

df.unpersist()
df.cache()
df.storageLevel
StorageLevel(True, True, False, True, 1)

上述儲存層級代表:

  1. useDisk = True
  2. useMemory = True
  3. useOffHeap = False
  4. deserialized = True
  5. replication = 1
Python Spark SQL 入門

持久化 dataframe

以下在 Spark 2.1+ 等價:

  • df.persist()

  • df.persist(storageLevel=pyspark.StorageLevel.MEMORY_AND_DISK)

  • df.cache()df.persist() 相同

Python Spark SQL 入門

快取資料表

df.createOrReplaceTempView('df')
spark.catalog.isCached(tableName='df')
False
spark.catalog.cacheTable('df')
spark.catalog.isCached(tableName='df')
True
Python Spark SQL 入門

取消資料表快取

spark.catalog.uncacheTable('df')
spark.catalog.isCached(tableName='df')
False
spark.catalog.clearCache()
Python Spark SQL 入門

技巧

  • 快取是延遲執行的
  • 只有在要執行多於一個操作時才快取
  • 不再需要物件時請 unpersist
  • 有選擇地快取
Python Spark SQL 入門

一起來練習吧!

Python Spark SQL 入門

Preparing Video For Download...