詳解 Flink DataStream中min(),minBy(),max(),max()之間的區別

ipoo發表於2020-06-10

解釋

官方文件中:

The difference between min and minBy is that min returns the minimum value, whereas minBy returns the element that has the minimum value in this field (same for max and maxBy).

翻譯:

min和minBy之間的區別是min返回最小值,而minBy返回在此欄位中具有最小值的元素(與max和maxBy相同)。

但是事實上,min與max 也會返回整個元素。

不同的是min會根據指定的欄位取最小值,並且把這個值儲存在對應的位置上,對於其他的欄位取了最先獲取的值,不能保證每個元素的數值正確,max同理。

而minBy會返回指定欄位取最小值的元素,並且會覆蓋指定欄位小於當前已找到的最小值元素。maxBy同理。

示例論證

先拿min()與minBy()舉例:

取第三個元素的最小值

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //獲取資料來源
        List data = new ArrayList<Tuple3<Integer,Integer,Integer>>();
        data.add(new Tuple3<>(0,2,2));
        data.add(new Tuple3<>(0,1,1));
        data.add(new Tuple3<>(0,5,6));
        data.add(new Tuple3<>(0,3,5));
        data.add(new Tuple3<>(1,1,9));
        data.add(new Tuple3<>(1,2,8));
        data.add(new Tuple3<>(1,3,10));
        data.add(new Tuple3<>(1,2,9));

        DataStreamSource<Tuple3<Integer,Integer,Integer>> items = env.fromCollection(data);
        items.keyBy(0).min(2).print();
        
        env.execute("defined streaming source");
    }

輸出結果:

(0,2,2)
(0,2,1)
(0,2,1)
(0,2,1)
(1,1,9)
(1,1,8)
(1,1,8)
(1,1,8)

可以看到返回的元素第二個欄位取的是獲取到第一個元素的欄位值; 往下找,第二個元素的指定值是最小的,則把這個值儲存的對應位置。

接下來再看minBy()的執行結果:

(0,2,2)
(0,1,1)
(0,1,1)
(0,1,1)
(1,1,9)
(1,2,8)
(1,2,8)
(1,2,8)

返回的是指定欄位最小值的元素。可以看到元素數值的正確。

當然max(),maxBy同理。

更多文章:www.ipooli.com

掃碼關注公眾號《ipoo》
ipoo

相關文章