- Spark Cookbook
- Rishi Yadav
- 309字
- 2021-07-16 13:44:01
Loading data from the local filesystem
Though the local filesystem is not a good fit to store big data due to disk size limitations and lack of distributed nature, technically you can load data in distributed systems using the local filesystem. But then the file/directory you are accessing has to be available on each node.
Please note that if you are planning to use this feature to load side data, it is not a good idea. To load side data, Spark has a broadcast variable feature, which will be discussed in upcoming chapters.
In this recipe, we will look at how to load data in Spark from the local filesystem.
How to do it...
Let's start with the example of Shakespeare's "to be or not to be":
- Create the
words
directory by using the following command:$ mkdir words
- Get into the
words
directory:$ cd words
- Create the
sh.txt
text file and enter"to be or not to be"
in it:$ echo "to be or not to be" > sh.txt
- Start the Spark shell:
$ spark-shell
- Load the
words
directory as RDD:scala> val words = sc.textFile("file:///home/hduser/words")
- Count the number of lines:
scala> words.count
- Divide the line (or lines) into multiple words:
scala> val wordsFlatMap = words.flatMap(_.split("\\W+"))
- Convert
word
to (word,1)—that is, output1
as the value for each occurrence ofword
as a key:scala> val wordsMap = wordsFlatMap.map( w => (w,1))
- Use the
reduceByKey
method to add the number of occurrences for each word as a key (this function works on two consecutive values at a time, represented bya
andb
):scala> val wordCount = wordsMap.reduceByKey( (a,b) => (a+b))
- Print the RDD:
scala> wordCount.collect.foreach(println)
- Doing all of the preceding operations in one step is as follows:
scala> sc.textFile("file:///home/hduser/ words"). flatMap(_.split("\\W+")).map( w => (w,1)). reduceByKey( (a,b) => (a+b)).foreach(println)
This gives the following output:

推薦閱讀
- 零起步玩轉(zhuǎn)掌控板與Mind+
- Building a Home Security System with Raspberry Pi
- 前端架構(gòu):從入門到微前端
- Functional Programming in JavaScript
- QTP自動(dòng)化測(cè)試進(jìn)階
- Python機(jī)器學(xué)習(xí)算法與實(shí)戰(zhàn)
- HTML5+CSS3網(wǎng)頁(yè)設(shè)計(jì)
- 零基礎(chǔ)趣學(xué)C語(yǔ)言
- SQL Server實(shí)用教程(SQL Server 2008版)
- 智能手機(jī)APP UI設(shè)計(jì)與應(yīng)用任務(wù)教程
- Building Serverless Architectures
- 新印象:解構(gòu)UI界面設(shè)計(jì)
- Android Studio Cookbook
- Arduino Wearable Projects
- C編程技巧:117個(gè)問題解決方案示例