DataSet Transformations

This document gives a deep-dive into the available transformations on DataSets. For a general introduction to the Flink Java API, please refer to the Programming Guide.

For zipping elements in a data set with a dense index, please refer to the Zip Elements Guide.

Map

The Map transformation applies a user-defined map function on each element of a DataSet. It implements a one-to-one mapping, that is, exactly one element must be returned by the function.

The following code transforms a DataSet of Integer pairs into a DataSet of Integers:

  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 }

FlatMap

The FlatMap transformation applies a user-defined flat-map function on each element of a DataSet. This variant of a map function can return arbitrary many result elements (including none) for each input element.

The following code transforms a DataSet of text lines into a DataSet of words:

  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(" ") }

MapPartition

MapPartition transforms a parallel partition in a single function call. The map-partition function gets the partition as Iterable and can produce an arbitrary number of result values. The number of elements in each partition depends on the degree-of-parallelism and previous operations.

The following code transforms a DataSet of text lines into a DataSet of counts per partition:

  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) }

Filter

The Filter transformation applies a user-defined filter function on each element of a DataSet and retains only those elements for which the function returns true.

The following code removes all Integers smaller than zero from a 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 }

IMPORTANT: The system assumes that the function does not modify the elements on which the predicate is applied. Violating this assumption can lead to incorrect results.

Projection of Tuple DataSet

The Project transformation removes or moves Tuple fields of a Tuple DataSet. The project(int...) method selects Tuple fields that should be retained by their index and defines their order in the output Tuple.

Projections do not require the definition of a user function.

The following code shows different ways to apply a Project transformation on a 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 with Type Hint

Note that the Java compiler cannot infer the return type of project operator. This can cause a problem if you call another operator on a result of project operator such as:

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

This problem can be overcome by hinting the return type of project operator like this:

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

Transformations on Grouped DataSet

The reduce operations can operate on grouped data sets. Specifying the key to be used for grouping can be done in many ways:

  • key expressions
  • a key-selector function
  • one or more field position keys (Tuple DataSet only)
  • Case Class fields (Case Classes only)

Please look at the reduce examples to see how the grouping keys are specified.

Reduce on Grouped DataSet

A Reduce transformation that is applied on a grouped DataSet reduces each group to a single element using a user-defined reduce function. For each group of input elements, a reduce function successively combines pairs of elements into one element until only a single element for each group remains.

Note that for a ReduceFunction the keyed fields of the returned object should match the input values. This is because reduce is implicitly combinable and objects emitted from the combine operator are again grouped by key when passed to the reduce operator.

Reduce on DataSet Grouped by Key Expression

Key expressions specify one or more fields of each element of a DataSet. Each key expression is either the name of a public field or a getter method. A dot can be used to drill down into objects. The key expression “*” selects all fields. The following code shows how to group a POJO DataSet using key expressions and to reduce it with a reduce function.

  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. }

Reduce on DataSet Grouped by KeySelector Function

A key-selector function extracts a key value from each element of a DataSet. The extracted key value is used to group the DataSet. The following code shows how to group a POJO DataSet using a key-selector function and to reduce it with a reduce function.

  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. }

Reduce on DataSet Grouped by Field Position Keys (Tuple DataSets only)

Field position keys specify one or more fields of a Tuple DataSet that are used as grouping keys. The following code shows how to use field position keys and apply a reduce function

  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 { ... }

Reduce on DataSet grouped by Case Class Fields

When using Case Classes you can also specify the grouping key using the names of the fields:

  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 { ... }

GroupReduce on Grouped DataSet

A GroupReduce transformation that is applied on a grouped DataSet calls a user-defined group-reduce function for each group. The difference between this and Reduce is that the user defined function gets the whole group at once. The function is invoked with an Iterable over all elements of a group and can return an arbitrary number of result elements.

GroupReduce on DataSet Grouped by Field Position Keys (Tuple DataSets only)

The following code shows how duplicate strings can be removed from a DataSet grouped by Integer.

  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. }

GroupReduce on DataSet Grouped by Key Expression, KeySelector Function, or Case Class Fields

Work analogous to key expressions, key-selector functions, and case class fields in Reduce transformations.

GroupReduce on sorted groups

A group-reduce function accesses the elements of a group using an Iterable. Optionally, the Iterable can hand out the elements of a group in a specified order. In many cases this can help to reduce the complexity of a user-defined group-reduce function and improve its efficiency.

The following code shows another example how to remove duplicate Strings in a DataSet grouped by an Integer and sorted by String.

  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 (comp == 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. }

Note: A GroupSort often comes for free if the grouping is established using a sort-based execution strategy of an operator before the reduce operation.

Combinable GroupReduceFunctions

In contrast to a reduce function, a group-reduce function is not implicitly combinable. In order to make a group-reduce function combinable it must implement the GroupCombineFunction interface.

Important: The generic input and output types of the GroupCombineFunction interface must be equal to the generic input type of the GroupReduceFunction as shown in the following example:

  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.iterator.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.iterator.asScala.reduce( (a,b) => (a._1, a._2 + b._2) )
  21. // emit tuple with key and sum
  22. out.collect(r)
  23. }
  24. }

GroupCombine on a Grouped DataSet

The GroupCombine transformation is the generalized form of the combine step in the combinable GroupReduceFunction. It is generalized in the sense that it allows combining of input type I to an arbitrary output type O. In contrast, the combine step in the GroupReduce only allows combining from input type I to output type I. This is because the reduce step in the GroupReduceFunction expects input type I.

In some applications, it is desirable to combine a DataSet into an intermediate format before performing additional transformations (e.g. to reduce data size). This can be achieved with a CombineGroup transformation with very little costs.

Note: The GroupCombine on a Grouped DataSet is performed in memory with a greedy strategy which may not process all data at once but in multiple steps. It is also performed on the individual partitions without a data exchange like in a GroupReduce transformation. This may lead to partial results.

The following example demonstrates the use of a CombineGroup transformation for an alternative WordCount implementation.

  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. }

The above alternative WordCount implementation demonstrates how the GroupCombine combines words before performing the GroupReduce transformation. The above example is just a proof of concept. Note, how the combine step changes the type of the DataSet which would normally require an additional Map transformation before executing the GroupReduce.

Aggregate on Grouped Tuple DataSet

There are some common aggregation operations that are frequently used. The Aggregate transformation provides the following build-in aggregation functions:

  • Sum,
  • Min, and
  • Max.

The Aggregate transformation can only be applied on a Tuple DataSet and supports only field position keys for grouping.

The following code shows how to apply an Aggregation transformation on a DataSet grouped by field position keys:

  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)

To apply multiple aggregations on a DataSet it is necessary to use the .and() function after the first aggregate, that means .aggregate(SUM, 0).and(MIN, 2) produces the sum of field 0 and the minimum of field 2 of the original DataSet. In contrast to that .aggregate(SUM, 0).aggregate(MIN, 2) will apply an aggregation on an aggregation. In the given example it would produce the minimum of field 2 after calculating the sum of field 0 grouped by field 1.

Note: The set of aggregation functions will be extended in the future.

MinBy / MaxBy on Grouped Tuple DataSet

The MinBy (MaxBy) transformation selects a single tuple for each group of tuples. The selected tuple is the tuple whose values of one or more specified fields are minimum (maximum). The fields which are used for comparison must be valid key fields, i.e., comparable. If multiple tuples have minimum (maximum) fields values, an arbitrary tuple of these tuples is returned.

The following code shows how to select the tuple with the minimum values for the Integer and Double fields for each group of tuples with the same String value from a DataSet<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.

Reduce on full DataSet

The Reduce transformation applies a user-defined reduce function to all elements of a DataSet. The reduce function subsequently combines pairs of elements into one element until only a single element remains.

The following code shows how to sum all elements of an 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 (_ + _)

Reducing a full DataSet using the Reduce transformation implies that the final Reduce operation cannot be done in parallel. However, a reduce function is automatically combinable such that a Reduce transformation does not limit scalability for most use cases.

GroupReduce on full DataSet

The GroupReduce transformation applies a user-defined group-reduce function on all elements of a DataSet. A group-reduce can iterate over all elements of DataSet and return an arbitrary number of result elements.

The following example shows how to apply a GroupReduce transformation on a full DataSet:

  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())

Note: A GroupReduce transformation on a full DataSet cannot be done in parallel if the group-reduce function is not combinable. Therefore, this can be a very compute intensive operation. See the paragraph on “Combinable GroupReduceFunctions” above to learn how to implement a combinable group-reduce function.

GroupCombine on a full DataSet

The GroupCombine on a full DataSet works similar to the GroupCombine on a grouped DataSet. The data is partitioned on all nodes and then combined in a greedy fashion (i.e. only data fitting into memory is combined at once).

Aggregate on full Tuple DataSet

There are some common aggregation operations that are frequently used. The Aggregate transformation provides the following build-in aggregation functions:

  • Sum,
  • Min, and
  • Max.

The Aggregate transformation can only be applied on a Tuple DataSet.

The following code shows how to apply an Aggregation transformation on a full 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)

Note: Extending the set of supported aggregation functions is on our roadmap.

MinBy / MaxBy on full Tuple DataSet

The MinBy (MaxBy) transformation selects a single tuple from a DataSet of tuples. The selected tuple is the tuple whose values of one or more specified fields are minimum (maximum). The fields which are used for comparison must be valid key fields, i.e., comparable. If multiple tuples have minimum (maximum) fields values, an arbitrary tuple of these tuples is returned.

The following code shows how to select the tuple with the maximum values for the Integer and Double fields from a 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.

Distinct

The Distinct transformation computes the DataSet of the distinct elements of the source DataSet. The following code removes all duplicate elements from the 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()

It is also possible to change how the distinction of the elements in the DataSet is decided, using:

  • one or more field position keys (Tuple DataSets only),
  • a key-selector function, or
  • a key expression.

Distinct with field position keys

  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)

Distinct with KeySelector function

  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)}

Distinct with key expression

  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")

It is also possible to indicate to use all the fields by the wildcard character:

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

Join

The Join transformation joins two DataSets into one DataSet. The elements of both DataSets are joined on one or more keys which can be specified using

  • a key expression
  • a key-selector function
  • one or more field position keys (Tuple DataSet only).
  • Case Class Fields

There are a few different ways to perform a Join transformation which are shown in the following.

Default Join (Join into Tuple2)

The default Join transformation produces a new Tuple DataSet with two fields. Each tuple holds a joined element of the first input DataSet in the first tuple field and a matching element of the second input DataSet in the second field.

The following code shows a default Join transformation using field position keys:

  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)

Join with Join Function

A Join transformation can also call a user-defined join function to process joining tuples. A join function receives one element of the first input DataSet and one element of the second input DataSet and returns exactly one element.

The following code performs a join of DataSet with custom java objects and a Tuple DataSet using key-selector functions and shows how to use a user-defined join function:

  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. }

Join with Flat-Join Function

Analogous to Map and FlatMap, a FlatJoin behaves in the same way as a Join, but instead of returning one element, it can return (collect), zero, one, or more elements.

  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. }

Join with Projection (Java Only)

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

  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...) and projectSecond(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, projectFirst() or projectSecond() must be called without arguments to add a joined element to the output Tuple.

  1. Not supported.

Join with DataSet Size Hint

In order to guide the optimizer to pick the right execution strategy, you can hint the size of a DataSet to join as shown here:

  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)

Join Algorithm Hints

The Flink runtime can execute joins in various ways. Each possible way outperforms the others under different circumstances. The system tries to pick a reasonable way automatically, but allows you to manually pick a strategy, in case you want to enforce a specific way of executing the join.

  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")

The following hints are available:

  • OPTIMIZER_CHOOSES: Equivalent to not giving a hint at all, leaves the choice to the system.

  • BROADCAST_HASH_FIRST: Broadcasts the first input and builds a hash table from it, which is probed by the second input. A good strategy if the first input is very small.

  • BROADCAST_HASH_SECOND: Broadcasts the second input and builds a hash table from it, which is probed by the first input. A good strategy if the second input is very small.

  • REPARTITION_HASH_FIRST: The system partitions (shuffles) each input (unless the input is already partitioned) and builds a hash table from the first input. This strategy is good if the first input is smaller than the second, but both inputs are still large. Note: This is the default fallback strategy that the system uses if no size estimates can be made and no pre-existing partitions and sort-orders can be re-used.

  • REPARTITION_HASH_SECOND: The system partitions (shuffles) each input (unless the input is already partitioned) and builds a hash table from the second input. This strategy is good if the second input is smaller than the first, but both inputs are still large.

  • REPARTITION_SORT_MERGE: The system partitions (shuffles) each input (unless the input is already partitioned) and sorts each input (unless it is already sorted). The inputs are joined by a streamed merge of the sorted inputs. This strategy is good if one or both of the inputs are already sorted.

OuterJoin

The OuterJoin transformation performs a left, right, or full outer join on two data sets. Outer joins are similar to regular (inner) joins and create all pairs of elements that are equal on their keys. In addition, records of the “outer” side (left, right, or both in case of full) are preserved if no matching key is found in the other side. Matching pair of elements (or one element and a null value for the other input) are given to a JoinFunction to turn the pair of elements into a single element, or to a FlatJoinFunction to turn the pair of elements into arbitrarily many (including none) elements.

The elements of both DataSets are joined on one or more keys which can be specified using

  • a key expression
  • a key-selector function
  • one or more field position keys (Tuple DataSet only).
  • Case Class Fields

OuterJoins are only supported for the Java and Scala DataSet API.

OuterJoin with Join Function

A OuterJoin transformation calls a user-defined join function to process joining tuples. A join function receives one element of the first input DataSet and one element of the second input DataSet and returns exactly one element. Depending on the type of the outer join (left, right, full) one of both input elements of the join function can be null.

The following code performs a left outer join of DataSet with custom java objects and a Tuple DataSet using key-selector functions and shows how to use a user-defined join function:

  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. }

OuterJoin with Flat-Join Function

Analogous to Map and FlatMap, an OuterJoin with flat-join function behaves in the same way as an OuterJoin with join function, but instead of returning one element, it can return (collect), zero, one, or more elements.

  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.

Join Algorithm Hints

The Flink runtime can execute outer joins in various ways. Each possible way outperforms the others under different circumstances. The system tries to pick a reasonable way automatically, but allows you to manually pick a strategy, in case you want to enforce a specific way of executing the outer join.

  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")

The following hints are available.

  • OPTIMIZER_CHOOSES: Equivalent to not giving a hint at all, leaves the choice to the system.

  • BROADCAST_HASH_FIRST: Broadcasts the first input and builds a hash table from it, which is probed by the second input. A good strategy if the first input is very small.

  • BROADCAST_HASH_SECOND: Broadcasts the second input and builds a hash table from it, which is probed by the first input. A good strategy if the second input is very small.

  • REPARTITION_HASH_FIRST: The system partitions (shuffles) each input (unless the input is already partitioned) and builds a hash table from the first input. This strategy is good if the first input is smaller than the second, but both inputs are still large.

  • REPARTITION_HASH_SECOND: The system partitions (shuffles) each input (unless the input is already partitioned) and builds a hash table from the second input. This strategy is good if the second input is smaller than the first, but both inputs are still large.

  • REPARTITION_SORT_MERGE: The system partitions (shuffles) each input (unless the input is already partitioned) and sorts each input (unless it is already sorted). The inputs are joined by a streamed merge of the sorted inputs. This strategy is good if one or both of the inputs are already sorted.

NOTE: Not all execution strategies are supported by every outer join type, yet.

  • LeftOuterJoin supports:
    • OPTIMIZER_CHOOSES
    • BROADCAST_HASH_SECOND
    • REPARTITION_HASH_SECOND
    • REPARTITION_SORT_MERGE
  • RightOuterJoin supports:
    • OPTIMIZER_CHOOSES
    • BROADCAST_HASH_FIRST
    • REPARTITION_HASH_FIRST
    • REPARTITION_SORT_MERGE
  • FullOuterJoin supports:
    • OPTIMIZER_CHOOSES
    • REPARTITION_SORT_MERGE

Cross

The Cross transformation combines two DataSets into one DataSet. It builds all pairwise combinations of the elements of both input DataSets, i.e., it builds a Cartesian product. The Cross transformation either calls a user-defined cross function on each pair of elements or outputs a Tuple2. Both modes are shown in the following.

Note: Cross is potentially a very compute-intensive operation which can challenge even large compute clusters!

Cross with User-Defined Function

A Cross transformation can call a user-defined cross function. A cross function receives one element of the first input and one element of the second input and returns exactly one result element.

The following code shows how to apply a Cross transformation on two DataSets using a cross function:

  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());

Cross with Projection

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

  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);

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

  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. }

Cross with DataSet Size Hint

In order to guide the optimizer to pick the right execution strategy, you can hint the size of a DataSet to cross as shown here:

  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)

CoGroup

The CoGroup transformation jointly processes groups of two DataSets. Both DataSets are grouped on a defined key and groups of both DataSets that share the same key are handed together to a user-defined co-group function. If for a specific key only one DataSet has a group, the co-group function is called with this group and an empty group. A co-group function can separately iterate over the elements of both groups and return an arbitrary number of result elements.

Similar to Reduce, GroupReduce, and Join, keys can be defined using the different key-selection methods.

CoGroup on DataSets

The example shows how to group by Field Position Keys (Tuple DataSets only). You can do the same with Pojo-types and key expressions.

  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. }

Union

Produces the union of two DataSets, which have to be of the same type. A union of more than two DataSets can be implemented with multiple union calls, as shown here:

  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)

Rebalance

Evenly rebalances the parallel partitions of a DataSet to eliminate data skew.

  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 { ... }

Hash-Partition

Hash-partitions a DataSet on a given key. Keys can be specified as position keys, expression keys, and key selector functions (see Reduce examples for how to specify keys).

  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 { ... }

Range-Partition

Range-partitions a DataSet on a given key. Keys can be specified as position keys, expression keys, and key selector functions (see Reduce examples for how to specify keys).

  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 { ... }

Sort Partition

Locally sorts all partitions of a DataSet on a specified field in a specified order. Fields can be specified as field expressions or field positions (see Reduce examples for how to specify keys). Partitions can be sorted on multiple fields by chaining sortPartition() calls.

  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 { ... }

First-n

Returns the first n (arbitrary) elements of a DataSet. First-n can be applied on a regular DataSet, a grouped DataSet, or a grouped-sorted DataSet. Grouping keys can be specified as key-selector functions or field position keys (see Reduce examples for how to specify keys).

  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)