我使用以下命令用一堆包含2个字符串"filename“、"content”的数组填充RDD。
现在,我想遍历所有这些事件,对每个文件名和内容做一些处理。
val someRDD = sc.wholeTextFiles("hdfs://localhost:8020/user/cloudera/*")
然而,我似乎找不到任何关于如何做到这一点的文档。
所以我想要的是:
foreach occurrence-in-the-rdd{
//do stuff with the array found on loccation n of the RDD
}
发布于 2014-09-19 01:54:07
Spark中的基本操作是map
和filter
。
val txtRDD = someRDD filter { case(id, content) => id.endsWith(".txt") }
txtRDD
现在将只包含扩展名为".txt“的文件
如果你想计算这些文件的字数,你可以说
//split the documents into words in one long list
val words = txtRDD flatMap { case (id,text) => text.split("\\s+") }
// give each word a count of 1
val wordT = words map (x => (x,1))
//sum up the counts for each word
val wordCount = wordsT reduceByKey((a, b) => a + b)
当您有一些昂贵的初始化需要执行时,您希望使用mapPartitions
--例如,如果您希望使用像斯坦福coreNLP工具这样的库进行命名实体识别。
掌握map
、filter
、flatMap
和reduce
,您就可以很好地掌握Spark。
发布于 2018-06-13 23:08:28
for (element <- YourRDD)
{
// do what you want with element in each iteration, and if you want the index of element, simply use a counter variable in this loop beginning from 0
println (element._1) // this will print all filenames
}
https://stackoverflow.com/questions/25914789
复制相似问题