centos 7.2     spark 2.3.3      scala 2.11.11    java 1.8.0_202-ea

spark-shell中为scala语法格式

1.distinct 去重

val c = sc.parallerlize(List("Gnu","Cat","Rat","Dog","Gnu","Rat"),2)      初始化rdd,将数据均匀加载到2个partition中

c.distinct.collect

>>res1: Array[String]=Array(Dog,Gnu,Cat,Rat)

2.  c.fisrt

first取RDD第一个Partition中的第一个记录

>>res2:String = Gnu

3.filter  过滤

val a = sc.parallelize(1 to 10,3)

val b = a.filter(_ % 2 ==0)

b.collect

>>res3:Array[Int] = Array(2,4,6,8,10)

4.filterByRange          返回指定范围内RDD记录,只能作用于排序RDD

val randRDD = sc.parallelize(List((2,"cat"),(6,"mouse"),(7,"cup),(3,"book"),(4,"tv"),(1,"screen"),(5,"heater")),3)

val sortedRDD = randRDD.sortByKey()

sortRDD.filterByRange(1,3).collect

>>res4:Array[(Int,String)] = Array((1,screen),(2,cat),(3,book))

5.foreach                    遍历RDD内每个记录

val c = sc.parallelize(List("cat","dog","tiger","lion","gnu"),3)

c.foreach(x => println(x + "is ym"))

>>lion is ym

gnu is ym

cat is ym

tiger is ym

dog is ym

6.foreachPartition        遍历RDD内每一个Partition(每个Partition对应一个值)

val b = sc.parallelize(List(1,2,3,4,5,6,7,8),3)

b.foreachPartition(x => println(x.reduce(_ + _ )))

>> 6

15

15

7.fullOuterJoin

rdd1.fullOuterJoin[rdd2]         对两个PairRDD进行外连接 ,相同的key值的全部value组合,没有相同key的也保留,值用None填充

val pairRDD1 = sc.parallelize(List(("cat",2),("cat",5),("book",40)))

val pairRDD2 = sc.parallelize(List(("cat",2),("cup",5),("book",40)))

pairRDD1.fullOuterJoin(pairRDD2).collect

>>res5: Array[(String,(Option[Int],Option[Int]))] = Array((book,(Some(40),Some(40))),  (cup,(None,Some(5))),  (cat,(Some(2),Some(2))),  (cat,(Some(5),Some(2)))

8.groupBy   根据给定的规则 来分组

val a = sc.parallelize(1 to 9,3)

a.groupBy(x => {if (x % 2 == 0) "even" else "odd" }).collect

>> res6:Array[(String,Seq[Int])] = Array((even,ArrayBuffer(2,4,6,8)),(odd,ArrayBuffer(1,3,5,7,9)))

groupBy中使用的方法函数写法还可写作:

def myfunc(a:Int):Int =

{

a % 2

}

a.groupBy(myfunc).collect

def myfunc(a:Int):Int=

{

a % 2

}

a.groupBy(x => myfunc(x),3).collect

a.groupBy(myfunc(_),1).collect

例  将groupBy的条件设置为 partition ,同时自定义数据分区的规则

  1. package sometest
  2. import org.apache.spark.SparkConf
    import org.apache.spark.SparkContext
  3.  
  4. object SparkApplication{
      def main(args:Array[String]){
        val conf = new SparkConf()
        val sc = new SparkContext(conf).setAppName("GroupPartition").setMaster("spark://master:7077")
        val a = sc.parallelize(1 to 9 , 3)
        val p = new MyPartitioner()
        val b = a.groupBy((x:Int) => {x},p) //这里按照自定义分区规则P重新分区,然后groupBy
       // b的形式为RDD[(Int,Iterable[Int])] 比如说 (1,CompactBuffer(1))
  5.  
  6.     def myfunc(index:Int,iter:Iterator[(Int,Iterable[Int])]): Iterator[(Int,(Iterable[Int],Int))] = {
          iter.map(a => (index,(a._2,a._1))) //a._2这种写法表示a中的第2个元素
        }
        val c = b.mapPartitionsWithIndex(myfunc)
        println("This is Result for My :")
        c.collect().foreach(println)
    }
  7.  
  8. 自定义分区规则
  1. package sometest
  2. import org.apache.spark.Partitioner
  3.  
  4. /**
    *自定义数据分区规则
    **/
    class MyPartitioner extends Partitioner{
      def numPartitions:Int = 2 //设置分区数
      def getPartition(key:Any):Int =
      {
        val code = key match
          {
            case null => 0
            case key:Int => key % numPartitions //取余
            case _ => key.hashCode % numPartitions
  1.       }
        ifcode < 0 ){ // 对 hashCode为负数的结果进行处理
                code + numPartitions  
                }
        else{
            code
          }
      }
      override def equals(other:Any):Boolean = // java标准的判断相等的函数, Spark内部比较两个RDD的分区是否一样时 会用到这个这个函数
      {
        other match
        {
          case h:MyPartitioner => h.numPartitions == numPartitions
          case _ => false
        }
      }
    }

打包成sparkAction.jar后 使用命令执行  spark-submit  --class sometest.SparkApplication  ~/sparkAction.jar

输出结果为:

  1. This is Result for My :
    0,(CompactBuffer(4),4))
    ( 0,( CompactBuffer(6),6))
  1. ( 0,( CompactBuffer(8),8))
  1. ( 0,( CompactBuffer(2),2))
  1. ( 0,( CompactBuffer(1),1))
  1. ( 0,( CompactBuffer(3),3))
  1. ( 0,( CompactBuffer(7),7))
  1. ( 0,( CompactBuffer(9),9))
  1. ( 0,( CompactBuffer(5),5))
  1.  
  1. 9.groupByKey [Pair]
    类似于groupBy ,不过函数作用于key,而groupBy的函数是作用于每个数据的
    val a = sc.parallelize(List("dog","tiger","lion","cat","spider","eagle"),2)
    val b = a.keyBy(_.length)
    b.groupByKey.collect
  2.  
  3. 输出res11:Array[(Int,Iterable[String])] = Array((4,CompactBuffer(lion)),(6,CompactBuffer(spider)),(3,CompactBuffer(dog,cat)),(5,CompactBuffer(tiger,eagle)))
  4.  
  5. 10 .histogram[Double] 计算数据直方图 (数值数据分布的精确图形表示)
  6.  
  7. 计算给定数据中的最大值和最小值 ,然后将这个范围段平均分成n组,统计给定数据中每组的频数
    一般来说,范围段为横轴 ,各组的统计个数为纵坐标
  8.  
  9. val a = sc.parallelize(List(1.1,1.2,1.3,2.0,2.1,7.4,7.5,7.6,8.8,9.0),3)
    a.histogram(5) //将样本数据分成 5 组
    res11: Array[Double],Array[Long]) = (Array(1.1,2.68,4.26,5.84,7.42,9.0),Array(5,0,0,1,4))
  10.  
  11. 11 .intersection 返回两个RDD的交集(内连接)
    val x=sc.parallelize(1 to 20)
    val y =sc.parallelize(10 to 30)
    val z = x.intersection(y)
    z.collect
    res74: Array[Int] = Array(16,17,18,10,19,11,20,12,13,14,15)
  12.  
  13. 内连接
    val a = sc.parallelize(List("dog","salmon","salmon","rat","elephant"),3)
    val b = a.keyBy(_.length) //Array[(Int,String)]=Array((3,dog),(3,rat),(6,salmon),(6(salmon),(8,elephant))
    val c = sc.parallelize(List("dog","cat","gnu","salmon","rabbit","turkey","wolf",bear","bee"),3)
  14.  
  15. val d = c.keyBy(_.length)
    b.join(d).collect
    输出 res0: Array[(Int,(String,String))] = Array((6,(salmon,salmon)), (6,(salmon,rabbit)),(6,(salmon.turkey)), (6,(salmon,salmon)),
    (6,(salmon,rabbit)), (6,(salmon,turkey)), (3,(dog,dog)), (3,(dog,cat)), (3,(dog,gnu)) ,(3,(dog,bee)), (3,(rat,dog)),(3,(rat,cat)), (3,(rat,gnu)), (,(rat,bee)))
  16.  
  17. 12 .keys[Pair] 返回 key,value列表中的所有key
  18.  
  19. val a = sc.parallelize(List((3,"dog"),(5,"tiger"),(4,"lion"),(3,"cat"),(7,"panther"),(5,"eagle")),2)
    a.keys.collect
    res2: Array[Int] = Array(3,5,4,3,7,5)
  20.  
  21. 13 . lookup 查找指定记录
    val a = sc.parallelize(List((3,"dog"),(5,"tiger"),(4,"lion"),(3,"cat"),,(7,"panther"),(5,"eagle")),2)
    a.lookup(5)
    res8: Seq[String] = WrappedArray(tiger,eagle)
  22.  
  23. 14 .max 返回最大值
    借用上述的a
    a.max
    res9: (Int,String) = (7,panther)
  24.  
  25. val y =sc.parallelize(10 to 30)
    y.max
    res10: Int = 30
  1. 15 . mean 平均值
    y.mean
    res13: Double = 20.0
  2.  
  3. 16 . persist,cache 设置RDD的存储级别
    val c = sc.parallelize(List("Gnu","Cat","Rat","Dog","Gnu","Rat"),2)
    c.getStorageLevel
    res14: org.apache.spark.storage.StorageLevel = StorageLevel(1 replicas)
    c.cache
    res15: c.type = ParallelCollectionRDD[41] at parallelize at <console>:24
    c.getStorageLevel
    res16:org.apache.spark.storage.StorageLevel = StorageLevel(memory, deserialized, 1 replicas)
  4.  
  5. 17 . sample 根据给定比例对数据进行采样
    sample(withReplacement, fraction, seed)
    withReplacement : 是否使用随机数替换
    fraction 对数据进行采样的比例
    seed : 随机数生成器种子
    val a = sc.parallelize(1 to 10000,3)
    a.sample(false,0.1,0).count
    res17:Long = 1032
  6.  
  7. a.sample(true,0.3,0).count
    res18: Long = 3110
  8.  
  9. a.sample(true,0.3,13).count
    res20 : Long = 2952
  10.  
  11. 18 .saveAsTextFile保存到文本数据 (默认 文件系统是hdfs
    textFile读取文本数据
  12.  
  13. val a = sc.parallelize(11 to 19,3)
    a.saveAsTextFile("test/tf") //实际上是保存到文件夹 test/tf ,由于并行化因子为3,一个Partition对应一个par-000x
    val b = sc.textFile("test/tf")
    b.collect
    res4: Array[String] = Array(11,12,13,14,15,16,17,18,19)
  14.  
  15. 19 .take 返回数据集中的前N个数据
    val b = sc.parallelize(List("dog","cat","ape","salmon","gnu"),2)
    b.take(2)
    res5: Array[String] = Array(dog,cat)
  16.  
  17. 20 .union,++ 对两个RDD数据进行并集 ,合并两个RDD
    val a = sc.parallelize( 1 to 5,1)
    val b = sc.parallelize(5 to 7,1)
    (a++b).collect
    Array[Int] = Array(1,2,3,4,5,5,6,7)

spark-shell 中rdd常用方法的更多相关文章

  1. 02、体验Spark shell下RDD编程

    02.体验Spark shell下RDD编程 1.Spark RDD介绍 RDD是Resilient Distributed Dataset,中文翻译是弹性分布式数据集.该类是Spark是核心类成员之 ...

  2. 在Spark shell中基于HDFS文件系统进行wordcount交互式分析

    Spark是一个分布式内存计算框架,可部署在YARN或者MESOS管理的分布式系统中(Fully Distributed),也可以以Pseudo Distributed方式部署在单个机器上面,还可以以 ...

  3. Spark SQL中 RDD 转换到 DataFrame (方法二)

    强调它与方法一的区别:当DataFrame的数据结构不能够被提前定义.例如:(1)记录结构已经被编码成字符串 (2) 结构在文本文件中,可能需要为不同场景分别设计属性等以上情况出现适用于以下方法.1. ...

  4. 在Spark shell中基于Alluxio进行wordcount交互式分析

    Spark是一个分布式内存计算框架,可部署在YARN或者MESOS管理的分布式系统中(Fully Distributed),也可以以Pseudo Distributed方式部署在单个机器上面,还可以以 ...

  5. Spark SQL中 RDD 转换到 DataFrame

    1.people.txtsoyo8, 35小周, 30小华, 19soyo,882./** * Created by soyo on 17-10-10. * 利用反射机制推断RDD模式 */impor ...

  6. Spark Shell简单使用

    基础 Spark的shell作为一个强大的交互式数据分析工具,提供了一个简单的方式学习API.它可以使用Scala(在Java虚拟机上运行现有的Java库的一个很好方式)或Python.在Spark目 ...

  7. [Spark][Python][DataFrame][RDD]DataFrame中抽取RDD例子

    [Spark][Python][DataFrame][RDD]DataFrame中抽取RDD例子 sqlContext = HiveContext(sc) peopleDF = sqlContext. ...

  8. Spark中RDD的常用操作(Python)

    弹性分布式数据集(RDD) Spark是以RDD概念为中心运行的.RDD是一个容错的.可以被并行操作的元素集合.创建一个RDD有两个方法:在你的驱动程序中并行化一个已经存在的集合:从外部存储系统中引用 ...

  9. 小白学习Spark系列三:RDD常用方法总结

    上一节简单介绍了Spark的基本原理以及如何调用spark进行打包一个独立应用,那么这节我们来学习下在spark中如何编程,同样先抛出以下几个问题. Spark支持的数据集,如何理解? Spark编程 ...

随机推荐

  1. & 和 && 的区别,与(&)运算符、位移运算符(<< 、>>、>>>)的含义及使用(Java示例)

    & 和 && 的区别,与(&)运算符.位移运算符(<< .>>.>>>)的含义及使用(Java示例) 1. & 和 & ...

  2. android binder 进程间通信机制3-Binder 对象生死

    以下概述Binder通信过程中涉及到的四个对象:Binder本地对象.Binder实体对象.Binder引用对象.Binder代理对象的生死. 1.Binder通信的交互过程 1.Client 进程发 ...

  3. Acwing 14. 不修改数组找出重复的数字

    题目地址  https://www.acwing.com/problem/content/description/15/ 来源:剑指Offer 给定一个长度为 n+1n+1 的数组nums,数组中所有 ...

  4. Python:程序练习题(二)

    Python:程序练习题(二) 2.1温度转换程序. 代码如下: t=input("请输入带符号的温度值(如:32C):") if t[-1] in ["C", ...

  5. servlet重点知识总结

    Servlet Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层. ...

  6. Mybatis相关试题

    1.MyBatis有两种事务管理器类型,分别是() A:JDBC B:MANAGED C:POOLED D:JBDI 正确答案:AB 试题分析: 在 MyBatis 中有两种事务管理器类型(也就是 t ...

  7. 《细说PHP》第四版 样章 第23章 自定义PHP接口规范 5

    23.3  接口的安全控制规范 23.2节的示例实现了一个简单接口,但是这个接口此时是在“裸奔”的.因为这个接口所有人都可以请求,不仅我们的客户端可以正常访问数据,如果有人使用如fiddler.wir ...

  8. H3C DRNI学习

    DRNI:Distributed Resilient Network Interconnect,分布式弹性网络互连.DR:分布式聚合接口IPP:内部控制链路端口IPL:内部控制链路DRCP报文:分布式 ...

  9. Nginx超时设定

    最近针对公司的goscon网关发了一个PR,新增了握手阶段的超时判定.现在回顾一下Nginx的所有超时判定,看看目前还缺少哪些判定 ngx_http_core_module包含的timeout: cl ...

  10. 错误InnoDB:Attemptedtoopenapreviouslyopenedtablespace.

    2013-08-04 13:48:22 760 [ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous t ...