spark-shell中的简单操作

1.wordCount的几种写法

一般函数式写法:

sc.textFile("/user/chenjinghui/words").flatMap(x=>x.split(" ")).map(x=>(x,1)).reduceByKey((a,b)=>(a+b)).collect



简洁写法:

sc.textFile("/user/chenjinghui/words").flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_).collect
拓展:按照统计结果降序排序:

sc.textFile("/user/chenjinghui/words").flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_).map(x=>(x._2,x._1)).sortByKey(false).map(x=>(x._2,x._1)).collect

2.读取操作sequenceFile

sc.sequenceFile[org.apache.hadoop.io.LongWritable,org.apache.hadoop.io.Text]("path").map(x=>x._2.toString).saveAsTextFile("/user/chenjinghui")


将结果保存到hdfs:

sc.sequenceFile[org.apache.hadoop.io.LongWritable,org.apache.hadoop.io.Text]("path").map(x=>x._2.toString).saveAsTextFile("/user/chenjinghui")

实例:取电信前10的domain

sc.sequenceFile[org.apache.hadoop.io.LongWritable,org.apache.hadoop.io.Text]("/daas/bstl/dpiqixin/beijing/20160612/MBLDPI3G.2016061223_10.1465743600915.lzo_deflate").map(x=>x._2.toString).map(_.split("\\|")(27)).map((_,1)).reduceByKey(_+_).map(x=>(x._2,x._1)).sortByKey(false).map(x=>(x._2,x._1)).take(10)

spark操作sequencefile

import org.apache.spark._
import org.apache.spark.SparkContext._

object SequenceFileTest {
  def main(args: Array[String]) {
    val conf = new SparkConf()
    conf.setAppName("SequenceFileTest")
    conf.setMaster("local[3]")
    val sc = new SparkContext(conf)
    val data = List(("ABC", 1), ("BCD", 2), ("CDE", 3), ("DEF", 4), ("FGH", 5))
    val rdd = sc.parallelize(data, 1)
    val dir = "/user/chenjinghui/text"
    rdd.saveAsSequenceFile(dir)
    val rdd2 = sc.sequenceFile[String, Int](dir + "/part-00000")
    println(rdd2.collect().map(elem => (elem._1 + ", " + elem._2)).toList)
    sc.stop()
  }
}


你可能感兴趣的:(spark-shell中的简单操作)