Bộ nhớ đệm

Nhập môn Spark SQL bằng Python

Mark Plutowski

Data Scientist

Caching là gì?

  • Giữ dữ liệu trong bộ nhớ
  • Spark có xu hướng giải phóng bộ nhớ mạnh
Nhập môn Spark SQL bằng Python

Chính sách thu hồi

  • Least Recently Used (LRU)
  • Thu hồi diễn ra độc lập trên từng worker
  • Phụ thuộc vào bộ nhớ của từng worker
Nhập môn Spark SQL bằng Python

Cache một dataframe

Để cache một dataframe:
df.cache()
Để bỏ cache:
df.unpersist()
Nhập môn Spark SQL bằng Python

Kiểm tra dataframe đã cache chưa

df.is_cached
False
df.cache()
df.is_cached
True
Nhập môn Spark SQL bằng Python

Bỏ cache một dataframe

df.unpersist()
df.is_cached()
False
Nhập môn Spark SQL bằng Python

Cấp lưu trữ

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

Ở cấp lưu trữ trên, các điều sau đúng:

  1. useDisk = True
  2. useMemory = True
  3. useOffHeap = False
  4. deserialized = True
  5. replication = 1
Nhập môn Spark SQL bằng Python

Lưu bền một dataframe

Các mục sau tương đương trong Spark 2.1+:

  • df.persist()

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

  • df.cache() giống df.persist()

Nhập môn Spark SQL bằng Python

Cache một bảng

df.createOrReplaceTempView('df')
spark.catalog.isCached(tableName='df')
False
spark.catalog.cacheTable('df')
spark.catalog.isCached(tableName='df')
True
Nhập môn Spark SQL bằng Python

Bỏ cache một bảng

spark.catalog.uncacheTable('df')
spark.catalog.isCached(tableName='df')
False
spark.catalog.clearCache()
Nhập môn Spark SQL bằng Python

Mẹo

  • Cache là lười thực thi
  • Chỉ cache khi cần chạy >1 thao tác
  • Unpersist khi không còn cần đối tượng
  • Cache có chọn lọc
Nhập môn Spark SQL bằng Python

Ayo berlatih!

Nhập môn Spark SQL bằng Python

Preparing Video For Download...