Caching

Introduction to Spark SQL in Python

Mark Plutowski

Data Scientist

Caching คืออะไร?

  • เก็บข้อมูลไว้ในหน่วยความจำ
  • Spark มักจะล้างหน่วยความจำอย่างรวดเร็ว
Introduction to Spark SQL in Python

นโยบายการขับข้อมูลออก

  • Least Recently Used (LRU)
  • การขับออกเกิดขึ้นอิสระบน worker แต่ละตัว
  • ขึ้นอยู่กับหน่วยความจำที่แต่ละ worker มีอยู่
Introduction to Spark SQL in Python

การ cache dataframe

สำหรับ cache dataframe:
df.cache()
สำหรับยกเลิก cache:
df.unpersist()
Introduction to Spark SQL in Python

ตรวจสอบว่า dataframe ถูก cache หรือไม่

df.is_cached
False
df.cache()
df.is_cached
True
Introduction to Spark SQL in Python

การยกเลิก cache ของ dataframe

df.unpersist()
df.is_cached()
False
Introduction to Spark SQL in Python

Storage level

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

ค่า storage level ข้างต้นมีความหมายดังนี้:

  1. useDisk = True
  2. useMemory = True
  3. useOffHeap = False
  4. deserialized = True
  5. replication = 1
Introduction to Spark SQL in Python

การ persist dataframe

สิ่งต่อไปนี้มีความหมายเทียบเท่ากันใน Spark 2.1+ :

  • df.persist()

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

  • df.cache() มีความหมายเดียวกับ df.persist()

Introduction to Spark SQL in Python

การ cache ตาราง

df.createOrReplaceTempView('df')
spark.catalog.isCached(tableName='df')
False
spark.catalog.cacheTable('df')
spark.catalog.isCached(tableName='df')
True
Introduction to Spark SQL in Python

การยกเลิก cache ของตาราง

spark.catalog.uncacheTable('df')
spark.catalog.isCached(tableName='df')
False
spark.catalog.clearCache()
Introduction to Spark SQL in Python

เคล็ดลับ

  • Caching เป็นแบบ lazy
  • Cache เฉพาะเมื่อต้องทำมากกว่าหนึ่ง operation
  • Unpersist เมื่อไม่ต้องการใช้ object นั้นแล้ว
  • เลือก cache เฉพาะที่จำเป็น
Introduction to Spark SQL in Python

มาฝึกกันเถอะ!

Introduction to Spark SQL in Python

Preparing Video For Download...