1. DataFrame

DataFrame과 partition
DataFrame과 partitionDataFrame · 6행 예시 · customer_id · Invoice_id · creation_date · 1 · 5101 · 2016-01-01 · 2 · 5201 · 2017-10-10 · 2 · 5301 · 2018-01-01 · 3 · 5102 · 2017-01-30 · 3 · 5202 · 2017-10-30 · 4 · 5302 · 2017-07-30 · Worker 1 · Executor · count = 3 · Partition 1 · 5101 · 5201 · 5301 · Worker 2 · Executor · count = 3 · Partition 2 · 5102 · 5202 · 5302 · Driver · count() · 3 + 3 = 6. driver가 3 + 3 = 6을 합칩니다. 논리 표의 6행과 같습니다.DataFrame · 6행 예시customer_idInvoice_idcreation_date151012016-01-01252012017-10-10253012018-01-01351022017-01-30352022017-10-30453022017-07-30Worker 1 · Executorcount = 3Partition 1510152015301Worker 2 · Executorcount = 3Partition 2510252025302Driver · count()3 + 3 = 6
DataFrame과 partitionDataFrame · 6행 예시 · customer_id · Invoice_id · creation_date · 1 · 5101 · 2016-01-01 · 2 · 5201 · 2017-10-10 · 2 · 5301 · 2018-01-01 · 3 · 5102 · 2017-01-30 · 3 · 5202 · 2017-10-30 · 4 · 5302 · 2017-07-30 · Worker 1 · Executor · count = 3 · Partition 1 · 5101 · 5201 · 5301 · Worker 2 · Executor · count = 3 · Partition 2 · 5102 · 5202 · 5302 · Driver · count() · 3 + 3 = 6. driver가 3 + 3 = 6을 합칩니다. 논리 표의 6행과 같습니다.DataFrame · 6행 예시customer_idInvoice_idcreation_date151012016-01-01252012017-10-10253012018-01-01351022017-01-30352022017-10-30453022017-07-30Worker 1 · Executorcount = 3Partition 1510152015301Worker 2 · Executorcount = 3Partition 2510252025302Driver · count()3 + 3 = 6
과정 보기

1. 사용자는 DataFrame을 하나의 표처럼 다룹니다.

DataFrame과 partition · 1DataFrame · 6행 예시 · customer_id · Invoice_id · creation_date · 1 · 5101 · 2016-01-01 · 2 · 5201 · 2017-10-10 · 2 · 5301 · 2018-01-01 · 3 · 5102 · 2017-01-30 · 3 · 5202 · 2017-10-30 · 4 · 5302 · 2017-07-30 · Partition 1 · 논리 · Partition 2 · 논리 · Driver. 사용자는 DataFrame을 하나의 표처럼 다룹니다.DataFrame · 6행 예시customer_idInvoice_idcreation_date151012016-01-01252012017-10-10253012018-01-01351022017-01-30352022017-10-30453022017-07-30Partition 1 · 논리Partition 2 · 논리Driver
DataFrame과 partition · 1DataFrame · 6행 예시 · customer_id · Invoice_id · creation_date · 1 · 5101 · 2016-01-01 · 2 · 5201 · 2017-10-10 · 2 · 5301 · 2018-01-01 · 3 · 5102 · 2017-01-30 · 3 · 5202 · 2017-10-30 · 4 · 5302 · 2017-07-30 · Partition 1 · 논리 · Partition 2 · 논리 · Driver. 사용자는 DataFrame을 하나의 표처럼 다룹니다.DataFrame · 6행 예시customer_idInvoice_idcreation_date151012016-01-01252012017-10-10253012018-01-01351022017-01-30352022017-10-30453022017-07-30Partition 1 · 논리Partition 2 · 논리Driver

2. Spark는 행을 논리 partition으로 나눕니다(그림 기준 예시 분할). action 전에는 executor에서 계산하지 않습니다.

DataFrame과 partition · 2DataFrame · 6행 예시 · customer_id · Invoice_id · creation_date · 1 · 5101 · 2016-01-01 · 2 · 5201 · 2017-10-10 · 2 · 5301 · 2018-01-01 · 3 · 5102 · 2017-01-30 · 3 · 5202 · 2017-10-30 · 4 · 5302 · 2017-07-30 · Partition 1 · 논리 · 5101 · 5201 · 5301 · Partition 2 · 논리 · 5102 · 5202 · 5302 · Driver. Spark는 행을 논리 partition으로 나눕니다. action 전에는 계산하지 않습니다.DataFrame · 6행 예시customer_idInvoice_idcreation_date151012016-01-01252012017-10-10253012018-01-01351022017-01-30352022017-10-30453022017-07-30Partition 1 · 논리510152015301Partition 2 · 논리510252025302Driver
DataFrame과 partition · 2DataFrame · 6행 예시 · customer_id · Invoice_id · creation_date · 1 · 5101 · 2016-01-01 · 2 · 5201 · 2017-10-10 · 2 · 5301 · 2018-01-01 · 3 · 5102 · 2017-01-30 · 3 · 5202 · 2017-10-30 · 4 · 5302 · 2017-07-30 · Partition 1 · 논리 · 5101 · 5201 · 5301 · Partition 2 · 논리 · 5102 · 5202 · 5302 · Driver. Spark는 행을 논리 partition으로 나눕니다. action 전에는 계산하지 않습니다.DataFrame · 6행 예시customer_idInvoice_idcreation_date151012016-01-01252012017-10-10253012018-01-01351022017-01-30352022017-10-30453022017-07-30Partition 1 · 논리510152015301Partition 2 · 논리510252025302Driver

3. count() action에서 task가 executor에 배정되어 각자 자기 partition을 세고, driver가 3 + 3 = 6을 합칩니다.

DataFrame과 partition · 3DataFrame · 6행 예시 · customer_id · Invoice_id · creation_date · 1 · 5101 · 2016-01-01 · 2 · 5201 · 2017-10-10 · 2 · 5301 · 2018-01-01 · 3 · 5102 · 2017-01-30 · 3 · 5202 · 2017-10-30 · 4 · 5302 · 2017-07-30 · Worker 1 · Executor · count = 3 · Partition 1 · 5101 · 5201 · 5301 · Worker 2 · Executor · count = 3 · Partition 2 · 5102 · 5202 · 5302 · Driver · count() · 3 + 3 = 6. driver가 3 + 3 = 6을 합칩니다. 논리 표의 6행과 같습니다.DataFrame · 6행 예시customer_idInvoice_idcreation_date151012016-01-01252012017-10-10253012018-01-01351022017-01-30352022017-10-30453022017-07-30Worker 1 · Executorcount = 3Partition 1510152015301Worker 2 · Executorcount = 3Partition 2510252025302Driver · count()3 + 3 = 6
DataFrame과 partition · 3DataFrame · 6행 예시 · customer_id · Invoice_id · creation_date · 1 · 5101 · 2016-01-01 · 2 · 5201 · 2017-10-10 · 2 · 5301 · 2018-01-01 · 3 · 5102 · 2017-01-30 · 3 · 5202 · 2017-10-30 · 4 · 5302 · 2017-07-30 · Worker 1 · Executor · count = 3 · Partition 1 · 5101 · 5201 · 5301 · Worker 2 · Executor · count = 3 · Partition 2 · 5102 · 5202 · 5302 · Driver · count() · 3 + 3 = 6. driver가 3 + 3 = 6을 합칩니다. 논리 표의 6행과 같습니다.DataFrame · 6행 예시customer_idInvoice_idcreation_date151012016-01-01252012017-10-10253012018-01-01351022017-01-30352022017-10-30453022017-07-30Worker 1 · Executorcount = 3Partition 1510152015301Worker 2 · Executorcount = 3Partition 2510252025302Driver · count()3 + 3 = 6
원본 도해

DataFrame은 데이터가 여러 머신에 분산돼 있어도 하나의 테이블처럼 다룰 수 있게 하는 API다.

df = spark.read.load("[파일경로]",
                     format="csv", 
                     sep="\t", 
                     inferSchema="true", // * 타입 추론
                     header="true")

dfSelected = df.select(
    col("ID").alias("id"),
    col("Year_Birth").alias("year_birth")
)

dfSelected.printSchema()
root
 |-- id: integer (nullable = true)
 |-- year_birth: integer (nullable = true)
  • 위의 예시에서 df, dfSelected 는 각각 다른 DataFrame으로 불변이다. 이 때, 물리적으로 실제 데이터가 복사되는 것은 아니다. 물리적인 데이터는 여전히 Disk에 CSV파일로 존재하고 count() 등의 RDD 액션을 수행할 때, 데이터를 메모리로 읽어 처리한다.

2. DataFrame vs DataSet vs SQL vs RDD

  • 데이터를 탐색하거나, 빠르게 가공하고 싶다면 SQL API를 사용한다.

  • DataFrame은 untyped API로, SQL과 1:1로 매핑된다. DataFrame은 Dataset[Row] 즉, Row라는 타입의 Dataset이다.

  • DataSet은 type-safe하며, lambda 등이 가능하다. map, flatmap, filter 등 함수형 Collection API 일부를 사용할 수 있다. Encoder를 이용해 DataFrame을 Dataset[T]로 변경한다. DataSet은 각 언어 구조에 따른 타입을 알 수 있다.

    case class MarketingUser(userId: Int, 
                             yearBirth: Int)
    
    # Encoder는 Serialization / Deserialization을 한다.
    val dsMarketingUser = dfSelected.as[MarketingUser]
    
    # dfSelected
    org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [id: int, yearBirth: int]
    
    # dsMaretingUser
    org.apache.spark.sql.Dataset[MarketingUser] = [userId: int, yearBirth: int]
  • 고도의 최적화 등 특별한 경우가 아니라면 낮은 수준의 API인 RDD를 사용하지 않는다. 일정 규모에서는 머신에 비용을 투자하는 것이 고도의 최적화를 유지보수하는 것보다 저렴하다. Public Cloud 환경에선 머신이 사람보다 구하기 쉽기 때문이다.

3. 실행계획과 최적화

  • DataFrame, SQL, DataSet API를 이용할 경우 Catalyst Optimizer를 이용하여 최적화한 후, RDD로 코드가 생성되어 실행된다.

explain()

실행계획 최적화
실행계획 최적화Unresolved · Analyzed · Optimized · Physical · RDDs · 원문 출력 없음 · xx.select("education").limit(5).explain("extended") · Analyzed Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [education#238] · Project · […, … AS date_joined#257] · Project · [ID#16 AS id#236, …, Education#18 AS education#238, … 7개] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · Optimized Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [Education#18 AS education#238] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · 가지치기 · Project 병합 · 결과 스키마 education: string · 최대 5행. 결과 스키마 education: string, 최대 5행. 결과는 그대로입니다.UnresolvedAnalyzedOptimizedPhysicalRDDs원문 출력 없음xx.select("education").limit(5).explain("extended")Analyzed Logical PlanGlobalLimit 5LocalLimit 5Project[education#238]Project[…, … AS date_joined#257]Project[ID#16 AS id#236, …, Education#18 ASeducation#238, … 7개]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csvOptimized Logical PlanGlobalLimit 5LocalLimit 5Project[Education#18 AS education#238]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csv가지치기 · Project 병합결과 스키마 education: string · 최대 5행
실행계획 최적화Unresolved · Analyzed · Optimized · Physical · RDDs · 원문 출력 없음 · xx.select("education") · .limit(5).explain("extended") · Analyzed Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [education#238] · Project · […, … AS date_joined#257] · Project · [ID#16 AS id#236, …, Education#18 AS education#238, … 7개] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · Optimized Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [Education#18 AS education#238] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · 가지치기 · Project 병합 · 결과 스키마 education: string · 최대 5행. 결과 스키마 education: string, 최대 5행. 결과는 그대로입니다.UnresolvedAnalyzedOptimizedPhysicalRDDs원문 출력 없음xx.select("education") .limit(5).explain("extended")Analyzed Logical PlanGlobalLimit 5LocalLimit 5Project[education#238]Project[…, … AS date_joined#257]Project[ID#16 AS id#236, …, Education#18 ASeducation#238, … 7개]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csvOptimized Logical PlanGlobalLimit 5LocalLimit 5Project[Education#18 AS education#238]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csv가지치기 · Project 병합결과 스키마 education: string · 최대 5행
과정 보기

1. Analyzed Logical Plan: 7개 이름 바꾸기, date_joined 계산, education 선택.

실행계획 최적화 · 1Unresolved · Analyzed · Optimized · Physical · RDDs · xx.select("education").limit(5).explain("extended") · Analyzed Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [education#238] · Project · […, … AS date_joined#257] · Project · [ID#16 AS id#236, …, Education#18 AS education#238, … 7개] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv. Analyzed Logical Plan: 7개 컬럼 이름 바꾸기와 date_joined 계산이 있습니다.UnresolvedAnalyzedOptimizedPhysicalRDDsxx.select("education").limit(5).explain("extended")Analyzed Logical PlanGlobalLimit 5LocalLimit 5Project[education#238]Project[…, … AS date_joined#257]Project[ID#16 AS id#236, …, Education#18 ASeducation#238, … 7개]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csv
실행계획 최적화 · 1Unresolved · Analyzed · Optimized · Physical · RDDs · xx.select("education") · .limit(5).explain("extended") · Analyzed Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [education#238] · Project · […, … AS date_joined#257] · Project · [ID#16 AS id#236, …, Education#18 AS education#238, … 7개] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv. Analyzed Logical Plan: 7개 컬럼 이름 바꾸기와 date_joined 계산이 있습니다.UnresolvedAnalyzedOptimizedPhysicalRDDsxx.select("education") .limit(5).explain("extended")Analyzed Logical PlanGlobalLimit 5LocalLimit 5Project[education#238]Project[…, … AS date_joined#257]Project[ID#16 AS id#236, …, Education#18 ASeducation#238, … 7개]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csv

2. 최적화는 education으로 이어지는 경로만 남기고 세 Project를 합칩니다.

실행계획 최적화 · 2Unresolved · Analyzed · Optimized · Physical · RDDs · xx.select("education").limit(5).explain("extended") · Analyzed Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [education#238] · Project · […, … AS date_joined#257] · Project · [ID#16 AS id#236, …, Education#18 AS education#238, … 7개] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · Optimized Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [Education#18 AS education#238] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · 가지치기 · Project 병합. Optimized Logical Plan: Project [Education#18 AS education#238] 하나입니다.UnresolvedAnalyzedOptimizedPhysicalRDDsxx.select("education").limit(5).explain("extended")Analyzed Logical PlanGlobalLimit 5LocalLimit 5Project[education#238]Project[…, … AS date_joined#257]Project[ID#16 AS id#236, …, Education#18 ASeducation#238, … 7개]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csvOptimized Logical PlanGlobalLimit 5LocalLimit 5Project[Education#18 AS education#238]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csv가지치기 · Project 병합
실행계획 최적화 · 2Unresolved · Analyzed · Optimized · Physical · RDDs · xx.select("education") · .limit(5).explain("extended") · Analyzed Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [education#238] · Project · […, … AS date_joined#257] · Project · [ID#16 AS id#236, …, Education#18 AS education#238, … 7개] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · Optimized Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [Education#18 AS education#238] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · 가지치기 · Project 병합. Optimized Logical Plan: Project [Education#18 AS education#238] 하나입니다.UnresolvedAnalyzedOptimizedPhysicalRDDsxx.select("education") .limit(5).explain("extended")Analyzed Logical PlanGlobalLimit 5LocalLimit 5Project[education#238]Project[…, … AS date_joined#257]Project[ID#16 AS id#236, …, Education#18 ASeducation#238, … 7개]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csvOptimized Logical PlanGlobalLimit 5LocalLimit 5Project[Education#18 AS education#238]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csv가지치기 · Project 병합

3. Optimized Logical Plan은 Project 하나. 실제로 읽는 열은 Physical Plan의 scan에서 확인합니다.

실행계획 최적화 · 3Unresolved · Analyzed · Optimized · Physical · RDDs · 원문 출력 없음 · xx.select("education").limit(5).explain("extended") · Analyzed Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [education#238] · Project · […, … AS date_joined#257] · Project · [ID#16 AS id#236, …, Education#18 AS education#238, … 7개] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · Optimized Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [Education#18 AS education#238] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · 가지치기 · Project 병합 · 결과 스키마 education: string · 최대 5행. 결과 스키마 education: string, 최대 5행. 결과는 그대로입니다.UnresolvedAnalyzedOptimizedPhysicalRDDs원문 출력 없음xx.select("education").limit(5).explain("extended")Analyzed Logical PlanGlobalLimit 5LocalLimit 5Project[education#238]Project[…, … AS date_joined#257]Project[ID#16 AS id#236, …, Education#18 ASeducation#238, … 7개]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csvOptimized Logical PlanGlobalLimit 5LocalLimit 5Project[Education#18 AS education#238]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csv가지치기 · Project 병합결과 스키마 education: string · 최대 5행
실행계획 최적화 · 3Unresolved · Analyzed · Optimized · Physical · RDDs · 원문 출력 없음 · xx.select("education") · .limit(5).explain("extended") · Analyzed Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [education#238] · Project · […, … AS date_joined#257] · Project · [ID#16 AS id#236, …, Education#18 AS education#238, … 7개] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · Optimized Logical Plan · GlobalLimit 5 · LocalLimit 5 · Project · [Education#18 AS education#238] · Relation · [ID#16,…,AcceptedCmp1#39,... 5 more fields] csv · 가지치기 · Project 병합 · 결과 스키마 education: string · 최대 5행. 결과 스키마 education: string, 최대 5행. 결과는 그대로입니다.UnresolvedAnalyzedOptimizedPhysicalRDDs원문 출력 없음xx.select("education") .limit(5).explain("extended")Analyzed Logical PlanGlobalLimit 5LocalLimit 5Project[education#238]Project[…, … AS date_joined#257]Project[ID#16 AS id#236, …, Education#18 ASeducation#238, … 7개]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csvOptimized Logical PlanGlobalLimit 5LocalLimit 5Project[Education#18 AS education#238]Relation[ID#16,…,AcceptedCmp1#39,... 5 morefields] csv가지치기 · Project 병합결과 스키마 education: string · 최대 5행
원본 도해

# xx.select("education").limit(5).explain("extended")

...
== Analyzed Logical Plan ==
education: string
GlobalLimit 5
+- LocalLimit 5
   +- Project [education#238]
      +- Project [id#236, year_birth#237, education#238, count_kid#239, count_teen#240, date_customer#241, days_last_login#242, add_months(to_date('date_customer, Some(d-M-yyyy)), 72) AS date_joined#257]
         +- Project [ID#16 AS id#236, Year_Birth#17 AS year_birth#237, Education#18 AS education#238, Kidhome#21 AS count_kid#239, Teenhome#22 AS count_teen#240, Dt_Customer#23 AS date_customer#241, Recency#24 AS days_last_login#242]
            +- Relation[ID#16,Year_Birth#17,Education#18,Marital_Status#19,Income#20,Kidhome#21,Teenhome#22,Dt_Customer#23,Recency#24,MntWines#25,MntFruits#26,MntMeatProducts#27,MntFishProducts#28,MntSweetProducts#29,MntGoldProds#30,NumDealsPurchases#31,NumWebPurchases#32,NumCatalogPurchases#33,NumStorePurchases#34,NumWebVisitsMonth#35,AcceptedCmp3#36,AcceptedCmp4#37,AcceptedCmp5#38,AcceptedCmp1#39,... 5 more fields] csv

== Optimized Logical Plan ==
GlobalLimit 5
+- LocalLimit 5
   +- Project [Education#18 AS education#238]
      +- Relation[ID#16,Year_Birth#17,Education#18,Marital_Status#19,Income#20,Kidhome#21,Teenhome#22,Dt_Customer#23,Recency#24,MntWines#25,MntFruits#26,MntMeatProducts#27,MntFishProducts#28,MntSweetProducts#29,MntGoldProds#30,NumDealsPurchases#31,NumWebPurchases#32,NumCatalogPurchases#33,NumStorePurchases#34,NumWebVisitsMonth#35,AcceptedCmp3#36,AcceptedCmp4#37,AcceptedCmp5#38,AcceptedCmp1#39,... 5 more fields] csv

== Physical Plan ==
  • 이 예시는 최적화 후 education 컬럼만 Projection 한다.

  • Spark 3 에서는 explain() 함수가 "simple", "extended", "codegen", "cost", "formatted" 등 다양한 기능을 지원한다.

  • 다만, 병목 등의 상황은 Spark UI를 활용하여 파악하는 것이 용이하다.

predicate pushdown
predicate pushdown.filter($"age" > 30) · JDBC · pushdown 없음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · Filter age > 30 · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · 건넌 행 8 · pushdown 있음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · WHERE age > 30 · age 34 · age 41 · age 52 · age 31 · age 38 · 건넌 행 5. 결과는 같은 5행. 건넌 행은 8 대 5입니다..filter($"age" > 30) · JDBCpushdown 없음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkFilter age > 30age 25age 34age 41age 29age 52age 31age 19age 38건넌 행 8pushdown 있음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkWHERE age > 30age 34age 41age 52age 31age 38건넌 행 5
predicate pushdown.filter($"age" > 30) · JDBC · pushdown 없음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · Filter age > 30 · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · 건넌 행 8 · pushdown 있음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · WHERE age > 30 · age 34 · age 41 · age 52 · age 31 · age 38 · 건넌 행 5. 결과는 같은 5행. 건넌 행은 8 대 5입니다..filter($"age" > 30) · JDBCpushdown 없음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkFilter age > 30age 25age 34age 41age 29age 52age 31age 19age 38건넌 행 8pushdown 있음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkWHERE age > 30age 34age 41age 52age 31age 38건넌 행 5
과정 보기

1. pushdown이 없으면 8행이 모두 건너온 뒤 Spark가 age > 30을 걸러냅니다.

predicate pushdown · 1.filter($"age" > 30) · JDBC · pushdown 없음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · Filter age > 30 · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · 건넌 행 8 · pushdown 있음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · Filter age > 30 · 건넌 행 0. pushdown이 없으면 모든 행이 네트워크를 건넌 뒤 Spark에서 걸러집니다..filter($"age" > 30) · JDBCpushdown 없음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkFilter age > 30age 25age 34age 41age 29age 52age 31age 19age 38건넌 행 8pushdown 있음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkFilter age > 30건넌 행 0
predicate pushdown · 1.filter($"age" > 30) · JDBC · pushdown 없음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · Filter age > 30 · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · 건넌 행 8 · pushdown 있음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · Filter age > 30 · 건넌 행 0. pushdown이 없으면 모든 행이 네트워크를 건넌 뒤 Spark에서 걸러집니다..filter($"age" > 30) · JDBCpushdown 없음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkFilter age > 30age 25age 34age 41age 29age 52age 31age 19age 38건넌 행 8pushdown 있음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkFilter age > 30건넌 행 0

2. pushdown은 조건을 저장소 쪽 조회(WHERE age > 30)로 내립니다.

predicate pushdown · 2.filter($"age" > 30) · JDBC · pushdown 없음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · Filter age > 30 · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · 건넌 행 8 · pushdown 있음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · WHERE age > 30 · 건넌 행 0. pushdown: 조건이 저장소 쪽 조회(WHERE age > 30)로 내려갑니다..filter($"age" > 30) · JDBCpushdown 없음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkFilter age > 30age 25age 34age 41age 29age 52age 31age 19age 38건넌 행 8pushdown 있음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkWHERE age > 30건넌 행 0
predicate pushdown · 2.filter($"age" > 30) · JDBC · pushdown 없음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · Filter age > 30 · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · 건넌 행 8 · pushdown 있음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · WHERE age > 30 · 건넌 행 0. pushdown: 조건이 저장소 쪽 조회(WHERE age > 30)로 내려갑니다..filter($"age" > 30) · JDBCpushdown 없음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkFilter age > 30age 25age 34age 41age 29age 52age 31age 19age 38건넌 행 8pushdown 있음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkWHERE age > 30건넌 행 0

3. 조건을 만족한 5행만 건너옵니다. 결과는 같습니다.

predicate pushdown · 3.filter($"age" > 30) · JDBC · pushdown 없음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · Filter age > 30 · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · 건넌 행 8 · pushdown 있음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · WHERE age > 30 · age 34 · age 41 · age 52 · age 31 · age 38 · 건넌 행 5. 결과는 같은 5행. 건넌 행은 8 대 5입니다..filter($"age" > 30) · JDBCpushdown 없음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkFilter age > 30age 25age 34age 41age 29age 52age 31age 19age 38건넌 행 8pushdown 있음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkWHERE age > 30age 34age 41age 52age 31age 38건넌 행 5
predicate pushdown · 3.filter($"age" > 30) · JDBC · pushdown 없음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · Filter age > 30 · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · 건넌 행 8 · pushdown 있음 · DB · people · age 25 · age 34 · age 41 · age 29 · age 52 · age 31 · age 19 · age 38 · Spark · WHERE age > 30 · age 34 · age 41 · age 52 · age 31 · age 38 · 건넌 행 5. 결과는 같은 5행. 건넌 행은 8 대 5입니다..filter($"age" > 30) · JDBCpushdown 없음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkFilter age > 30age 25age 34age 41age 29age 52age 31age 19age 38건넌 행 8pushdown 있음DB · peopleage 25age 34age 41age 29age 52age 31age 19age 38SparkWHERE age > 30age 34age 41age 52age 31age 38건넌 행 5
원본 도해
  • 저장소에서 데이터를 필터링한 결과만 가져와 네트워크 및 가공 비용을 줄이는 Predicate Push Down 최적화다.

  • Logical Plan이 최적화 단계를 거쳐 Physical Plan이 생성되는데, 구체적으로 어떤 알고리즘을 수행해야 하는지 등의 정보를 담고 있다. 가령 위의 예시에서 Logical Plan에서는 Join이라고 표시되지만 Physical Plan 에서는 Sort-merge Join을 사용한다고 표시된다.

4. Transformation과 Action

Spark · 지연 실행
Spark · 지연 실행논리 연산 · lineage · Parent RDD · map(x × 2) · filter(x ≥ 8) · count() · 계산 완료 · Partition 1 · 1 · 2 · 2 · 4 · 3 · 6 · [] · 0 · Partition 2 · 4 · 8 · 8 · 5 · 10 · 10 · 6 · 12 · 12 · 3 · Driver 결과 3 · 0 + 3 = 3. 0 + 3 = 3. count 결과를 driver에 반환합니다.논리 연산 · lineageParent RDDmap(x × 2)filter(x ≥ 8)count()계산 완료Partition 1122436[]0Partition 248851010612123Driver 결과 30 + 3 = 3
Spark · 지연 실행논리 연산 · lineage · Parent RDD · map(x × 2) · filter(x ≥ 8) · count() · 계산 완료 · Partition 1 · 입력 · map · filter · count · 1 · 2 · 2 · 4 · 3 · 6 · [] · 0 · Partition 2 · 입력 · map · filter · count · 4 · 8 · 8 · 5 · 10 · 10 · 6 · 12 · 12 · 3 · Driver 결과 3 · 0 + 3 = 3. 0 + 3 = 3. count 결과를 driver에 반환합니다.논리 연산 · lineageParentRDDmap(x ×2)filter(x≥ 8)count()계산 완료Partition 1입력mapfiltercount122436[]0Partition 2입력mapfiltercount48851010612123Driver 결과 30 + 3 = 3
과정 보기

1. Parent RDD → map → filter의 lineage를 등록합니다. 데이터 처리는 아직 없습니다.

Spark · 지연 실행 · 1논리 연산 · lineage · Parent RDD · map(x × 2) · filter(x ≥ 8) · action 대기 · Partition 1 · 1 · 2 · 3 · Partition 2 · 4 · 5 · 6 · Driver 결과 —. 아직 action이 없어 데이터 처리는 시작하지 않습니다.논리 연산 · lineageParent RDDmap(x × 2)filter(x ≥ 8)action 대기Partition 1123Partition 2456Driver 결과 —
Spark · 지연 실행 · 1논리 연산 · lineage · Parent RDD · map(x × 2) · filter(x ≥ 8) · action 대기 · Partition 1 · 입력 · map · filter · count · 1 · 2 · 3 · Partition 2 · 입력 · map · filter · count · 4 · 5 · 6 · Driver 결과 —. 아직 action이 없어 데이터 처리는 시작하지 않습니다.논리 연산 · lineageParentRDDmap(x ×2)filter(x≥ 8)action 대기Partition 1입력mapfiltercount123Partition 2입력mapfiltercount456Driver 결과 —

2. count action이 계산을 요구한 뒤 각 partition의 연산을 보여줍니다.

Spark · 지연 실행 · 2논리 연산 · lineage · Parent RDD · map(x × 2) · filter(x ≥ 8) · count() · count() 호출 · 계산 중 · Partition 1 · 1 · 2 · 2 · 4 · 3 · 6 · Partition 2 · 4 · 8 · 5 · 10 · 6 · 12 · Driver 결과 —. 각 partition에서 map(x × 2)을 계산합니다.논리 연산 · lineageParent RDDmap(x × 2)filter(x ≥ 8)count()count() 호출 · 계산 중Partition 1122436Partition 248510612Driver 결과 —
Spark · 지연 실행 · 2논리 연산 · lineage · Parent RDD · map(x × 2) · filter(x ≥ 8) · count() · count() 호출 · 계산 중 · Partition 1 · 입력 · map · filter · count · 1 · 2 · 2 · 4 · 3 · 6 · Partition 2 · 입력 · map · filter · count · 4 · 8 · 5 · 10 · 6 · 12 · Driver 결과 —. 각 partition에서 map(x × 2)을 계산합니다.논리 연산 · lineageParentRDDmap(x ×2)filter(x≥ 8)count()count() 호출 · 계산 중Partition 1입력mapfiltercount122436Partition 2입력mapfiltercount48510612Driver 결과 —

3. partition 결과 [] / [8, 10, 12] → count 0 + 3 → driver 결과 3. collect도 Action입니다.

Spark · 지연 실행 · 3논리 연산 · lineage · Parent RDD · map(x × 2) · filter(x ≥ 8) · count() · 계산 완료 · Partition 1 · 1 · 2 · 2 · 4 · 3 · 6 · [] · 0 · Partition 2 · 4 · 8 · 8 · 5 · 10 · 10 · 6 · 12 · 12 · 3 · Driver 결과 3 · 0 + 3 = 3. 0 + 3 = 3. count 결과를 driver에 반환합니다.논리 연산 · lineageParent RDDmap(x × 2)filter(x ≥ 8)count()계산 완료Partition 1122436[]0Partition 248851010612123Driver 결과 30 + 3 = 3
Spark · 지연 실행 · 3논리 연산 · lineage · Parent RDD · map(x × 2) · filter(x ≥ 8) · count() · 계산 완료 · Partition 1 · 입력 · map · filter · count · 1 · 2 · 2 · 4 · 3 · 6 · [] · 0 · Partition 2 · 입력 · map · filter · count · 4 · 8 · 8 · 5 · 10 · 10 · 6 · 12 · 12 · 3 · Driver 결과 3 · 0 + 3 = 3. 0 + 3 = 3. count 결과를 driver에 반환합니다.논리 연산 · lineageParentRDDmap(x ×2)filter(x≥ 8)count()계산 완료Partition 1입력mapfiltercount122436[]0Partition 2입력mapfiltercount48851010612123Driver 결과 30 + 3 = 3
원본 도해

filter, map 등 다양한 Tranformation 을 적용하는 것을 반복하다가 최종적으로는 count()와 같은 Action 을 호출해 결과를 만들어낸다. 이 때, Action 시점까지 Transformation 요청을 미루는 것을 Lazy Evaluation이라 한다.

Lazy Evaluation 장점

  • 많은 데이터를 다룰 때, map(withColumn), filter(where)과 같은 함수를 호출할 때마다 즉시 연산된다면 데이터 로딩이 잦아져 네트워크 비용이 증가한다.

  • map, filter 등을 통해 최적화가 가능한 로직이 존재할 경우 지연로딩함으로써 불필요한 연산을 피할 수 있다.

5. Partition

데이터 시스템에서 Partition이란, 전체에서 나누어진 부분을 말한다. 데이터가 수천억 건일 경우, 단일 머신에서 처리하기 어렵다. 따라서 사용자는 DataFrame이라는 추상화된 API를 통해 데이터를 '하나'처럼 다루지만, Spark는 데이터를 분할해 Partition 단위로 데이터를 처리한다.