Spark官网提供的Spark快速使用指南。首先,我们通过Spark的交互式shell来介绍API。然后展示如何使用Java,Scala,Python编写应用。完全参考手册请见programming guide。
To follow along with this guide, first download a packaged release of Spark from the Spark website. Since we won’t be using HDFS, you can download a package for any version of Hadoop.
跟随这个这个指南,首先下载Spark Website。如果我们不使用HDFS,你可以下载任何版本的Hadoop包。
Interactive Analysis with the Spark Shell
Basics
Spark shell提供一个简单的学习API的方法,交互式分析数据的强力工具。Scala或Python都可以。让我们在Spark的目录中运行它:
./bin/spark-shell
Spark’s primary abstraction is a distributed collection of items called a Resilient Distributed Dataset (RDD). RDDs can be created from Hadoop InputFormats (such as HDFS files) or by transforming other RDDs. Let’s make a new RDD from the text of the README file in the Spark source directory:
Spark的主要抽象数据是一种称为弹性分布数据集(RDD)的分布式的元素集合。RDDs可以从Hadoop InputFormats(例如HDFS文件)创建,或在其它RDDs转化而来。让我们从在Spark目录文件中的README.txt,来创建一个新RDD:
scala> val textFile = sc.textFile("README.md")
textFile: spark.RDD[String] = spark.MappedRDD@2ee9b6e3
Action,可以返回值;或者transformations-新RDDs的指针。(只有action才会执行;熟记那些函数是action的-如:count(),collect()等)。
scala> textFile.count() // Number of items in this RDD
res0: Long = 126
scala> textFile.first() // First item in this RDD
res1: String = # Apache Spark
Transformation.使用filter transformation返回一个新RDD,通过文件中元素的子集。
scala> val linesWithSpark = textFile.filter(line => line.contains("Spark"))
linesWithSpark: spark.RDD[String] = spark.FilteredRDD@7dd4af09
我们可以把transformations和actions链接在一起:
scala> textFile.filter(line => line.contains("Spark")).count() // How many lines contain "Spark"?
res3: Long = 15
More on RDD Operations
RDD actions 和 transformations 可以被应用在更复杂的计算。查找words最多的line:
scala> textFile.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b)
res4: Long = 15
第一个方法把一行映射成一个整数值,创建一个新RDD。这个新RDD调用reduce 找到行中最大值。map和reduce是Scala的方法(闭包),也可以使用任何语言的特征或Scala/Java库。例如,我们可以很容易的调用函数声明的地方。我们用Math.max() 函数使代码更加容易理解:
scala> import java.lang.Math
import java.lang.Math
scala> textFile.map(line => line.split(" ").size).reduce((a, b) => Math.max(a, b))
res5: Int = 15
常见的数据流模式是MapReduce。Spark可以很容易的实现MapReduce:
scala> val wordCounts = textFile.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey((a, b) => a + b)
wordCounts: spark.RDD[(String, Int)] = spark.ShuffledAggregatedRDD@71f027b8
这里我们结合 flatMap, map and reduceByKey transformations计算文件中每个字的数量通过使用(String, Int)对的RDD。在shell中使用collect action收集字的数量:
scala> wordCounts.collect()
res6: Array[(String, Int)] = Array((means,1), (under,2), (this,3), (Because,1), (Python,2), (agree,1), (cluster.,1), ...)
Caching
Spark支持把数据集放入集群内存缓存。反复访问的时候会非常有用,例如:查询一个小的”热”数据集或运行一个像PageRank这样的迭代算法。让我们缓存linesWithSpark数据集:
scala> linesWithSpark.cache()
res7: spark.RDD[String] = spark.FilteredRDD@17e51082
scala> linesWithSpark.count()
res8: Long = 15
scala> linesWithSpark.count()
res9: Long = 15
使用Spark探索缓存一个100行的文本文件看起来很愚蠢。有趣的是这些相同的方法也可以使用在相当大的数据集中,甚至当他们跨越几十或几百的节点。也可以使用bin/spark-shell与集群交互的缓存,programming guide中描述了。
Self-Contained Applications
现在,我们要使用Spark API编写一个独立的应用。
使用Scala编写的一个简单Spark应用:SimpleApp.scala:
/* SimpleApp.scala */
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
object SimpleApp {
def main(args: Array[String]) {
val logFile = "YOUR_SPARK_HOME/README.md" // Should be some file on your system
val conf = new SparkConf().setAppName("Simple Application")
val sc = new SparkContext(conf)
val logData = sc.textFile(logFile, 2).cache()
val numAs = logData.filter(line => line.contains("a")).count()
val numBs = logData.filter(line => line.contains("b")).count()
println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
}
}
注意,applications应该定义main()方法替代实现scala.App的方式。scala.App的子类不会正确的运行。
这段程序只是计算Spark的REDAME中,包含’a’的行的数和包含’b’的行的数。注意,你需要替换YOUR_SPARK_HOME为你的Spark本地目录。不像使用Spark shell的简单示例-初始化他自己的SparkContext,我们初始化一个SparkContext作为程序的一部分。
我们要传递给SparkContext constructor一个包含应用信息的SparkConf对象。
我们的应用依赖Spark API,所以我们也要引入sbt配置文件-simple.sbt。
simple.sbt也添加Spark依赖仓库:
name := "Simple Project"
version := "1.0"
scalaVersion := "2.10.4"
libraryDependencies += "org.apache.spark" %% "spark-core" % "1.3.0"
为了sbt正确的运行,我们需要根据典型的目录结构布局SimpleApp.scala和simple.sbt。当准备好后,我们就可以创建包含代码的JAR包,然后使用spark-submit脚本运行我们的程序。
# Your directory layout should look like this
$ find .
.
./simple.sbt
./src
./src/main
./src/main/scala
./src/main/scala/SimpleApp.scala
# Package a jar containing your application
$ sbt package
...
[info] Packaging {..}/{..}/target/scala-2.10/simple-project_2.10-1.0.jar
# Use spark-submit to run your application
$ YOUR_SPARK_HOME/bin/spark-submit \
--class "SimpleApp" \
--master local[4] \
target/scala-2.10/simple-project_2.10-1.0.jar
...
Lines with a: 46, Lines with b: 23
Where to Go from Here
- 更深入的概述:Spark programming guide。
- 在集群中运行applications,deployment overview.
- 最后,在examples目录中,Spark包含几个示例(Scala, Java, Python)。如下运行:
# For Scala and Java, use run-example:
./bin/run-example SparkPi
# For Python examples, use spark-submit directly:
./bin/spark-submit examples/src/main/python/pi.py