首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在apache spark (scala)中迭代RDD

如何在apache spark (scala)中迭代RDD
EN

Stack Overflow用户
提问于 2014-09-18 22:00:15
回答 2查看 85.4K关注 0票数 22

我使用以下命令用一堆包含2个字符串"filename“、"content”的数组填充RDD。

现在,我想遍历所有这些事件,对每个文件名和内容做一些处理。

代码语言:javascript
复制
val someRDD = sc.wholeTextFiles("hdfs://localhost:8020/user/cloudera/*")

然而,我似乎找不到任何关于如何做到这一点的文档。

所以我想要的是:

代码语言:javascript
复制
foreach occurrence-in-the-rdd{
   //do stuff with the array found on loccation n of the RDD
} 
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-09-19 01:54:07

Spark中的基本操作是mapfilter

代码语言:javascript
复制
val txtRDD = someRDD filter { case(id, content) => id.endsWith(".txt") }

txtRDD现在将只包含扩展名为".txt“的文件

如果你想计算这些文件的字数,你可以说

代码语言:javascript
复制
//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工具这样的库进行命名实体识别。

掌握mapfilterflatMapreduce,您就可以很好地掌握Spark。

票数 9
EN

Stack Overflow用户

发布于 2018-06-13 23:08:28

代码语言:javascript
复制
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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25914789

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档