apache beam 入門之數據集PCollection的拆分和合並

目錄:apache beam 個人使用經驗總結目錄和入門指導(Java)

有時候我們會需要對PCollection數據集進行拆分, 分別進行不同的計算後,再合併成1個數據集。

拆分數據集

拆分數據集有2種方式,1種是使用PartitionFn。
假設我們要將1個整數的數據集分成2份,奇數和偶數分別處理,則可以如下:

    PCollection<Integer> numbers = pipeline.apply(Create.of(1,2,3,4,5));
    PCollectionList<Integer> numbersList
            = numbers.apply(Partition.of(2, new PartitionFn<Integer>(){
        // numPartitions是上面這行定義的這個2,即分區數量
        public int partitionFor(Integer input, int numPartitions) {
// 如果是偶數,返回0,表示輸出到第0個數據集中
            if(input % 2 == 0) {
                return 0;
            }
// 返回1表示輸出到第1個數據集中
            else{
                return 1
            }
        }
    }));

其中Partition.of(count,PartitionFn) 中的count指的是你需要分成多少份, 然後在實現partitonFor接口的時候,你返回幾,就代表這份數據被分到哪個數據集中。
生成了numberList後,就可以從中取出自己需要的數據集進行處理

PCollection<Integer> pEven = numbersList.get(0);
PCollection<Integer> pOdd = numbersList.get(1);

但這種方式只能通過確定數據集序號的方式去拆分。
注意分區數count必須是運行前就確定好的,而不能運行中去計算
——————————————————————————————————————

另一種拆分方式是自己寫過濾器,過濾2次,把數據集過濾成2份數據集。

    PCollection<Integer> pEven = numbers.apply(ParDo.of(new DoFn<Integer, Integer>() {
        @ProcessElement
        public void processElement(ProcessContext context) {
            int element = context.element();
            if (element % 2 == 0) {
                context.output(element);
            }
        }
    }));
    PCollection<Integer> pOdd = numbers.apply(ParDo.of(new DoFn<Integer, Integer>() {
        @ProcessElement
        public void processElement(ProcessContext context) {
            int element = context.element();
            if (element % 2 == 1) {
                context.output(element);
            }
        }
    }));

不過這種方式相當於操作了2次原數據集,性能上會有影響。儘可能使用Partition去拆分數據集。

數據集合並

合併時,需要先合成1個PCollectionList,才能用Flatten進行合併。

PCollectionList<Integer> numberList = PCollectionList.of(pOdd).and(pEven);
pCollection<Integer> mergeNumber = numberList.apply(Flatten.<Integer>pCollections());

注意合併時,數據集內的元素類型必須一致,否則運行時會報錯

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章