02-大数据内存计算spark系列贴-spark介绍、spark程序

   (原文地址: http://blog.csdn.net/codemosi/article/category/2777045,转载麻烦带上原文地址。hadoop hive hbase mahout storm spark kafka flume,等连载中,做个爱分享的人 奋斗)

有hadoop上经验的人知道,hadoop上有mapreduce可以分析。spark可以像,hadoop中的mapreduce那样做数据分析。spark提供了比hadoop的map(),reduce()更多的函数来分析,并且在内存中运算(基于RDD),速度比hadoop的mapreduce快。程序员都喜欢从代码入手,不喜欢听故事。


  1. package cn.ffcs.rdc.spark

  2. import org.apache.spark.{SparkContext, SparkConf}
  3. import org.apache.spark.SparkContext._

  4. /**
  5. * Created by lee gz
  6. */
  7. class RdcTest{

  8. }

  9. object RdcTest{

  10.          def main(args : Array[String]){

  11.                     val conf = new SparkConf() //conf 对象,用来记录配置信息,供下面的SparkContext使用。类似xml配置 jdbc的信息一样的作用。
  12.                     conf.setMaster("spark://rdc:8888")
  13.                            .setSparkHome("/usr/spark-0.9.2")
  14.                            .setAppName("RDC")
  15.                            .setJars(jars)
  16.                            .set("spark.executor.memory","4g")

  17.                    val sc = new SparkContext(conf) // spark 的上下文对象
  18.                    val data = sc.textFile("hdfs://rdc/data.txt")//spark提供统一的接口,textFile(path)方法。支持hdfs,本地文件系统,hbase,s3,Cassandra等多种数据源
  19.                   
  20.                    data.cache  //将 data 持久化到 内存中,供下次使用。

  21.                    println(data.count)      

  22.                    data.filter(_.split(' ').length == 3)
  23.                           .map(_.split(' ')(1))
  24.                           .map((_,1))
  25.                           .reduceByKey(_+_)
  26.                           .map(x => (x._2, x._1))
  27.                           .sortByKey(false)
  28.                           .map( x => (x._2, x._1))
  29.                           .saveAsTextFile("hdfs://rdc/result.txt")     //通过saveAsTextFile的方法,将分析的结结果导入hdfs,本地文件系统中去
  30.          }

  31. }

从代码出发,来研究spark。
                        1:spark的执行流程 1,2,3
                                        1 将数据源,换成RDD(弹性分布式集合。)  //      sc.textFile("hdfs://rdc/data.txt")
                           --》       2  Transformations  类型的方法                       //       filter,reduceByKey,sortByKey 等转换,用来构造DAG 图(执行的流程,无回路有向图)。
                                                                                                               // 由Actions来启动执行流程。
                           --》       3  Actions         类型的方法                             //         saveAsTextFile()  ,actions开始执行DAG图
                                       
                         2:   Transformations 类型的方法

TransformationMeaning
map(func)Return a new distributed dataset formed by passing each element of the source through a functionfunc.
filter(func)Return a new dataset formed by selecting those elements of the source on whichfunc returns true.
flatMap(func)Similar to map, but each input item can be mapped to 0 or more output items (sofunc should return a Seq rather than a single item).
mapPartitions(func)Similar to map, but runs separately on each partition (block) of the RDD, so func must be of type Iterator<T> => Iterator<U> when running on an RDD of type T.
mapPartitionsWithIndex(func)Similar to mapPartitions, but also provides func with an integer value representing the index of the partition, sofunc must be of type (Int, Iterator<T>) => Iterator<U> when running on an RDD of type T.
sample(withReplacement, fraction, seed)Sample a fraction fraction of the data, with or without replacement, using a given random number generator seed.
union(otherDataset)Return a new dataset that contains the union of the elements in the source dataset and the argument.
intersection(otherDataset)Return a new RDD that contains the intersection of elements in the source dataset and the argument.
distinct([numTasks]))Return a new dataset that contains the distinct elements of the source dataset.
groupByKey([numTasks])When called on a dataset of (K, V) pairs, returns a dataset of (K, Iterable<V>) pairs.
Note: If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduceByKey or combineByKey will yield much better performance.
Note: By default, the level of parallelism in the output depends on the number of partitions of the parent RDD. You can pass an optional numTasks argument to set a different number of tasks.
reduceByKey(func, [numTasks])When called on a dataset of (K, V) pairs, returns a dataset of (K, V) pairs where the values for each key are aggregated using the given reduce functionfunc, which must be of type (V,V) => V. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.
sortByKey([ascending], [numTasks])When called on a dataset of (K, V) pairs where K implements Ordered, returns a dataset of (K, V) pairs sorted by keys in ascending or descending order, as specified in the boolean ascending argument.
join(otherDataset, [numTasks])When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (V, W)) pairs with all pairs of elements for each key. Outer joins are also supported through leftOuterJoin and rightOuterJoin.
cogroup(otherDataset, [numTasks])When called on datasets of type (K, V) and (K, W), returns a dataset of (K, Iterable<V>, Iterable<W>) tuples. This operation is also called groupWith.
cartesian(otherDataset)When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements).
pipe(command, [envVars])Pipe each partition of the RDD through a shell command, e.g. a Perl or bash script. RDD elements are written to the process's stdin and lines output to its stdout are returned as an RDD of strings.
coalesce(numPartitions)Decrease the number of partitions in the RDD to numPartitions. Useful for running operations more efficiently after filtering down a large dataset.
repartition(numPartitions)Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them. This always shuffles all data over the network.


                   3: Actions 类型的方法
ActionMeaning
reduce(func)Aggregate the elements of the dataset using a function func (which takes two arguments and returns one). The function should be commutative and associative so that it can be computed correctly in parallel.
collect()Return all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data.
count()Return the number of elements in the dataset.
first()Return the first element of the dataset (similar to take(1)).
take(n)Return an array with the first n elements of the dataset. Note that this is currently not executed in parallel. Instead, the driver program computes all the elements.
takeSample(withReplacement, num, seed)Return an array with a random sample of num elements of the dataset, with or without replacement, using the given random number generator seed.
takeOrdered(n, [ordering])Return the first n elements of the RDD using either their natural order or a custom comparator.
saveAsTextFile(path)Write the elements of the dataset as a text file (or set of text files) in a given directory in the local filesystem, HDFS or any other Hadoop-supported file system. Spark will call toString on each element to convert it to a line of text in the file.
saveAsSequenceFile(path)
(Java and Scala)
Write the elements of the dataset as a Hadoop SequenceFile in a given path in the local filesystem, HDFS or any other Hadoop-supported file system. This is available on RDDs of key-value pairs that either implement Hadoop's Writable interface. In Scala, it is also available on types that are implicitly convertible to Writable (Spark includes conversions for basic types like Int, Double, String, etc).
saveAsObjectFile(path)
(Java and Scala)
Write the elements of the dataset in a simple format using Java serialization, which can then be loaded using SparkContext.objectFile().
countByKey()Only available on RDDs of type (K, V). Returns a hashmap of (K, Int) pairs with the count of each key.
foreach(func)Run a function func on each element of the dataset. This is usually done for side effects such as updating an accumulator variable (see below) or interacting with external storage systems.

                        4:  从执行流程可以看出,为什么spark运行得快  
                              1:可以看到执行过程基于RDD,在内存中计算减少和磁盘的IO
                              2:map,reduceByKey,等分析都是先构造DAG(无回路有向图),延迟执行而不是立即执行,这样调度器根据这个DAG图,提前知道执行流程,自动做线性复 杂度的优化。最好的利用集群的内存cpu资源。

                      5:容错性(Lineage特性)
                               1:DAG,图可以得到,每一步的RDD的依赖关系。当数据丢失时,根据依赖关系(Lineage特性)自动快速的恢复数据
                                           如 :    data.txt  -->  RDD1 --map  -- RDD2   -->  groupByKey -->RDD3 -- map -->  RDD4  --> count -- > result.txt
                                           上面这个分析过程绘出的DAG图记录着 每个RDD的依赖关系,如RDD3是由RDD2 通过groupBeKey 转换过来的依赖关系。当RDD3的某个机器上的分区数据丢失,可以直接在
                                    RDD2执行groupByKey一步操作就可以恢复RDD3丢失的数据。而不用从新从data.txt文件开始一步步的执行。这就是spark的 Lineage特性。

                      6:RDD(弹性分布式集合)
                               到这里,我们知道spark进行大数据分析,是通过一个个的RDD,的transformation,action来做分析的。那么什么是RDD呢。下面是官方的说明
                                       Spark revolves around the concept of a resilient distributed dataset (RDD), which is a fault-tolerant collection of elements that can be operated on in parallel。By default,
                               each transformed RDD may be recomputed each time you run an action on it. However, you may also persist an RDD in memory using the persist (or cache) method。
                               Spark’s cache is fault-tolerant – if any partition of an RDD is lost, it will automatically be recomputed using the transformations that originally created it.  
                               1:  RDD是一个弹性分布式内存的抽象概念。是集群中各个机器中保存的物理partition 分片的集合。可以通过RDD的引用并行的访问集群的数据。分片并行的运行transcription任务。
                               2:  默认做过transformation类型操作的RDD进行action操作时都会重新计算一次,可以使用persist或者cache 将RDD 保存在内存中。
                               3:  cache到内存中的RDD是容错的,当RDD的某个机器上的分片丢失,Lineage特性根据DAG, 自动的恢复丢失的数据。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值