spark shell的学习

Spark的交互式脚本是一种学习API的简单途径,也是分析数据集交互的有力工具。

Spark抽象的分布式集群空间叫做Resilient Distributed Dataset (RDD)弹性数据集。

其中,RDD有两种创建方式:

(1)、从Hadoop的文件系统输入(例如HDFS);

(2)、有其他已存在的RDD转换得到新的RDD;

下面进行简单的测试:

 

1. 进入SPARK_HOME/bin下运行命令:

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. $./spark-shell  


2. 利用HDFS上的一个文本文件创建一个新RDD:

 

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. scala> var textFile = sc.textFile("hdfs://localhost:50040/input/WordCount/text1");  
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. textFile: org.apache.spark.rdd.RDD[String] = MappedRDD[1] at textFile at <console>:12  


3. RDD有两种类型的操作 ,分别是Action(返回values)和Transformations(返回一个新的RDD)

 

(1)Action相当于执行一个动作,会返回一个结果:

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. scala> textFile.count() // RDD中有多少行  

 

 

输出结果2:

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. 14/11/11 22:59:07 INFO spark.SparkContext: Job finished: count at <console>:15, took 5.654325469 s  
  2. res1: Long = 2  

 

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. scala> textFile.first() // RDD第一行的内容  

结果输出:

 

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. 14/11/11 23:01:25 INFO spark.SparkContext: Job finished: first at <console>:15, took 0.049004829 s  
  2. res3: String = hello world  

 

(2)Transformation相当于一个转换,会将一个RDD转换,并返回一个新的RDD:

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. scala> textFile.filter(line => line.contains("hello")).count() // 有多少行含有hello  

结果输出:

 

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. 14/11/11 23:06:33 INFO spark.SparkContext: Job finished: count at <console>:15, took 0.867975549 s  
  2. res4: Long = 2  


4. spark shell的WordCount

 

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. scala> val file = sc.textFile("hdfs://localhost:50040/input")  
  2. scala>  val count = file.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey(_+_)  
  3. scala> count.collect()  

 

输出结果:

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
 
  1. 14/11/11 23:11:46 INFO spark.SparkContext: Job finished: collect at <console>:17, took 1.624248037 s  

 

http://blog.csdn.net/yeruby/article/details/41043039

猜你喜欢

转载自m635674608.iteye.com/blog/2251187