What is the right JavaRDD transformation to cluster rows on disjoint sets

120 Views Asked by At

I have my rows setup in the JavaPairRDD<String, MyPojo> where MyPojo is a pojo with an attribute (let's call it HashSet<String> values).

Now I want to cluster (merge) my rows based on any intersection with MyPojo.values.

For example:

<Row K1 : MyPojo (values: [A,B,C])>

<Row K2 : MyPojo (values: [A,B])>

<Row K3 : MyPojo (values: [D,E,F])>

I want to merge the rows with keys K1, K2.

1

There are 1 best solutions below

0
On

If keys with values intersection have to be found, such approach can be used:

    List<Tuple2<String, MyPojo>> data = Lists.newArrayList(
            new Tuple2("K1", new MyPojo("A", "B", "C")),
            new Tuple2("K2", new MyPojo("A", "B")),
            new Tuple2("K3", new MyPojo("D", "E", "F")));
    JavaPairRDD<String, MyPojo> original = jsc().parallelizePairs(data);

    JavaPairRDD<String, String> preparedToJoin = original.flatMapToPair(
            v ->
                    v._2().getValues().stream().map(
                            s -> new Tuple2<String, String>(s, v._1()))
                            .collect(Collectors.toList()).iterator()
    );

    preparedToJoin.join(preparedToJoin)
            .filter(v -> !v._2()._1().equals(v._2()._2()))
             // remove one of: (K1,K2), (K2,K1)
            .filter(v -> v._2()._1().compareTo(v._2()._2()) <= 0)
            .values()
            .distinct().foreach(v -> System.out.println(v));

Output is:

(K1,K2)