// 读取文件,压缩文件和路径都可以
val lines = sc.textFile("hdfs://localhost:9000/...")// hdfs
val textFile = sc.textFile("file:///usr/local/spark/mycode/wordcount/word.txt")// local// 从driver的内存中读取
val array =Array(1,2,3,4,5)// list也okay的
val rdd = sc.parallelize(array)// transformation 转换操作(惰性)filter()//filter desired datamap()//A -> A'flatMap()//map first and then concatenationgroupByKey()//(k,v) -> (k,iterable)reduceByKey()//(k,v) -> (k,v')// action 行动操作(非惰性)结果返回到master上count()// return the number of elementscollect()// return all elements in an array to the masterfirst()// return the first elementtake(n)// return first n elements as an array to the masterreduce(func)// aggregation elements (no key)foreach(func)// iterate all elements and pass to func// 持久化,重复数据的不同action之前可以加入持久化,加快运行速度
rdd.cache()// 键值对操作(k,v)// 表现为数组形式,第一个为key,第二个为value// reduceByKey(func)
pairRDD.reduceByKey((a,b)=>a+b).foreach(println)// a和b都是value// groupByKey()
pairRDD.groupByKey().foreach(println)// (Spark,CompactBuffer(1, 1))// keys操作
pairRDD.keys.foreach(println)//返回所有key// values操作
pairRDD.values.foreach(println)//返回所有values// sortByKey()
pairRDD.sortByKey().foreach(println)// mapValues(func)
pairRDD.mapValues(x => x+1).foreach(println)// func only operates on values// join// 对于内连接,对于给定的两个输入数据集(K,V1)和(K,V2),// 只有在两个数据集中都存在的key才会被输出,最终得到一个(K,(V1,V2))类型的数据集。
pairRDD1.join(pairRDD2).foreach(println)// (spark,(1,fast))// (spark,(2,fast))// 共享变量// 1. Broadcast Variables: 在所有节点的内存间共享,无副本
val broadcastVar = sc.broadcast(Array(1,2,3))// create
broadcastVar.value // get// 2. Accumulators:支持在所有节点进行累加计算(比如计数或者求和)
val accum = sc.longAccumulator("My Accumulator")// 子节点只能读值,不能累加// master 或者说driver program会累加值
sc.parallelize(Array(1,2,3,4)).foreach(x => accum.add(x))
accum.value
// 保存文件
val textFile = sc.textFile("file:///usr/local/spark/mycode/wordcount/word.txt")// local
textFile.saveAsTestFile("file:///usr/local/spark/mycode/wordcount/new_word.txt")
val lines = sc.textFile("hdfs://localhost:9000/word.txt")// hdfs
lines.saveAsTestFile("hdfs://localhost:9000/new_word.txt")// read json fileimport scala.util.parsing.json.JSON
val result = jsonStrs.map(s => JSON.parseFull(s))
result.foreach({r => r match {caseSome(map: Map[String, Any])=>println(map)case None =>println("Parsing failed")case other =>println("Unknown data structure: "+ other)}})