数据集转换

本文档深入介绍了DataSet上的可用转换。有关Flink Java API的一般介绍,请参阅编程指南

有关在具有密集索引的数据集中压缩数据元,请参阅Zip数据元指南

Map

Map转换在DataSet的每个数据元上应用用户定义的map函数。它实现了一对一的映射,也就是说,函数必须返回一个数据元。

以下代码将Integer对的DataSet转换为Integers的DataSet:

  1. // MapFunction that adds two integer values
  2. public class IntAdder implements MapFunction<Tuple2<Integer, Integer>, Integer> {
  3. @Override
  4. public Integer map(Tuple2<Integer, Integer> in) {
  5. return in.f0 + in.f1;
  6. }
  7. }
  8. // [...]
  9. DataSet<Tuple2<Integer, Integer>> intPairs = // [...]
  10. DataSet<Integer> intSums = intPairs.map(new IntAdder());
  1. val intPairs: DataSet[(Int, Int)] = // [...]
  2. val intSums = intPairs.map { pair => pair._1 + pair._2 }
  1. intSums = intPairs.map(lambda x: sum(x))

FlatMap

FlatMap转换在DataSet的每个数据元上应用用户定义的平面映射函数。map函数的这种变体可以为每个输入数据元返回任意多个结果数据元(包括none)。

以下代码将文本行的DataSet转换为单词的DataSet:

  1. // FlatMapFunction that tokenizes a String by whitespace characters and emits all String tokens.
  2. public class Tokenizer implements FlatMapFunction<String, String> {
  3. @Override
  4. public void flatMap(String value, Collector<String> out) {
  5. for (String token : value.split("\\W")) {
  6. out.collect(token);
  7. }
  8. }
  9. }
  10. // [...]
  11. DataSet<String> textLines = // [...]
  12. DataSet<String> words = textLines.flatMap(new Tokenizer());
  1. val textLines: DataSet[String] = // [...]
  2. val words = textLines.flatMap { _.split(" ") }
  1. words = lines.flat_map(lambda x,c: [line.split() for line in x])

MapPartition

MapPartition在单个函数调用中转换并行分区。map-partition函数将分区作为Iterable获取,并且可以生成任意数量的结果值。每个分区中的数据元数量取决于并行度和先前的 算子操作。

以下代码将文本行的DataSet转换为每个分区的计数数据集:

  1. public class PartitionCounter implements MapPartitionFunction<String, Long> {
  2. public void mapPartition(Iterable<String> values, Collector<Long> out) {
  3. long c = 0;
  4. for (String s : values) {
  5. c++;
  6. }
  7. out.collect(c);
  8. }
  9. }
  10. // [...]
  11. DataSet<String> textLines = // [...]
  12. DataSet<Long> counts = textLines.mapPartition(new PartitionCounter());
  1. val textLines: DataSet[String] = // [...]
  2. // Some is required because the return value must be a Collection.
  3. // There is an implicit conversion from Option to a Collection.
  4. val counts = texLines.mapPartition { in => Some(in.size) }
  1. counts = lines.map_partition(lambda x,c: [sum(1 for _ in x)])

Filter

Filter转换在DataSet的每个数据元上应用用户定义的过滤器函数,并仅保存函数返回的数据元true

以下代码从DataSet中删除所有小于零的整数:

  1. // FilterFunction that filters out all Integers smaller than zero.
  2. public class NaturalNumberFilter implements FilterFunction<Integer> {
  3. @Override
  4. public boolean filter(Integer number) {
  5. return number >= 0;
  6. }
  7. }
  8. // [...]
  9. DataSet<Integer> intNumbers = // [...]
  10. DataSet<Integer> naturalNumbers = intNumbers.filter(new NaturalNumberFilter());
  1. val intNumbers: DataSet[Int] = // [...]
  2. val naturalNumbers = intNumbers.filter { _ > 0 }
  1. naturalNumbers = intNumbers.filter(lambda x: x > 0)

重要信息:系统假定该函数不会修改应用谓词的数据元。违反此假设可能会导致错误的结果。

元组数据集的Projection

Project转换删除或移动元组DataSet的Tuple字段。project(int…)方法选择应由其索引保存的元组字段,并在输出元组中定义它们的顺序。

预测不需要定义用户函数。

以下代码显示了在DataSet上应用项目转换的不同方法:

  1. DataSet<Tuple3<Integer, Double, String>> in = // [...]
  2. // converts Tuple3<Integer, Double, String> into Tuple2<String, Integer>
  3. DataSet<Tuple2<String, Integer>> out = in.project(2,0);

使用类型提示进行Projection

请注意,Java编译器无法推断project 算子的返回类型如果您对 算子的结果调用另一个 算子,则可能会导致问题,project例如:

  1. DataSet<Tuple5<String,String,String,String,String>> ds = ....
  2. DataSet<Tuple1<String>> ds2 = ds.project(0).distinct(0);

通过提示返回类型的project 算子可以克服此问题,如下所示:

  1. DataSet<Tuple1<String>> ds2 = ds.<Tuple1<String>>project(0).distinct(0);
  1. Not supported.
  1. out = in.project(2,0);

分组数据集的转换

reduce 算子操作可以对分组数据集进行 算子操作。指定用于分组的Keys可以通过多种方式完成:

  • 关键表达
  • 键选择器函数
  • 一个或多个字段位置键(仅限元组数据集)
  • 案例类字段(仅限案例类)请查看reduce示例以了解如何指定分组键。

Reduce分组数据集

应用于分组DataSet的Reduce转换使用用户定义的reduce函数将每个组Reduce为单个数据元。对于每组输入数据元,reduce函数连续地将数据元对组合成一个数据元,直到每个组只剩下一个数据元。

请注意,对于ReduceFunction返回对象的被Keys化字段,应与输入值匹配。这是因为reduce是可隐式组合的,并且从组合 算子发出的对象在传递给reduce 算子时再次按键分组。

Reduce由键表达式分组的DataSet

键表达式指定DataSet的每个数据元的一个或多个字段。每个键表达式都是公共字段的名称或getter方法。点可用于向下钻取对象。关键表达式“*”选择所有字段。以下代码显示如何使用键表达式对POJO DataSet进行分组,并使用reduce函数对其进行缩减。

  1. // some ordinary POJO
  2. public class WC {
  3. public String word;
  4. public int count;
  5. // [...]
  6. }
  7. // ReduceFunction that sums Integer attributes of a POJO
  8. public class WordCounter implements ReduceFunction<WC> {
  9. @Override
  10. public WC reduce(WC in1, WC in2) {
  11. return new WC(in1.word, in1.count + in2.count);
  12. }
  13. }
  14. // [...]
  15. DataSet<WC> words = // [...]
  16. DataSet<WC> wordCounts = words
  17. // DataSet grouping on field "word"
  18. .groupBy("word")
  19. // apply ReduceFunction on grouped DataSet
  20. .reduce(new WordCounter());
  1. // some ordinary POJO
  2. class WC(val word: String, val count: Int) {
  3. def this() {
  4. this(null, -1)
  5. }
  6. // [...]
  7. }
  8. val words: DataSet[WC] = // [...]
  9. val wordCounts = words.groupBy("word").reduce {
  10. (w1, w2) => new WC(w1.word, w1.count + w2.count)
  11. }
  1. Not supported.

Reduce由KeySelector函数分组的DataSet

键选择器函数从DataSet的每个数据元中提取键值。提取的键值用于对DataSet进行分组。以下代码显示如何使用键选择器函数对POJO DataSet进行分组,并使用reduce函数对其进行缩减。

  1. // some ordinary POJO
  2. public class WC {
  3. public String word;
  4. public int count;
  5. // [...]
  6. }
  7. // ReduceFunction that sums Integer attributes of a POJO
  8. public class WordCounter implements ReduceFunction<WC> {
  9. @Override
  10. public WC reduce(WC in1, WC in2) {
  11. return new WC(in1.word, in1.count + in2.count);
  12. }
  13. }
  14. // [...]
  15. DataSet<WC> words = // [...]
  16. DataSet<WC> wordCounts = words
  17. // DataSet grouping on field "word"
  18. .groupBy(new SelectWord())
  19. // apply ReduceFunction on grouped DataSet
  20. .reduce(new WordCounter());
  21. public class SelectWord implements KeySelector<WC, String> {
  22. @Override
  23. public String getKey(Word w) {
  24. return w.word;
  25. }
  26. }
  1. // some ordinary POJO
  2. class WC(val word: String, val count: Int) {
  3. def this() {
  4. this(null, -1)
  5. }
  6. // [...]
  7. }
  8. val words: DataSet[WC] = // [...]
  9. val wordCounts = words.groupBy { _.word } reduce {
  10. (w1, w2) => new WC(w1.word, w1.count + w2.count)
  11. }
  1. class WordCounter(ReduceFunction):
  2. def reduce(self, in1, in2):
  3. return (in1[0], in1[1] + in2[1])
  4. words = // [...]
  5. wordCounts = words \
  6. .group_by(lambda x: x[0]) \
  7. .reduce(WordCounter())

Reduce由字段位置键分组的DataSet(仅限元组数据集)

字段位置键指定用作分组键的元组数据集的一个或多个字段。以下代码显示如何使用字段位置键并应用reduce函数

  1. DataSet<Tuple3<String, Integer, Double>> tuples = // [...]
  2. DataSet<Tuple3<String, Integer, Double>> reducedTuples = tuples
  3. // group DataSet on first and second field of Tuple
  4. .groupBy(0, 1)
  5. // apply ReduceFunction on grouped DataSet
  6. .reduce(new MyTupleReducer());
  1. val tuples = DataSet[(String, Int, Double)] = // [...]
  2. // group on the first and second Tuple field
  3. val reducedTuples = tuples.groupBy(0, 1).reduce { ... }
  1. reducedTuples = tuples.group_by(0, 1).reduce( ... )

按案例类字段分组的DataSetReduce

使用Case Classes时,您还可以使用字段名称指定分组键:

  1. Not supported.
  1. case class MyClass(val a: String, b: Int, c: Double)
  2. val tuples = DataSet[MyClass] = // [...]
  3. // group on the first and second field
  4. val reducedTuples = tuples.groupBy("a", "b").reduce { ... }
  1. Not supported.

GroupReduce在分组数据集上

应用于分组DataSet的GroupReduce转换为每个组调用用户定义的group-reduce函数。这与Reduce之间的区别在于用户定义的函数会立即获得整个组。在组的所有数据元上使用Iterable调用该函数,并且可以返回任意数量的结果数据元。

由字段位置键分组的DataSet上的GroupReduce(仅限元组数据集)

以下代码显示如何从按Integer分组的DataSet中删除重复的字符串。

  1. public class DistinctReduce
  2. implements GroupReduceFunction<Tuple2<Integer, String>, Tuple2<Integer, String>> {
  3. @Override
  4. public void reduce(Iterable<Tuple2<Integer, String>> in, Collector<Tuple2<Integer, String>> out) {
  5. Set<String> uniqStrings = new HashSet<String>();
  6. Integer key = null;
  7. // add all strings of the group to the set
  8. for (Tuple2<Integer, String> t : in) {
  9. key = t.f0;
  10. uniqStrings.add(t.f1);
  11. }
  12. // emit all unique strings.
  13. for (String s : uniqStrings) {
  14. out.collect(new Tuple2<Integer, String>(key, s));
  15. }
  16. }
  17. }
  18. // [...]
  19. DataSet<Tuple2<Integer, String>> input = // [...]
  20. DataSet<Tuple2<Integer, String>> output = input
  21. .groupBy(0) // group DataSet by the first tuple field
  22. .reduceGroup(new DistinctReduce()); // apply GroupReduceFunction
  1. val input: DataSet[(Int, String)] = // [...]
  2. val output = input.groupBy(0).reduceGroup {
  3. (in, out: Collector[(Int, String)]) =>
  4. in.toSet foreach (out.collect)
  5. }
  1. class DistinctReduce(GroupReduceFunction):
  2. def reduce(self, iterator, collector):
  3. dic = dict()
  4. for value in iterator:
  5. dic[value[1]] = 1
  6. for key in dic.keys():
  7. collector.collect(key)
  8. output = data.group_by(0).reduce_group(DistinctReduce())

按键表达式,键选择器函数或案例类字段分组的DataSet上的GroupReduce

类似于Reduce转换中的键表达式键选择器函数案例类字段的工作

对已排序的组进行GroupReduce

group-reduce函数使用Iterable访问组的数据元。可选地,Iterable可以按指定的顺序分发组的数据元。在许多情况下,这可以帮助降低用户定义的组Reduce函数的复杂性并提高其效率。

下面的代码显示了如何删除由Integer分组并按String排序的DataSet中的重复字符串的另一个示例。

  1. // GroupReduceFunction that removes consecutive identical elements
  2. public class DistinctReduce
  3. implements GroupReduceFunction<Tuple2<Integer, String>, Tuple2<Integer, String>> {
  4. @Override
  5. public void reduce(Iterable<Tuple2<Integer, String>> in, Collector<Tuple2<Integer, String>> out) {
  6. Integer key = null;
  7. String comp = null;
  8. for (Tuple2<Integer, String> t : in) {
  9. key = t.f0;
  10. String next = t.f1;
  11. // check if strings are different
  12. if (com == null || !next.equals(comp)) {
  13. out.collect(new Tuple2<Integer, String>(key, next));
  14. comp = next;
  15. }
  16. }
  17. }
  18. }
  19. // [...]
  20. DataSet<Tuple2<Integer, String>> input = // [...]
  21. DataSet<Double> output = input
  22. .groupBy(0) // group DataSet by first field
  23. .sortGroup(1, Order.ASCENDING) // sort groups on second tuple field
  24. .reduceGroup(new DistinctReduce());
  1. val input: DataSet[(Int, String)] = // [...]
  2. val output = input.groupBy(0).sortGroup(1, Order.ASCENDING).reduceGroup {
  3. (in, out: Collector[(Int, String)]) =>
  4. var prev: (Int, String) = null
  5. for (t <- in) {
  6. if (prev == null || prev != t)
  7. out.collect(t)
  8. prev = t
  9. }
  10. }
  1. class DistinctReduce(GroupReduceFunction):
  2. def reduce(self, iterator, collector):
  3. dic = dict()
  4. for value in iterator:
  5. dic[value[1]] = 1
  6. for key in dic.keys():
  7. collector.collect(key)
  8. output = data.group_by(0).sort_group(1, Order.ASCENDING).reduce_group(DistinctReduce())

注意:如果在reduce 算子操作之前使用 算子的基于排序的执行策略建立分组,则GroupSort通常是免费的。

可组合的GroupReduce函数

与reduce函数相比,group-reduce函数不是可隐式组合的。为了使组合 - 缩减函数可组合,它必须实现GroupCombineFunction接口。

要点:接口的通用输入和输出类型GroupCombineFunction必须等于GroupReduceFunction以下示例中所示的通用输入类型

  1. // Combinable GroupReduceFunction that computes a sum.
  2. public class MyCombinableGroupReducer implements
  3. GroupReduceFunction<Tuple2<String, Integer>, String>,
  4. GroupCombineFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>
  5. {
  6. @Override
  7. public void reduce(Iterable<Tuple2<String, Integer>> in,
  8. Collector<String> out) {
  9. String key = null;
  10. int sum = 0;
  11. for (Tuple2<String, Integer> curr : in) {
  12. key = curr.f0;
  13. sum += curr.f1;
  14. }
  15. // concat key and sum and emit
  16. out.collect(key + "-" + sum);
  17. }
  18. @Override
  19. public void combine(Iterable<Tuple2<String, Integer>> in,
  20. Collector<Tuple2<String, Integer>> out) {
  21. String key = null;
  22. int sum = 0;
  23. for (Tuple2<String, Integer> curr : in) {
  24. key = curr.f0;
  25. sum += curr.f1;
  26. }
  27. // emit tuple with key and sum
  28. out.collect(new Tuple2<>(key, sum));
  29. }
  30. }
  1. // Combinable GroupReduceFunction that computes two sums.
  2. class MyCombinableGroupReducer
  3. extends GroupReduceFunction[(String, Int), String]
  4. with GroupCombineFunction[(String, Int), (String, Int)]
  5. {
  6. override def reduce(
  7. in: java.lang.Iterable[(String, Int)],
  8. out: Collector[String]): Unit =
  9. {
  10. val r: (String, Int) =
  11. in.asScala.reduce( (a,b) => (a._1, a._2 + b._2) )
  12. // concat key and sum and emit
  13. out.collect (r._1 + "-" + r._2)
  14. }
  15. override def combine(
  16. in: java.lang.Iterable[(String, Int)],
  17. out: Collector[(String, Int)]): Unit =
  18. {
  19. val r: (String, Int) =
  20. in.asScala.reduce( (a,b) => (a._1, a._2 + b._2) )
  21. // emit tuple with key and sum
  22. out.collect(r)
  23. }
  24. }
  1. class GroupReduce(GroupReduceFunction):
  2. def reduce(self, iterator, collector):
  3. key, int_sum = iterator.next()
  4. for value in iterator:
  5. int_sum += value[1]
  6. collector.collect(key + "-" + int_sum))
  7. def combine(self, iterator, collector):
  8. key, int_sum = iterator.next()
  9. for value in iterator:
  10. int_sum += value[1]
  11. collector.collect((key, int_sum))
  12. data.reduce_group(GroupReduce(), combinable=True)

GroupCombine在分组数据集上

GroupCombine变换是可组合GroupReduceFunction中的组合步骤的一般形式。从某种意义上说,它允许将输入类型组合I到任意输出类型O相反,GroupReduce中的组合步骤仅允许从输入类型I到输出类型的组合I这是因为GroupReduceFunction中的reduce步骤需要输入类型I

在一些应用中,期望在执行附加变换(例如,减小数据大小)之前将DataSet组合成中间格式。这可以通过CombineGroup转换以非常低的成本实现。

注意:分组数据集上的GroupCombine在内存中使用贪婪策略执行,该策略可能不会一次处理所有数据,而是以多个步骤处理。它也可以在各个分区上执行,而无需像GroupReduce转换那样进行数据交换。这可能会导致部分结果。

以下示例演示了如何将CombineGroup转换用于Slave WordCount实现。

  1. DataSet<String> input = [..] // The words received as input
  2. DataSet<Tuple2<String, Integer>> combinedWords = input
  3. .groupBy(0) // group identical words
  4. .combineGroup(new GroupCombineFunction<String, Tuple2<String, Integer>() {
  5. public void combine(Iterable<String> words, Collector<Tuple2<String, Integer>>) { // combine
  6. String key = null;
  7. int count = 0;
  8. for (String word : words) {
  9. key = word;
  10. count++;
  11. }
  12. // emit tuple with word and count
  13. out.collect(new Tuple2(key, count));
  14. }
  15. });
  16. DataSet<Tuple2<String, Integer>> output = combinedWords
  17. .groupBy(0) // group by words again
  18. .reduceGroup(new GroupReduceFunction() { // group reduce with full data exchange
  19. public void reduce(Iterable<Tuple2<String, Integer>>, Collector<Tuple2<String, Integer>>) {
  20. String key = null;
  21. int count = 0;
  22. for (Tuple2<String, Integer> word : words) {
  23. key = word;
  24. count++;
  25. }
  26. // emit tuple with word and count
  27. out.collect(new Tuple2(key, count));
  28. }
  29. });
  1. val input: DataSet[String] = [..] // The words received as input
  2. val combinedWords: DataSet[(String, Int)] = input
  3. .groupBy(0)
  4. .combineGroup {
  5. (words, out: Collector[(String, Int)]) =>
  6. var key: String = null
  7. var count = 0
  8. for (word <- words) {
  9. key = word
  10. count += 1
  11. }
  12. out.collect((key, count))
  13. }
  14. val output: DataSet[(String, Int)] = combinedWords
  15. .groupBy(0)
  16. .reduceGroup {
  17. (words, out: Collector[(String, Int)]) =>
  18. var key: String = null
  19. var sum = 0
  20. for ((word, sum) <- words) {
  21. key = word
  22. sum += count
  23. }
  24. out.collect((key, sum))
  25. }
  1. Not supported.

上面的替代WordCount实现演示了GroupCombine在执行GroupReduce转换之前如何组合单词。上面的例子只是一个概念证明。注意,组合步骤如何更改DataSet的类型,这通常需要在执行GroupReduce之前进行额外的Map转换。

聚合在分组元组数据集上

有一些常用的聚合 算子操作经常使用。Aggregate转换提供以下内置聚合函数:

  • Sum
  • Min,Sum
  • Max。聚合转换只能应用于元组数据集,并且仅支持字段位置键进行分组。

以下代码显示如何对按字段位置键分组的DataSet应用聚合转换:

  1. DataSet<Tuple3<Integer, String, Double>> input = // [...]
  2. DataSet<Tuple3<Integer, String, Double>> output = input
  3. .groupBy(1) // group DataSet on second field
  4. .aggregate(SUM, 0) // compute sum of the first field
  5. .and(MIN, 2); // compute minimum of the third field
  1. val input: DataSet[(Int, String, Double)] = // [...]
  2. val output = input.groupBy(1).aggregate(SUM, 0).and(MIN, 2)
  1. from flink.functions.Aggregation import Sum, Min
  2. input = # [...]
  3. output = input.group_by(1).aggregate(Sum, 0).and_agg(Min, 2)

要在DataSet上应用多个聚合,必须.and()在第一个聚合之后使用该函数,这意味着.aggregate(SUM, 0).and(MIN, 2)生成字段0的总和和原始DataSet的字段2的最小值。与此相反,.aggregate(SUM, 0).aggregate(MIN, 2)将在聚合上应用聚合。在给定的示例中,在计算由字段1分组的字段0的总和之后,它将产生字段2的最小值。

注意:将来会扩展聚合函数集。

MinBy / MaxBy在Grouped Tuple DataSet上

MinBy(MaxBy)转换为每组元组选择一个元组。选定的元组是一个元组,其一个或多个指定字段的值最小(最大)。用于比较的字段必须是有效的关键字段,即可比较。如果多个元组具有最小(最大)字段值,则返回这些元组的任意元组。

下面的代码显示了如何选择具有最小值的元组,每个元组的字段IntegerDouble字段具有相同的StringDataSet<Tuple3<Integer, String, Double>>

  1. DataSet<Tuple3<Integer, String, Double>> input = // [...]
  2. DataSet<Tuple3<Integer, String, Double>> output = input
  3. .groupBy(1) // group DataSet on second field
  4. .minBy(0, 2); // select tuple with minimum values for first and third field.
  1. val input: DataSet[(Int, String, Double)] = // [...]
  2. val output: DataSet[(Int, String, Double)] = input
  3. .groupBy(1) // group DataSet on second field
  4. .minBy(0, 2) // select tuple with minimum values for first and third field.
  1. Not supported.

Reduce完整的DataSet

Reduce转换将用户定义的reduce函数应用于DataSet的所有数据元。reduce函数随后将数据元对组合成一个数据元,直到只剩下一个数据元。

以下代码显示了如何对Integer DataSet的所有数据元求和:

  1. // ReduceFunction that sums Integers
  2. public class IntSummer implements ReduceFunction<Integer> {
  3. @Override
  4. public Integer reduce(Integer num1, Integer num2) {
  5. return num1 + num2;
  6. }
  7. }
  8. // [...]
  9. DataSet<Integer> intNumbers = // [...]
  10. DataSet<Integer> sum = intNumbers.reduce(new IntSummer());
  1. val intNumbers = env.fromElements(1,2,3)
  2. val sum = intNumbers.reduce (_ + _)
  1. intNumbers = env.from_elements(1,2,3)
  2. sum = intNumbers.reduce(lambda x,y: x + y)

使用Reduce转换Reduce完整的DataSet意味着最终的Reduce 算子操作不能并行完成。但是,reduce函数可以自动组合,因此Reduce转换不会限制大多数用例的可伸缩性。

完整DataSet上的GroupReduce

GroupReduce转换在DataSet的所有数据元上应用用户定义的group-reduce函数。group-reduce可以迭代DataSet的所有数据元并返回任意数量的结果数据元。

以下示例显示如何在完整DataSet上应用GroupReduce转换:

  1. DataSet<Integer> input = // [...]
  2. // apply a (preferably combinable) GroupReduceFunction to a DataSet
  3. DataSet<Double> output = input.reduceGroup(new MyGroupReducer());
  1. val input: DataSet[Int] = // [...]
  2. val output = input.reduceGroup(new MyGroupReducer())
  1. output = data.reduce_group(MyGroupReducer())

注意:如果group-reduce函数不可组合,则无法并行完成对完整DataSet的GroupReduce转换。因此,这可能是计算密集型 算子操作。请参阅上面的“可组合GroupReduceFunctions”一节,了解如何实现可组合的group-reduce函数。

GroupCombine在完整的DataSet上

完整DataSet上的GroupCombine与分组DataSet上的GroupCombine类似。数据在所有节点上分区,然后以贪婪的方式组合(即,只有一次合并到存储器中的数据)。

在完整的Tuple DataSet上聚合

有一些常用的聚合 算子操作经常使用。Aggregate转换提供以下内置聚合函数:

  • Sum
  • Min,Sum
  • Max。聚合转换只能应用于元组数据集。

以下代码显示如何在完整DataSet上应用聚合转换:

  1. DataSet<Tuple2<Integer, Double>> input = // [...]
  2. DataSet<Tuple2<Integer, Double>> output = input
  3. .aggregate(SUM, 0) // compute sum of the first field
  4. .and(MIN, 1); // compute minimum of the second field
  1. val input: DataSet[(Int, String, Double)] = // [...]
  2. val output = input.aggregate(SUM, 0).and(MIN, 2)
  1. from flink.functions.Aggregation import Sum, Min
  2. input = # [...]
  3. output = input.aggregate(Sum, 0).and_agg(Min, 2)

注意:扩展支持的聚合函数集在我们的路线图中。

完整的Tuple DataSet上的MinBy / MaxBy

MinBy(MaxBy)转换从元组的DataSet中选择一个元组。选定的元组是一个元组,其一个或多个指定字段的值最小(最大)。用于比较的字段必须是有效的关键字段,即可比较。如果多个元组具有最小(最大)字段值,则返回这些元组的任意元组。

下面的代码演示如何选择与为最大值的元组Integer,并Double从一个领域DataSet<Tuple3<Integer, String, Double>>

  1. DataSet<Tuple3<Integer, String, Double>> input = // [...]
  2. DataSet<Tuple3<Integer, String, Double>> output = input
  3. .maxBy(0, 2); // select tuple with maximum values for first and third field.
  1. val input: DataSet[(Int, String, Double)] = // [...]
  2. val output: DataSet[(Int, String, Double)] = input
  3. .maxBy(0, 2) // select tuple with maximum values for first and third field.
  1. Not supported.

Distinct

Distinct转换计算源DataSet的不同数据元的DataSet。以下代码从DataSet中删除所有重复的数据元:

  1. DataSet<Tuple2<Integer, Double>> input = // [...]
  2. DataSet<Tuple2<Integer, Double>> output = input.distinct();
  1. val input: DataSet[(Int, String, Double)] = // [...]
  2. val output = input.distinct()
  1. Not supported.

还可以使用以下方法更改DataSet中数据元的区别:

  • 一个或多个字段位置键(仅限元组数据集),
  • 键选择器函数,或
  • 一个关键的表达。

与列位置Keys取Distinct

  1. DataSet<Tuple2<Integer, Double, String>> input = // [...]
  2. DataSet<Tuple2<Integer, Double, String>> output = input.distinct(0,2);
  1. val input: DataSet[(Int, Double, String)] = // [...]
  2. val output = input.distinct(0,2)
  1. Not supported.

与KeySelector函数取Distinct

  1. private static class AbsSelector implements KeySelector<Integer, Integer> {
  2. private static final long serialVersionUID = 1L;
  3. @Override
  4. public Integer getKey(Integer t) {
  5. return Math.abs(t);
  6. }
  7. }
  8. DataSet<Integer> input = // [...]
  9. DataSet<Integer> output = input.distinct(new AbsSelector());
  1. val input: DataSet[Int] = // [...]
  2. val output = input.distinct {x => Math.abs(x)}
  1. Not supported.

用Key表达式取Distinct

  1. // some ordinary POJO
  2. public class CustomType {
  3. public String aName;
  4. public int aNumber;
  5. // [...]
  6. }
  7. DataSet<CustomType> input = // [...]
  8. DataSet<CustomType> output = input.distinct("aName", "aNumber");
  1. // some ordinary POJO
  2. case class CustomType(aName : String, aNumber : Int) { }
  3. val input: DataSet[CustomType] = // [...]
  4. val output = input.distinct("aName", "aNumber")
  1. Not supported.

也可以通过通配符指示使用所有字段:

  1. DataSet<CustomType> input = // [...]
  2. DataSet<CustomType> output = input.distinct("*");
  1. // some ordinary POJO
  2. val input: DataSet[CustomType] = // [...]
  3. val output = input.distinct("_")
  1. Not supported.

Join

Join转换将两个DataSet连接到一个DataSet中。两个DataSet的数据元连接在一个或多个可以使用的键上

  • 一个关键的表达
  • 键选择器函数
  • 一个或多个字段位置键(仅限元组数据集)。
  • 案例类字段有几种不同的方法可以执行Join转换,如下所示。

默认Join(关联Tuple2)

默认的Join转换生成一个包含两个字段的新Tuple DataSet。每个元组保存第一个元组字段中第一个输入DataSet的连接数据元和第二个字段中第二个输入DataSet的匹配数据元。

以下代码显示使用字段位置键的默认Join转换:

  1. public static class User { public String name; public int zip; }
  2. public static class Store { public Manager mgr; public int zip; }
  3. DataSet<User> input1 = // [...]
  4. DataSet<Store> input2 = // [...]
  5. // result dataset is typed as Tuple2
  6. DataSet<Tuple2<User, Store>>
  7. result = input1.join(input2)
  8. .where("zip") // key of the first input (users)
  9. .equalTo("zip"); // key of the second input (stores)
  1. val input1: DataSet[(Int, String)] = // [...]
  2. val input2: DataSet[(Double, Int)] = // [...]
  3. val result = input1.join(input2).where(0).equalTo(1)
  1. result = input1.join(input2).where(0).equal_to(1)

关联Join函数

Join转换还可以调用用户定义的连接函数来处理连接元组。连接函数接收第一个输入DataSet的一个数据元和第二个输入DataSet的一个数据元,并返回一个数据元。

以下代码使用键选择器函数执行DataSet与自定义java对象和Tuple DataSet的连接,并显示如何使用用户定义的连接函数:

  1. // some POJO
  2. public class Rating {
  3. public String name;
  4. public String category;
  5. public int points;
  6. }
  7. // Join function that joins a custom POJO with a Tuple
  8. public class PointWeighter
  9. implements JoinFunction<Rating, Tuple2<String, Double>, Tuple2<String, Double>> {
  10. @Override
  11. public Tuple2<String, Double> join(Rating rating, Tuple2<String, Double> weight) {
  12. // multiply the points and rating and construct a new output tuple
  13. return new Tuple2<String, Double>(rating.name, rating.points * weight.f1);
  14. }
  15. }
  16. DataSet<Rating> ratings = // [...]
  17. DataSet<Tuple2<String, Double>> weights = // [...]
  18. DataSet<Tuple2<String, Double>>
  19. weightedRatings =
  20. ratings.join(weights)
  21. // key of the first input
  22. .where("category")
  23. // key of the second input
  24. .equalTo("f0")
  25. // applying the JoinFunction on joining pairs
  26. .with(new PointWeighter());
  1. case class Rating(name: String, category: String, points: Int)
  2. val ratings: DataSet[Ratings] = // [...]
  3. val weights: DataSet[(String, Double)] = // [...]
  4. val weightedRatings = ratings.join(weights).where("category").equalTo(0) {
  5. (rating, weight) => (rating.name, rating.points * weight._2)
  6. }
  1. class PointWeighter(JoinFunction):
  2. def join(self, rating, weight):
  3. return (rating[0], rating[1] * weight[1])
  4. if value1[3]:
  5. weightedRatings =
  6. ratings.join(weights).where(0).equal_to(0). \
  7. with(new PointWeighter());

关联Flat-Join函数

类似于Map和FlatMap,FlatJoin的行为与Join相同,但它不是返回一个数据元,而是返回(收集),零,一个或多个数据元。

  1. public class PointWeighter
  2. implements FlatJoinFunction<Rating, Tuple2<String, Double>, Tuple2<String, Double>> {
  3. @Override
  4. public void join(Rating rating, Tuple2<String, Double> weight,
  5. Collector<Tuple2<String, Double>> out) {
  6. if (weight.f1 > 0.1) {
  7. out.collect(new Tuple2<String, Double>(rating.name, rating.points * weight.f1));
  8. }
  9. }
  10. }
  11. DataSet<Tuple2<String, Double>>
  12. weightedRatings =
  13. ratings.join(weights) // [...]
  1. case class Rating(name: String, category: String, points: Int)
  2. val ratings: DataSet[Ratings] = // [...]
  3. val weights: DataSet[(String, Double)] = // [...]
  4. val weightedRatings = ratings.join(weights).where("category").equalTo(0) {
  5. (rating, weight, out: Collector[(String, Double)]) =>
  6. if (weight._2 > 0.1) out.collect(rating.name, rating.points * weight._2)
  7. }

Not supported.

关联Projection(仅限Java / Python)

Join变换可以使用Projection构造结果元组,如下所示:

  1. DataSet<Tuple3<Integer, Byte, String>> input1 = // [...]
  2. DataSet<Tuple2<Integer, Double>> input2 = // [...]
  3. DataSet<Tuple4<Integer, String, Double, Byte>>
  4. result =
  5. input1.join(input2)
  6. // key definition on first DataSet using a field position key
  7. .where(0)
  8. // key definition of second DataSet using a field position key
  9. .equalTo(0)
  10. // select and reorder fields of matching tuples
  11. .projectFirst(0,2).projectSecond(1).projectFirst(1);

projectFirst(int…)projectSecond(int…)选择应组合成输出元组的第一个和第二个连接输入的字段。索引的顺序定义输出元组中的字段顺序。连接Projection也适用于非元组数据集。在这种情况下,projectFirst()或者projectSecond()必须不带参数调用才能将连接数据元添加到输出元组。

  1. Not supported.
  1. result = input1.join(input2).where(0).equal_to(0) \
  2. .project_first(0,2).project_second(1).project_first(1);

project_first(int…) and project_second(int…) select the fields of the first and second joined input that should be assembled into an output Tuple. The order of indexes defines the order of fields in the output tuple.The join projection works also for non-Tuple DataSets. In this case, project_first() or project_second() must be called without arguments to add a joined element to the output Tuple.

关联DataSet Size提示

为了引导优化器选择正确的执行策略,您可以提示要关联的DataSet的大小,如下所示:

  1. DataSet<Tuple2<Integer, String>> input1 = // [...]
  2. DataSet<Tuple2<Integer, String>> input2 = // [...]
  3. DataSet<Tuple2<Tuple2<Integer, String>, Tuple2<Integer, String>>>
  4. result1 =
  5. // hint that the second DataSet is very small
  6. input1.joinWithTiny(input2)
  7. .where(0)
  8. .equalTo(0);
  9. DataSet<Tuple2<Tuple2<Integer, String>, Tuple2<Integer, String>>>
  10. result2 =
  11. // hint that the second DataSet is very large
  12. input1.joinWithHuge(input2)
  13. .where(0)
  14. .equalTo(0);
  1. val input1: DataSet[(Int, String)] = // [...]
  2. val input2: DataSet[(Int, String)] = // [...]
  3. // hint that the second DataSet is very small
  4. val result1 = input1.joinWithTiny(input2).where(0).equalTo(0)
  5. // hint that the second DataSet is very large
  6. val result1 = input1.joinWithHuge(input2).where(0).equalTo(0)
  1. #hint that the second DataSet is very small
  2. result1 = input1.join_with_tiny(input2).where(0).equal_to(0)
  3. #hint that the second DataSet is very large
  4. result1 = input1.join_with_huge(input2).where(0).equal_to(0)

关联算法提示

Flink运行时可以以各种方式执行连接。在不同情况下,每种可能的方式都优于其他方式。系统会尝试自动选择合理的方式,但允许您手动选择策略,以防您想要强制执行连接的特定方式。

  1. DataSet<SomeType> input1 = // [...]
  2. DataSet<AnotherType> input2 = // [...]
  3. DataSet<Tuple2<SomeType, AnotherType> result =
  4. input1.join(input2, JoinHint.BROADCAST_HASH_FIRST)
  5. .where("id").equalTo("key");
  1. val input1: DataSet[SomeType] = // [...]
  2. val input2: DataSet[AnotherType] = // [...]
  3. // hint that the second DataSet is very small
  4. val result1 = input1.join(input2, JoinHint.BROADCAST_HASH_FIRST).where("id").equalTo("key")
  1. Not supported.

以下提示可用:

  • OPTIMIZER_CHOOSES:相当于不提供任何提示,将选择留给系统。

  • BROADCAST_HASH_FIRST:广播第一个输入并从中构建哈希表,由第二个输入探测。如果第一个输入非常小,这是一个很好的策略。

  • BROADCAST_HASH_SECOND:广播第二个输入并从中构建哈希表,由第一个输入探测。如果第二个输入非常小,这是一个很好的策略。

  • REPARTITIONHASH_FIRST:系统分区(shuffle)每个输入(除非输入已经分区)并从第一个输入构建哈希表。如果第一个输入小于第二个输入,则此策略很好,但两个输入仍然很大。注意:_这是系统使用的默认回退策略,如果不能进行大小估计,并且不能重新使用预先存在的分区和排序顺序。

  • REPARTITION_HASH_SECOND:系统分区(shuffle)每个输入(除非输入已经分区)并从第二个输入构建哈希表。如果第二个输入小于第一个输入,则此策略很好,但两个输入仍然很大。

  • REPARTITION_SORT_MERGE:系统对每个输入进行分区(shuffle)(除非输入已经分区)并对每个输入进行排序(除非它已经排序)。输入通过已排序输入的流合并来连接。如果已经对一个或两个输入进行了排序,则此策略很好。

Outer Join

OuterJoin转换在两个数据集上执行左,右或全外连接。外连接类似于常规(内部)连接,并创建在其键上相等的所有数据元对。此外,如果在另一侧没有找到匹配的Keys,则保存“外部”侧(左侧,右侧或两者都满)的记录。匹配数据元对(或一个数据元和null另一个输入值)被赋予a JoinFunction以将该对数据元转换为单个数据元,或者FlatJoinFunction将该数据元对转换为任意多个(包括无)数据元。

两个DataSet的数据元连接在一个或多个可以使用的键上

  • 一个关键的表达
  • 键选择器函数
  • 一个或多个字段位置键(仅限元组数据集)。
  • 案例类字段OuterJoins仅支持Java和Scala DataSet API。

具有连接函数的OuterJoin

OuterJoin转换调用用户定义的连接函数来处理连接元组。连接函数接收第一个输入DataSet的一个数据元和第二个输入DataSet的一个数据元,并返回一个数据元。根据外连接的类型(left,right,full),连接函数的两个输入数据元之一可以是null

以下代码使用键选择器函数执行DataSet与自定义java对象和Tuple DataSet的左外连接,并显示如何使用用户定义的连接函数:

  1. // some POJO
  2. public class Rating {
  3. public String name;
  4. public String category;
  5. public int points;
  6. }
  7. // Join function that joins a custom POJO with a Tuple
  8. public class PointAssigner
  9. implements JoinFunction<Tuple2<String, String>, Rating, Tuple2<String, Integer>> {
  10. @Override
  11. public Tuple2<String, Integer> join(Tuple2<String, String> movie, Rating rating) {
  12. // Assigns the rating points to the movie.
  13. // NOTE: rating might be null
  14. return new Tuple2<String, Double>(movie.f0, rating == null ? -1 : rating.points;
  15. }
  16. }
  17. DataSet<Tuple2<String, String>> movies = // [...]
  18. DataSet<Rating> ratings = // [...]
  19. DataSet<Tuple2<String, Integer>>
  20. moviesWithPoints =
  21. movies.leftOuterJoin(ratings)
  22. // key of the first input
  23. .where("f0")
  24. // key of the second input
  25. .equalTo("name")
  26. // applying the JoinFunction on joining pairs
  27. .with(new PointAssigner());
  1. case class Rating(name: String, category: String, points: Int)
  2. val movies: DataSet[(String, String)] = // [...]
  3. val ratings: DataSet[Ratings] = // [...]
  4. val moviesWithPoints = movies.leftOuterJoin(ratings).where(0).equalTo("name") {
  5. (movie, rating) => (movie._1, if (rating == null) -1 else rating.points)
  6. }
  1. Not supported.

具有Flat-Join函数的外部连接

类似于Map和FlatMap,具有Flat-Join函数的OuterJoin与具有连接函数的OuterJoin的行为方式相同,但它不返回一个数据元,而是返回(收集),零个,一个或多个数据元。

  1. public class PointAssigner
  2. implements FlatJoinFunction<Tuple2<String, String>, Rating, Tuple2<String, Integer>> {
  3. @Override
  4. public void join(Tuple2<String, String> movie, Rating rating
  5. Collector<Tuple2<String, Integer>> out) {
  6. if (rating == null ) {
  7. out.collect(new Tuple2<String, Integer>(movie.f0, -1));
  8. } else if (rating.points < 10) {
  9. out.collect(new Tuple2<String, Integer>(movie.f0, rating.points));
  10. } else {
  11. // do not emit
  12. }
  13. }
  14. DataSet<Tuple2<String, Integer>>
  15. moviesWithPoints =
  16. movies.leftOuterJoin(ratings) // [...]
  1. Not supported.
  1. Not supported.

关联算法提示

Flink运行时可以以各种方式执行外连接。在不同情况下,每种可能的方式都优于其他方式。系统会尝试自动选择合理的方式,但允许您手动选择策略,以防您想要强制执行外连接的特定方式。

  1. DataSet<SomeType> input1 = // [...]
  2. DataSet<AnotherType> input2 = // [...]
  3. DataSet<Tuple2<SomeType, AnotherType> result1 =
  4. input1.leftOuterJoin(input2, JoinHint.REPARTITION_SORT_MERGE)
  5. .where("id").equalTo("key");
  6. DataSet<Tuple2<SomeType, AnotherType> result2 =
  7. input1.rightOuterJoin(input2, JoinHint.BROADCAST_HASH_FIRST)
  8. .where("id").equalTo("key");
  1. val input1: DataSet[SomeType] = // [...]
  2. val input2: DataSet[AnotherType] = // [...]
  3. // hint that the second DataSet is very small
  4. val result1 = input1.leftOuterJoin(input2, JoinHint.REPARTITION_SORT_MERGE).where("id").equalTo("key")
  5. val result2 = input1.rightOuterJoin(input2, JoinHint.BROADCAST_HASH_FIRST).where("id").equalTo("key")
  1. Not supported.

以下提示可用。

  • OPTIMIZER_CHOOSES:相当于不提供任何提示,将选择留给系统。

  • BROADCAST_HASH_FIRST:广播第一个输入并从中构建哈希表,由第二个输入探测。如果第一个输入非常小,这是一个很好的策略。

  • BROADCAST_HASH_SECOND:广播第二个输入并从中构建哈希表,由第一个输入探测。如果第二个输入非常小,这是一个很好的策略。

  • REPARTITION_HASH_FIRST:系统分区(shuffle)每个输入(除非输入已经分区)并从第一个输入构建哈希表。如果第一个输入小于第二个输入,则此策略很好,但两个输入仍然很大。

  • REPARTITION_HASH_SECOND:系统分区(shuffle)每个输入(除非输入已经分区)并从第二个输入构建哈希表。如果第二个输入小于第一个输入,则此策略很好,但两个输入仍然很大。

  • REPARTITION_SORT_MERGE:系统对每个输入进行分区(shuffle)(除非输入已经分区)并对每个输入进行排序(除非它已经排序)。输入通过已排序输入的流合并来连接。如果已经对一个或两个输入进行了排序,则此策略很好。

注意:并非所有外部联接类型都支持所有执行策略。

  • LeftOuterJoin 支持:
    • OPTIMIZER_CHOOSES
    • BROADCAST_HASH_SECOND
    • REPARTITION_HASH_SECOND
    • REPARTITION_SORT_MERGE
  • RightOuterJoin 支持:
    • OPTIMIZER_CHOOSES
    • BROADCAST_HASH_FIRST
    • REPARTITION_HASH_FIRST
    • REPARTITION_SORT_MERGE
  • FullOuterJoin 支持:
    • OPTIMIZER_CHOOSES
    • REPARTITION_SORT_MERGE

交叉

交叉转换将两个DataSet组合到一个DataSet中。它构建了两个输入DataSet的数据元的所有成对组合,即它构建了一个笛卡尔积。交叉变换要么在每对数据元上调用用户定义的交叉函数,要么输出Tuple2。两种模式如下所示。

注:十字是一个潜在的非常计算密集型 算子操作它甚至可以挑战大的计算集群!

与用户定义的函数交叉

交叉转换可以调用用户定义的交叉函数。交叉函数接收第一个输入的一个数据元和第二个输入的一个数据元,并返回一个结果数据元。

以下代码显示如何使用交叉函数在两个DataSet上应用Cross转换:

  1. public class Coord {
  2. public int id;
  3. public int x;
  4. public int y;
  5. }
  6. // CrossFunction computes the Euclidean distance between two Coord objects.
  7. public class EuclideanDistComputer
  8. implements CrossFunction<Coord, Coord, Tuple3<Integer, Integer, Double>> {
  9. @Override
  10. public Tuple3<Integer, Integer, Double> cross(Coord c1, Coord c2) {
  11. // compute Euclidean distance of coordinates
  12. double dist = sqrt(pow(c1.x - c2.x, 2) + pow(c1.y - c2.y, 2));
  13. return new Tuple3<Integer, Integer, Double>(c1.id, c2.id, dist);
  14. }
  15. }
  16. DataSet<Coord> coords1 = // [...]
  17. DataSet<Coord> coords2 = // [...]
  18. DataSet<Tuple3<Integer, Integer, Double>>
  19. distances =
  20. coords1.cross(coords2)
  21. // apply CrossFunction
  22. .with(new EuclideanDistComputer());

与Projection交叉

交叉变换还可以使用Projection构造结果元组,如下所示:

  1. DataSet<Tuple3<Integer, Byte, String>> input1 = // [...]
  2. DataSet<Tuple2<Integer, Double>> input2 = // [...]
  3. DataSet<Tuple4<Integer, Byte, Integer, Double>
  4. result =
  5. input1.cross(input2)
  6. // select and reorder fields of matching tuples
  7. .projectSecond(0).projectFirst(1,0).projectSecond(1);

交叉Projection中的字段选择与连接结果的Projection中的工作方式相同。

  1. case class Coord(id: Int, x: Int, y: Int)
  2. val coords1: DataSet[Coord] = // [...]
  3. val coords2: DataSet[Coord] = // [...]
  4. val distances = coords1.cross(coords2) {
  5. (c1, c2) =>
  6. val dist = sqrt(pow(c1.x - c2.x, 2) + pow(c1.y - c2.y, 2))
  7. (c1.id, c2.id, dist)
  8. }
  1. class Euclid(CrossFunction):
  2. def cross(self, c1, c2):
  3. return (c1[0], c2[0], sqrt(pow(c1[1] - c2.[1], 2) + pow(c1[2] - c2[2], 2)))
  4. distances = coords1.cross(coords2).using(Euclid())

Cross with Projection

A Cross transformation can also construct result tuples using a projection as shown here:

  1. result = input1.cross(input2).projectFirst(1,0).projectSecond(0,1);

The field selection in a Cross projection works the same way as in the projection of Join results.

与DataSet大小提示交叉

为了引导优化器选择正确的执行策略,您可以提示要交叉的DataSet的大小,如下所示:

  1. DataSet<Tuple2<Integer, String>> input1 = // [...]
  2. DataSet<Tuple2<Integer, String>> input2 = // [...]
  3. DataSet<Tuple4<Integer, String, Integer, String>>
  4. udfResult =
  5. // hint that the second DataSet is very small
  6. input1.crossWithTiny(input2)
  7. // apply any Cross function (or projection)
  8. .with(new MyCrosser());
  9. DataSet<Tuple3<Integer, Integer, String>>
  10. projectResult =
  11. // hint that the second DataSet is very large
  12. input1.crossWithHuge(input2)
  13. // apply a projection (or any Cross function)
  14. .projectFirst(0,1).projectSecond(1);
  1. val input1: DataSet[(Int, String)] = // [...]
  2. val input2: DataSet[(Int, String)] = // [...]
  3. // hint that the second DataSet is very small
  4. val result1 = input1.crossWithTiny(input2)
  5. // hint that the second DataSet is very large
  6. val result1 = input1.crossWithHuge(input2)
  1. #hint that the second DataSet is very small
  2. result1 = input1.cross_with_tiny(input2)
  3. #hint that the second DataSet is very large
  4. result1 = input1.cross_with_huge(input2)

CoGroup

CoGroup转换共同处理两个DataSet的组。两个DataSet都在定义的Keys上分组,并且共享相同Keys的两个DataSet的组被一起交给用户定义的共同组函数。如果对于特定键,只有一个DataSet具有组,则使用该组和空组调用co-group函数。共同组函数可以单独迭代两个组的数据元并返回任意数量的结果数据元。

与Reduce,GroupReduce和Join类似,可以使用不同的键选择方法定义键。

DataSet上的CoGroup

该示例显示如何按字段位置键进行分组(仅限元组数据集)。您可以使用Pojo类型和键表达式执行相同的 算子操作。

  1. // Some CoGroupFunction definition
  2. class MyCoGrouper
  3. implements CoGroupFunction<Tuple2<String, Integer>, Tuple2<String, Double>, Double> {
  4. @Override
  5. public void coGroup(Iterable<Tuple2<String, Integer>> iVals,
  6. Iterable<Tuple2<String, Double>> dVals,
  7. Collector<Double> out) {
  8. Set<Integer> ints = new HashSet<Integer>();
  9. // add all Integer values in group to set
  10. for (Tuple2<String, Integer>> val : iVals) {
  11. ints.add(val.f1);
  12. }
  13. // multiply each Double value with each unique Integer values of group
  14. for (Tuple2<String, Double> val : dVals) {
  15. for (Integer i : ints) {
  16. out.collect(val.f1 * i);
  17. }
  18. }
  19. }
  20. }
  21. // [...]
  22. DataSet<Tuple2<String, Integer>> iVals = // [...]
  23. DataSet<Tuple2<String, Double>> dVals = // [...]
  24. DataSet<Double> output = iVals.coGroup(dVals)
  25. // group first DataSet on first tuple field
  26. .where(0)
  27. // group second DataSet on first tuple field
  28. .equalTo(0)
  29. // apply CoGroup function on each pair of groups
  30. .with(new MyCoGrouper());
  1. val iVals: DataSet[(String, Int)] = // [...]
  2. val dVals: DataSet[(String, Double)] = // [...]
  3. val output = iVals.coGroup(dVals).where(0).equalTo(0) {
  4. (iVals, dVals, out: Collector[Double]) =>
  5. val ints = iVals map { _._2 } toSet
  6. for (dVal <- dVals) {
  7. for (i <- ints) {
  8. out.collect(dVal._2 * i)
  9. }
  10. }
  11. }
  1. class CoGroup(CoGroupFunction):
  2. def co_group(self, ivals, dvals, collector):
  3. ints = dict()
  4. # add all Integer values in group to set
  5. for value in ivals:
  6. ints[value[1]] = 1
  7. # multiply each Double value with each unique Integer values of group
  8. for value in dvals:
  9. for i in ints.keys():
  10. collector.collect(value[1] * i)
  11. output = ivals.co_group(dvals).where(0).equal_to(0).using(CoGroup())

Union

生成两个DataSet的并集,它们必须属于同一类型。可以使用多个联合调用实现两个以上DataSet的并集,如下所示:

  1. DataSet<Tuple2<String, Integer>> vals1 = // [...]
  2. DataSet<Tuple2<String, Integer>> vals2 = // [...]
  3. DataSet<Tuple2<String, Integer>> vals3 = // [...]
  4. DataSet<Tuple2<String, Integer>> unioned = vals1.union(vals2).union(vals3);
  1. val vals1: DataSet[(String, Int)] = // [...]
  2. val vals2: DataSet[(String, Int)] = // [...]
  3. val vals3: DataSet[(String, Int)] = // [...]
  4. val unioned = vals1.union(vals2).union(vals3)
  1. unioned = vals1.union(vals2).union(vals3)

Rebalance

均匀地Rebalance DataSet的并行分区以消除数据偏斜。

  1. DataSet<String> in = // [...]
  2. // rebalance DataSet and apply a Map transformation.
  3. DataSet<Tuple2<String, String>> out = in.rebalance()
  4. .map(new Mapper());
  1. val in: DataSet[String] = // [...]
  2. // rebalance DataSet and apply a Map transformation.
  3. val out = in.rebalance().map { ... }
  1. Not supported.

Hash-Partition

散列分区给定键上的DataSet。键可以指定为位置键,表达式键和键选择器函数(有关如何指定键,请参阅Reduce示例)。

  1. DataSet<Tuple2<String, Integer>> in = // [...]
  2. // hash-partition DataSet by String value and apply a MapPartition transformation.
  3. DataSet<Tuple2<String, String>> out = in.partitionByHash(0)
  4. .mapPartition(new PartitionMapper());
  1. val in: DataSet[(String, Int)] = // [...]
  2. // hash-partition DataSet by String value and apply a MapPartition transformation.
  3. val out = in.partitionByHash(0).mapPartition { ... }
  1. Not supported.

Range-Partition

对给定键的DataSet进行Range-Partition。键可以指定为位置键,表达式键和键选择器函数(有关如何指定键,请参阅Reduce示例)。

  1. DataSet<Tuple2<String, Integer>> in = // [...]
  2. // range-partition DataSet by String value and apply a MapPartition transformation.
  3. DataSet<Tuple2<String, String>> out = in.partitionByRange(0)
  4. .mapPartition(new PartitionMapper());
  1. val in: DataSet[(String, Int)] = // [...]
  2. // range-partition DataSet by String value and apply a MapPartition transformation.
  3. val out = in.partitionByRange(0).mapPartition { ... }
  1. Not supported.

Sort Partition

本地按指定顺序对指定字段上的DataSet的所有分区进行排序。可以将字段指定为字段表达式或字段位置(有关如何指定键,请参阅Reduce示例)。可以通过链接sortPartition()调用在多个字段上对分区进行排序

  1. DataSet<Tuple2<String, Integer>> in = // [...]
  2. // Locally sort partitions in ascending order on the second String field and
  3. // in descending order on the first String field.
  4. // Apply a MapPartition transformation on the sorted partitions.
  5. DataSet<Tuple2<String, String>> out = in.sortPartition(1, Order.ASCENDING)
  6. .sortPartition(0, Order.DESCENDING)
  7. .mapPartition(new PartitionMapper());
  1. val in: DataSet[(String, Int)] = // [...]
  2. // Locally sort partitions in ascending order on the second String field and
  3. // in descending order on the first String field.
  4. // Apply a MapPartition transformation on the sorted partitions.
  5. val out = in.sortPartition(1, Order.ASCENDING)
  6. .sortPartition(0, Order.DESCENDING)
  7. .mapPartition { ... }
  1. Not supported.

First-n

返回DataSet的前n个(任意)数据元。First-n可以应用于常规DataSet,分组DataSet或分组排序DataSet。可以将分组键指定为键选择器函数或字段位置键(有关如何指定键,请参阅Reduce示例)。

  1. DataSet<Tuple2<String, Integer>> in = // [...]
  2. // Return the first five (arbitrary) elements of the DataSet
  3. DataSet<Tuple2<String, Integer>> out1 = in.first(5);
  4. // Return the first two (arbitrary) elements of each String group
  5. DataSet<Tuple2<String, Integer>> out2 = in.groupBy(0)
  6. .first(2);
  7. // Return the first three elements of each String group ordered by the Integer field
  8. DataSet<Tuple2<String, Integer>> out3 = in.groupBy(0)
  9. .sortGroup(1, Order.ASCENDING)
  10. .first(3);
  1. val in: DataSet[(String, Int)] = // [...]
  2. // Return the first five (arbitrary) elements of the DataSet
  3. val out1 = in.first(5)
  4. // Return the first two (arbitrary) elements of each String group
  5. val out2 = in.groupBy(0).first(2)
  6. // Return the first three elements of each String group ordered by the Integer field
  7. val out3 = in.groupBy(0).sortGroup(1, Order.ASCENDING).first(3)
  1. Not supported.