spark编写WordCount

文章目录

一、在hdfs创建in.txt文件

1.在hdfs的/user/spark/in/目录下建一个in.txt文件

分析如下:

(1).我们需要现在hdfs中创建文件所需目录。

1>创建文件夹

[e93b8f root@master ~]$ hdfs dfs -mkdir /user
[e93b8f root@master ~]$ hdfs dfs -mkdir /user/spark/
[e93b8f root@master ~]$ hdfs dfs -mkdir /user/spark/in

2>也可通过命令创建多级目录。

[ebdfc5 root@master ~]$ hdfs dfs -mkdir -p /user/spark/in/
[ebdfc5 root@master ~]$ hdfs dfs -ls /user/spark/in/

3>通过命令查看是否创建成功

[ebdfc5 root@master ~]$ hdfs dfs -ls /user/spark/

(2).在根目录创建in.txt文件并将其传到hdfs中

1>首先创建txt文件

[e93b8f root@master ~]$ vim in.txt

在文件中输入内容

hello world
ni hao

2>通过pwd查看本地文件所在路径

[ebdfc5 root@master ~]$ pwd

3>文件创建成功之后,将本地的in.txt文件上传至hdfs中。

hadoop fs -put /root/in.txt hdfs:/user/spark/in/

4> 在hdfs中查看是否已经存在。

二、运行wordcount

 2.在spark-shell中编写WordCount代码和运行。

1>启动spark-shell

[131ba4 root@master ~]$ spark-shell

2>写入wordcount的scala代码并运行

scala> val file=sc.textFile("hdfs://master:8020/user/spark/in/in.txt")
scala> val count=file.flatMap(line => line.split(" ")).map(word =>(word,1)).reduceByKey(_+_)
scala> count.collect()

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值