Transforming data in Spark

The core ability of Spark is to operate on data that is distributed in the cluster (RDDs aka Resilient Distributed Datasets). In this post I am giving a reference of the available transformations you can use along with some examples.

Maps

map(func)

Return a new distributed dataset formed by passing each element of the source through a function func.

1
2
3
4
5
List<List<Integer>> map = sc.parallelize(Arrays.asList(1,2,3,4,5)).map(i->Arrays.asList(i,1)).collect();
System.out.println(map.toString());

Output:
[[1, 1], [2, 1], [3, 1], [4, 1], [5, 1]]

flatMap(func)

Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).

1
2
3
4
5
List<Integer> flatMap = sc.parallelize(Arrays.asList(1,2,3,4,5)).flatMap(i->Arrays.asList(i,1)).collect();
System.out.println(flatMap.toString());

Output:
[1, 1, 2, 1, 3, 1, 4, 1, 5, 1]

mapToPair, flatMapToPair

There are also variants of map and flatMap that returns a pairs (tuples). In Java the implementation we can use is Tuple2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Input
(chinese,[(chinese,2), (chinese,1), (chinese,3), (chinese,4)])
(japan,[(japan,4)])
(beijing,[(beijing,1)])
(shanghai,[(shanghai,2)])
(tokyo,[(tokyo,4)])
(macao,[(macao,3)])

.mapToPair(t -> {
    Integer i = 0;
    for(Tuple2<String,Integer> it : t._2()){
        i++;
    }
    return new Tuple2<String, Integer>(t._1(), i);
});

Output
(chinese,4)
(japan,1)
(beijing,1)
(shanghai,1)
(tokyo,1)
(macao,1)

mapPartitions(func)

Similar to map, but runs separately on each partition (block) of the RDD, so func must be of type

1
Iterator<T> => Iterator<U>

when running on an RDD of type T.

mapPartitionsWithIndex(func)

Similar to mapPartitions, but also provides func with an integer value representing the index of the partition, so func must be of type

1
(Int, Iterator<T>) => Iterator<U>

when running on an RDD of type T.

SQL-like methods

Transformation with an obvious connotation with SQL

filter(func)

Return a new dataset formed by selecting those elements of the source on which func returns true.
… it is like a WHERE clause

1
2
3
List<Integer> filter = sc.parallelize(Arrays.asList(1,2,3,4,5)).filter(i->i>2).collect();

Output: [3, 4, 5]

union(otherDataset)

Return a new dataset that contains the union of the elements in the source dataset and the argument.

1
2
3
4
5
JavaRDD<Integer> s1 = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5));
List<Integer> union = sc.parallelize(Arrays.asList(11,12,13,14,15)).union(s1).collect();
System.out.println(union.toString());

Output: [11, 12, 13, 14, 15, 1, 2, 3, 4, 5]

intersection(otherDataset)

Return a new RDD that contains the intersection of elements in the source dataset and the argument.

1
2
3
4
5
JavaRDD<Integer> s1 = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5));
List<Integer> intersection = sc.parallelize(Arrays.asList(11,2,13,4,15)).intersection(s1).collect();
System.out.println(intersection.toString());

Output: [4, 2]

distinct([numTasks]))

Return a new dataset that contains the distinct elements of the source dataset.
It will remove redundancy leaving only the distinct elements of the source dataset. Note that when using tuples it will leave a distinct tuples and not the keys

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Input:
(chinese,1) // -> Tuple2<String,Integer>
(beijing,1)
(chinese,1)
(chinese,2)
(chinese,2)
(shanghai,2)
(chinese,3)
(macao,3)
(tokyo,4)
(japan,4)

.distinct()

Output:
(macao,3)
(japan,4)
(beijing,1)
(shanghai,2)
(chinese,2) // !
(chinese,1) // !
(chinese,3) // !
(chinese,4) // !
(tokyo,4)

Grouping, aggregating and sorting

groupBy(func)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Input:
(macao,3)
(japan,4)
(beijing,1)
(shanghai,2)
(chinese,2)
(chinese,1)
(chinese,3)
(chinese,4)
(tokyo,4)

.groupBy(t -> t._1())

Output:
(chinese,[(chinese,2), (chinese,1), (chinese,3), (chinese,4)])
(japan,[(japan,4)])
(beijing,[(beijing,1)])
(shanghai,[(shanghai,2)])
(tokyo,[(tokyo,4)])
(macao,[(macao,3)])

If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduceByKey or aggregateByKey will yield much better performance:
https://databricks.gitbooks.io/databricks-spark-knowledge-base/content/best_practices/prefer_reducebykey_over_groupbykey.html
The *ByKey operations works on a K-V pairs

groupByKey([numTasks])

When called on a dataset of (K, V) pairs, returns a dataset of (K, Iterable) pairs.
Note: By default, the level of parallelism in the output depends on the number of partitions of the parent RDD. You can pass an optional numTasks argument to set a different number of tasks.

reduceByKey(func, [numTasks])

When called on a dataset of (K, V) pairs, returns a dataset of (K, V) pairs where the values for each key are aggregated using the given reduce function func, which must be of type (V,V) => V. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.

aggregateByKey(zeroValue)(seqOp, combOp, [numTasks])

When called on a dataset of (K, V) pairs, returns a dataset of (K, U) pairs where the values for each key are aggregated using the given combine functions and a neutral “zero” value. Allows an aggregated value type that is different than the input value type, while avoiding unnecessary allocations. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.

sortByKey([ascending], [numTasks])

When called on a dataset of (K, V) pairs where K implements Ordered, returns a dataset of (K, V) pairs sorted by keys in ascending or descending order, as specified in the boolean ascending argument.

Joins

join(otherDataset, [numTasks])

When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (V, W)) pairs with all pairs of elements for each key. Outer joins are supported through leftOuterJoin, rightOuterJoin, and fullOuterJoin.

Others

sample(withReplacement, fraction, seed)

Sample a fraction fraction of the data, with or without replacement, using a given random number generator seed.

1
2
3
List<Integer> sample = sc.parallelize(Arrays.asList(1,2,3,4,5)).sample(true, 0.3).collect();

Output: [2, 3]

cogroup(otherDataset, [numTasks])

When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (Iterable, Iterable)) tuples. This operation is also called groupWith.

cartesian(otherDataset)

When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements).

pipe(command, [envVars])

Pipe each partition of the RDD through a shell command, e.g. a Perl or bash script. RDD elements are written to the process’s stdin and lines output to its stdout are returned as an RDD of strings.

coalesce(numPartitions)

Decrease the number of partitions in the RDD to numPartitions. Useful for running operations more efficiently after filtering down a large dataset.

repartition(numPartitions)

Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them. This always shuffles all data over the network.

repartitionAndSortWithinPartitions(partitioner)

Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their keys. This is more efficient than calling repartition and then sorting within each partition because it can push the sorting down into the shuffle machinery.

Official docs: http://spark.apache.org/docs/latest/programming-guide.html#transformations

Leave a Reply