spark1.1.0下使用SparkSQL

spark1.1.0的安装参见http://blog.csdn.net/bluejoe2000/article/details/41391407

安装了spark之后,可以在 shell中执行Spark SQL。Spark SQL是支持在Spark中使用Sql、HiveSql、Scaca中的关系型查询表达式。它的核心组件是一个新增的RDD类型SchemaRDD,它把行对象用一个Schema来描述行里面的所有列的数据类型,它就像是关系型数据库里面的一张表。它可以从原有的RDD创建,也可以是Parquet文件,最重要的是它可以支持用HiveQL从hive里面读取数据。

首先查看下数据文件:

cat ./examples/src/main/resources/people.txt
Michael, 29
Andy, 30
Justin, 19

Spark SQL测试:

val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlContext._
case class Person(name: String, age: Int)
val people = sc.textFile("examples/src/main/resources/people.txt").map(_.split(",")).map(p => Person(p(0), p(1).trim.toInt))
people.registerAsTable("people")
val teenagers = sql("SELECT name FROM people WHERE age >= 13 AND age <= 19")
teenagers.map(t => "Name: " + t(0)).collect().foreach(println)

shell将输出:

14/11/23 16:28:07 INFO SparkContext: Job finished: collect at <console>:20, took 0.377845624 s
Name: Justin


HiveQL测试:

val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)
import hiveContext._
hql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING)")
hql("LOAD DATA LOCAL INPATH 'examples/src/main/resources/kv1.txt' INTO TABLE src")
hql("SELECT count(*) FROM src").collect().foreach(println)
hql("SELECT key, value FROM src WHERE key>200 and key<300 order by key asc").collect().foreach(println)


你可能感兴趣的:(spark1.1.0下使用SparkSQL)