合併

使用者定義的 CombineFn
可用於合併 PCollection
中的所有元素 (全域合併) 或合併與每個索引鍵相關的所有元素。
雖然結果類似於應用 GroupByKey
,然後聚合每個 Iterable
中的值,但這會影響您必須撰寫的程式碼以及管道的效能。撰寫一個 ParDo
來計算每個值中的元素數量會非常簡單。但是,如執行模型中所述,這也需要由單一工作節點處理與每個索引鍵相關的所有值。這會引入大量的通訊負擔。使用 CombineFn
需要將程式碼結構化為關聯性和可交換運算。但是,它允許使用預先計算的部分總和。
請參閱 Beam 程式設計指南 中的詳細資訊。
範例
範例 1:全域合併
使用全域合併將給定 PCollection
中的所有元素合併為單一值,在您的管道中表示為包含一個元素的新 PCollection
。以下範例程式碼顯示如何應用 Beam 提供的總和合併函數,以產生整數 PCollection
的單一總和值。
範例 2:索引鍵合併
使用索引鍵合併將與每個索引鍵相關的所有值合併為每個索引鍵的單一輸出值。與全域合併一樣,傳遞到索引鍵合併的函數必須具有關聯性和可交換性。
// PCollection is grouped by key and the Double values associated with each key are combined into a Double.
PCollection<KV<String, Double>> salesRecords = ...;
PCollection<KV<String, Double>> totalSalesPerPerson =
salesRecords.apply(Combine.<String, Double, Double>perKey(
new Sum.SumDoubleFn()));
// The combined value is of a different type than the original collection of values per key. PCollection has
// keys of type String and values of type Integer, and the combined value is a Double.
PCollection<KV<String, Integer>> playerAccuracy = ...;
PCollection<KV<String, Double>> avgAccuracyPerPlayer =
playerAccuracy.apply(Combine.<String, Integer, Double>perKey(
new MeanInts())));
範例 3:
相關轉換
上次更新於 2024/10/31
您是否找到了您要找的所有內容?
所有內容是否實用且清晰?您想更改任何內容嗎?請告訴我們!