[英]How does spark calculates number of records in a dataframe?
我知道 df.count() 將觸發火花動作並返回數據框中存在的記錄數,但我想知道這個過程在內部是如何工作的,火花會遍歷整個數據幀以計算記錄數還是有其他的優化技術,例如將值存儲在數據框的元數據中?
我正在使用 pyspark 3.2.1。
似乎在運行df.count()
的底層實際上使用了Count聚合類。 我基於Dataset.scala中count
方法的定義。
/**
* Returns the number of rows in the Dataset.
* @group action
* @since 1.6.0
*/
def count(): Long = withAction("count", groupBy().count().queryExecution) { plan =>
plan.executeCollect().head.getLong(0)
}
是否有任何其他優化技術,例如將值存儲在數據幀的元數據中?
它將采用 Catalyst 使用的所有相同優化策略。 它創建表達式的有向圖,評估並匯總它們。 它沒有將計數值存儲為元數據,這將違反 Spark 的惰性求值原則。
我進行了一個實驗並驗證了df.count()
和df.groupBy().count()
產生了相同的物理計划。
df = spark.createDataFrame(pd.DataFrame({"a": [1,2,3], "b": ["a", "b", "c"]}))
# count using the Dataframe method
df.count()
# count using the Count aggregator
cnt_agg = df.groupBy().count()
這兩個工作產生了相同的物理計划:
== Physical Plan ==
AdaptiveSparkPlan (9)
+- == Final Plan ==
* HashAggregate (6)
+- ShuffleQueryStage (5), Statistics(sizeInBytes=64.0 B, rowCount=4, isRuntime=true)
+- Exchange (4)
+- * HashAggregate (3)
+- * Project (2)
+- * Scan ExistingRDD (1)
+- == Initial Plan ==
HashAggregate (8)
+- Exchange (7)
+- HashAggregate (3)
+- Project (2)
+- Scan ExistingRDD (1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.