Big Data Application

Spark快速入门(1) 核心概念和抽象:RDD

2019-03-28  本文已影响0人  MeazZa

Spark简介

Spark是目前比较流程的大数据计算引擎。在Spark出现之前,MapReduce已经作为大数据领域的编程模型和计算框架,那为什么又开发了Spark呢?

Spark通过对数据的重新抽象,和执行过程的优化,致力于解决以上问题,目前Spark已经可以应用于批计算、实时计算和图计算,并在向数据科学方向继续发展。

Spark RDD

RDD是Spark的核心抽象,既可以灵活方便的定义一个计算过程,又可以保证计算过程可以有效的执行。

为什么需要RDD

假设我们实现一些需要循环的计算,比如K-Means和PageRank,使用MapReduce的模型存在什么问题呢?

什么是RDD

然后我们看一下RDD(Resilient Distributed Dataset),这里的Resilient和Distributed体现了两个重要的特性:

因此RDD的准确定义是一组只读并且支持分区的数据集。每个RDD需要实现的三个接口有:

  /**
   * Get the array of partitions of this RDD, taking into account whether the
   * RDD is checkpointed or not.
   */
  final def partitions: Array[Partition] = {
    checkpointRDD.map(_.partitions).getOrElse {
      if (partitions_ == null) {
        partitions_ = getPartitions
        partitions_.zipWithIndex.foreach { case (partition, index) =>
          require(partition.index == index,
            s"partitions($index).partition == ${partition.index}, but it should equal $index")
        }
      }
      partitions_
    }
  }
  /**
   * Internal method to this RDD; will read from cache if applicable, or otherwise compute it.
   * This should ''not'' be called by users directly, but is available for implementors of custom
   * subclasses of RDD.
   */
  final def iterator(split: Partition, context: TaskContext): Iterator[T] = {
    if (storageLevel != StorageLevel.NONE) {
      getOrCompute(split, context)
    } else {
      computeOrReadCheckpoint(split, context)
    }
  }
  /**
   * Get the list of dependencies of this RDD, taking into account whether the
   * RDD is checkpointed or not.
   */
  final def dependencies: Seq[Dependency[_]] = {
    checkpointRDD.map(r => List(new OneToOneDependency(r))).getOrElse {
      if (dependencies_ == null) {
        dependencies_ = getDependencies
      }
      dependencies_
    }
  }

RDD中的数据类型是提前定义好的,比如RDD<String>、RDD<Integer>等。

我们来看一个RDD的实现,假如我们有一个读取HDFS上的二进制文件的RDD:

这里如果文件是由某种Hadoop的文件格式存储,并进行切分的话,切分会使用到一个实现了输入文件切分接口的对象,而且这个对象也会被发送到iterator中用于解析切分后的文件。

再看一个RDD的实现,内存中的数组。如果将整个数组看成一个partition,那么它的三个方法的实现分别为:

如果将数组分成多块,每块为一个partition的话,那么它的三个方法实现如下:

使用分块的方法可以使计算并行化,加快计算速度。

小结

本节我们主要介绍了RDD的概念,RDD的实现不仅说明了RDD的分区方式,遍历方式,还说明了它所依赖的RDD的格式,这么做的目的会在后面继续介绍。

上一篇 下一篇

猜你喜欢

热点阅读