简体   繁体   English

Spark:RDD.map/mapToPair如何与Java配合使用

[英]Spark: How RDD.map/mapToPair work with Java

I have some pairs cw (Integer i, String word) with i number of occurences of word in a text file. 我有一些对cw(整数i,字符串词)和i个文本文件中出现的词的对。

I would like to simply have for each pair a new pair c1 (Integer i, 1) with 1 fixed number. 我只想为每对具有1个固定数字的新对c1(整数i,1)。

It seems to be really trivial but I haven't understood how map/mapToPair functions actually work. 看起来确实很琐碎,但我还不了解map / mapToPair函数的实际工作方式。

JavaPairRDD<Integer, Integer> c1 = cw.map(??? -> new Tuple2<Integer, Integer>(??, 1));

I am working using Java-8. 我正在使用Java-8。

If I understand you correctly, you have below JavaPairRDD. 如果我对您的理解正确,那么您在JavaPairRDD之下。

JavaPairRDD<Integer, String> cw = ...;

Now you want to create below JavaPairRDD where second value is 1. 现在,您要在JavaPairRDD下面创建第二个值为1的值。

JavaPairRDD<Integer, Integer> c1;

In order to get this, first you have to extract JavaRDD from cw JavaPairRDD and for this you will have to call map function like below. 为了做到这一点,首先您必须从cw JavaPairRDD中提取JavaRDD,为此,您必须调用如下的map函数。 We will extract first value from pair. 我们将从配对中提取第一个值。

JavaRDD<Integer> cw1 = cw.map(tuple -> tuple._1());

Now you will create new JavaPairRDD from JavaRDD using mapToPair function like below. 现在,您将使用如下所示的mapToPair函数从JavaRDD创建新的JavaPairRDD。

JavaPairRDD<Integer, Integer> c1 = cw1.mapToPair(i -> new Tuple2<Integer, Integer>(i, 1));

In single line you can write it like 在单行中,您可以像这样写

JavaPairRDD<Integer, Integer> c1 = cw.map(tuple -> tuple._1()).mapToPair(i -> new Tuple2<Integer, Integer>(i, 1));

This is what you can try: 您可以尝试以下方法:

JavaPairRDD<Integer, Integer> tuples = filtered.mapToPair(
                                            f -> new Tuple2<Integer, Integer>(
                                                       Integer.parseInt(f[0]), 
                                                       Integer.parseInt(f[1])
                                       ));

Simply ... cw.mapValues(v -> 1); 简单地... cw.mapValues(v -> 1);

From the api docs for JavaPairRDD.mapValues() ... Java文档的JavaPairRDD.mapValues() ...

Pass each value in the key-value pair RDD through a map function without changing the keys; 通过映射函数传递键-值对RDD中的每个值,而无需更改键; this also retains the original RDD's partitioning. 这也保留了原始RDD的分区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM