我有一个数据集,我将从文件中读取,
1 2 3 4 5:9:3 2 1 2 1
2 3 5:4:1 2 1
4 5:3:1 2
我正在尝试将这些分割为每一行,然后使用colon
的左侧部分和colon
的相应右侧部分创建一个键/值。例如,在第一行中,1
与3
映射为(1,3)
,2
与2
映射为(2,2)
。同样,第一行会有(3,1), (4,2), (5,1)
。同样,它应该为第二行和第三行生成。
到目前为止,我尝试使用map函数拆分每一行,然后尝试通过将每个左侧部分项目与相应的右侧部分值进行映射来创建元组。
到目前为止代码:
JavaRDD<List<String>> transactions = data.map(
new Function<String, List<String>>() {
public List<String> call(String line) {
String[] parts = line.split(" ");
return Arrays.asList(parts);
}
}
);
JavaPairRDD<String, Integer> ones = transactions.mapToPair(
new PairFunction<List<String>, String, Integer>() {
public Tuple2<String, Integer> call(List<String> w) {
return new Tuple2<String, Integer>....;
}
});
我对返回部分感到震惊。有没有办法获得所有的键/值对?
PS:我是apache spark的新手。
答案 0 :(得分:1)
您可以使用flatmap获得相对更优雅的解决方案:
val res = dataset.flatMap(line => {
val f = line.split(":", -1) //taking care of the empty values with -1
val keys = f(0).split(" ", -1)
val values = f(2).split(" ", -1)
keys.zip(values) //List[(String, String)], (key, value) pairs for a line
})
res.collect.map(println)
(1,3)
(2,2)
(3,1)
(4,2)
(5,1)
(2,1)
(3,2)
(5,1)
(4,1)
(5,2)