結合

Javadoc Javadoc


ユーザー定義のCombineFnは、PCollection内のすべての要素を結合(グローバル結合)したり、各キーに関連付けられたすべての要素を結合するために適用できます。

結果は、GroupByKeyを適用した後、各Iterable内の値を集計する場合と似ていますが、記述する必要があるコードとパイプラインのパフォーマンスに影響があります。各値の要素数をカウントするParDoを記述するのは非常に簡単です。ただし、実行モデルで説明されているように、各キーに関連付けられたすべての値を単一のワーカーで処理する必要もあります。これにより、多くの通信オーバーヘッドが発生します。CombineFnを使用するには、コードを結合法則と可換法則の演算として構成する必要があります。ただし、部分和を使用して事前に計算できます。

Beamプログラミングガイドで詳細を確認してください。

例1:グローバル結合

グローバル結合を使用して、特定のPCollection内のすべての要素を単一の値に結合し、パイプライン内で1つの要素を含む新しいPCollectionとして表現します。次のコード例は、Beamが提供する合計結合関数を適用して、整数のPCollectionの単一の合計値を生成する方法を示しています。

// Sum.SumIntegerFn() combines the elements in the input PCollection. The resulting PCollection, called sum,
// contains one value: the sum of all the elements in the input PCollection.
PCollection<Integer> pc = ...;
PCollection<Integer> sum = pc.apply(
   Combine.globally(new Sum.SumIntegerFn()));

例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: