Spark SQL是处理结构化数据的Spark模块。它提供了DataFrames这样的编程抽象。同一时候也能够作为分布式SQL查询引擎使用。

DataFrames

DataFrame是一个带有列名的分布式数据集合。等同于一张关系型数据库中的表或者R/Python中的data frame,只是在底层做了非常多优化;我们能够使用结构化数据文件、Hive tables,外部数据库或者RDDS来构造DataFrames。

1. 開始入口:

入口须要从SQLContext类或者它的子类開始,当然须要使用SparkContext创建SQLContext;这里我们使用pyspark(已经自带了SQLContext即sc):

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

还能够使用HiveContext,它能够提供比SQLContext很多其它的功能。比如能够使用更完整的HiveQL解析器写查询,使用Hive UDFs。从Hive表中读取数据等。

使用HiveContext并不须要安装hive,Spark默认将HiveContext单独打包避免对hive过多的依赖

2.创建DataFrames

使用JSON文件创建:

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc) df = sqlContext.read.json("examples/src/main/resources/people.json") # Displays the content of the DataFrame to stdout
df.show()

注意:

这里你可能须要将文件存入HDFS(这里的文件在Spark安装文件夹中,1.4版本号)

hadoop fs -mkdir examples/src/main/resources/
hadoop fs -put /appcom/spark/examples/src/main/resources/* /user/hdpuser/examples/src/main/resources/

3.DataFrame操作

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc) # Create the DataFrame
df = sqlContext.read.json("examples/src/main/resources/people.json") # Show the content of the DataFrame
df.show()
## age name
## null Michael
## 30 Andy
## 19 Justin # Print the schema in a tree format
df.printSchema()
## root
## |-- age: long (nullable = true)
## |-- name: string (nullable = true) # Select only the "name" column
df.select("name").show()
## name
## Michael
## Andy
## Justin # Select everybody, but increment the age by 1
df.select(df['name'], df['age'] + 1).show()
## name (age + 1)
## Michael null
## Andy 31
## Justin 20 # Select people older than 21
df.filter(df['age'] > 21).show()
## age name
## 30 Andy # Count people by age
df.groupBy("age").count().show()
## age count
## null 1
## 19 1
## 30 1

4.使用编程执行SQL查询

SQLContext能够使用编程执行SQL查询并返回DataFrame。

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
df = sqlContext.sql("SELECT * FROM table")

5.和RDD交互

将RDD转换成DataFrames有两种方法:

  • 利用反射来判断包括特定类型对象的RDD的schema。这样的方法会简化代码而且在你已经知道schema的时候非常适用。
  • 使用编程接口。构造一个schema并将其应用在已知的RDD上。

一、利用反射判断Schema

Spark SQL能够将含Row对象的RDD转换成DataFrame。并判断数据类型。通过将一个键值对(key/value)列表作为kwargs传给Row类来构造Rows。

key定义了表的列名,类型通过看第一列数据来判断。

(所以这里RDD的第一列数据不能有缺失)未来版本号中将会通过看很多其它数据来判断数据类型。像如今对JSON文件的处理一样。

# sc is an existing SparkContext.
from pyspark.sql import SQLContext, Row
sqlContext = SQLContext(sc) # Load a text file and convert each line to a Row.
lines = sc.textFile("examples/src/main/resources/people.txt")
parts = lines.map(lambda l: l.split(","))
people = parts.map(lambda p: Row(name=p[0], age=int(p[1]))) # Infer the schema, and register the DataFrame as a table.
schemaPeople = sqlContext.createDataFrame(people)
schemaPeople.registerTempTable("people") # SQL can be run over DataFrames that have been registered as a table.
teenagers = sqlContext.sql("SELECT name FROM people WHERE age >= 13 AND age <= 19") # The results of SQL queries are RDDs and support all the normal RDD operations.
teenNames = teenagers.map(lambda p: "Name: " + p.name)
for teenName in teenNames.collect():
print teenName

二、编程指定Schema

通过编程指定Schema须要3步:

  1. 从原来的RDD创建一个元祖或列表的RDD。
  2. 用StructType 创建一个和步骤一中创建的RDD中元祖或列表的结构相匹配的Schema。

  3. 通过SQLContext提供的createDataFrame方法将schema 应用到RDD上。

# Import SQLContext and data types
from pyspark.sql import SQLContext
from pyspark.sql.types import * # sc is an existing SparkContext.
sqlContext = SQLContext(sc) # Load a text file and convert each line to a tuple.
lines = sc.textFile("examples/src/main/resources/people.txt")
parts = lines.map(lambda l: l.split(","))
people = parts.map(lambda p: (p[0], p[1].strip())) # The schema is encoded in a string.
schemaString = "name age" fields = [StructField(field_name, StringType(), True) for field_name in schemaString.split()]
schema = StructType(fields) # Apply the schema to the RDD.
schemaPeople = sqlContext.createDataFrame(people, schema) # Register the DataFrame as a table.
schemaPeople.registerTempTable("people") # SQL can be run over DataFrames that have been registered as a table.
results = sqlContext.sql("SELECT name FROM people") # The results of SQL queries are RDDs and support all the normal RDD operations.
names = results.map(lambda p: "Name: " + p.name)
for name in names.collect():
print name

Spark SQL and DataFrame Guide(1.4.1)——之DataFrames的更多相关文章

  1. Spark SQL 之 DataFrame

    Spark SQL 之 DataFrame 转载请注明出处:http://www.cnblogs.com/BYRans/ 概述(Overview) Spark SQL是Spark的一个组件,用于结构化 ...

  2. Spark SQL 之 Migration Guide

    Spark SQL 之 Migration Guide 支持的Hive功能 转载请注明出处:http://www.cnblogs.com/BYRans/ Migration Guide 与Hive的兼 ...

  3. spark结构化数据处理:Spark SQL、DataFrame和Dataset

    本文讲解Spark的结构化数据处理,主要包括:Spark SQL.DataFrame.Dataset以及Spark SQL服务等相关内容.本文主要讲解Spark 1.6.x的结构化数据处理相关东东,但 ...

  4. Spark SQL、DataFrame和Dataset——转载

    转载自:  Spark SQL.DataFrame和Datase

  5. 转】Spark SQL 之 DataFrame

    原博文出自于: http://www.cnblogs.com/BYRans/p/5003029.html 感谢! Spark SQL 之 DataFrame 转载请注明出处:http://www.cn ...

  6. Spark学习之路(八)—— Spark SQL 之 DataFrame和Dataset

    一.Spark SQL简介 Spark SQL是Spark中的一个子模块,主要用于操作结构化数据.它具有以下特点: 能够将SQL查询与Spark程序无缝混合,允许您使用SQL或DataFrame AP ...

  7. Spark 系列(八)—— Spark SQL 之 DataFrame 和 Dataset

    一.Spark SQL简介 Spark SQL 是 Spark 中的一个子模块,主要用于操作结构化数据.它具有以下特点: 能够将 SQL 查询与 Spark 程序无缝混合,允许您使用 SQL 或 Da ...

  8. Spark官方1 ---------Spark SQL和DataFrame指南(1.5.0)

    概述 Spark SQL是用于结构化数据处理的Spark模块.它提供了一个称为DataFrames的编程抽象,也可以作为分布式SQL查询引擎. Spark SQL也可用于从现有的Hive安装中读取数据 ...

  9. spark sql 创建DataFrame

    SQLContext是创建DataFrame和执行SQL语句的入口 通过RDD结合case class转换为DataFrame 1.准备:hdfs上提交一个文件,schema为id name age, ...

随机推荐

  1. Read UNIQUE ID and flash size method for stm32

    /* 读取stm32的unique id 与 flash size */ /* func: unsigned int Read_UniqueID_Byte(unsigned char offset) ...

  2. Photoshop的版本体系

    Photoshop CS6 和Photoshop CC的区别 没有什么玄乎的,仅仅是版本不一样. 版本的命名 Photoshop CS6 是CS系列的最后一版本, Adobe Photoshop CS ...

  3. windows下gVim(Vi/vim)基本使用

    Vim 是一个Linux 平台上功能非常强大的编辑器,他是早年的Vi 编辑器的加强版.这个gVim 是windows 版的,并且有了标准的windows 风格的图形界面,所以叫g(graphical) ...

  4. fmri资源站点

    1.  MRI analysis tutorials:http://www.mccauslandcenter.sc.edu/CRNL/wp-content/tools/tutorial/index.h ...

  5. 使用openURL实现程序间带参数跳转详解

    使用openURL实现程序间带参数跳转详解 实现的效果:有两款应用A与B,A打开B A --> B 1. 新建工程B,bundle ID为com.YouXianMing.B 建立一个URL 这么 ...

  6. Computer Vision Tutorials from Conferences (1) -- ICCV

    ICCV 2013 (http://www.iccv2013.org/tutorials.php) Don't Relax: Why Non-Convex Algorithms are Often N ...

  7. Python 字符串前面加'r'

    在Python的string前面加上‘r’, 是为了告诉编译器这个string是个raw string,不要转意backslash '\' . 例如,\n 在raw string中,是两个字符,\和n ...

  8. qt study 元对象,属性和反射编程

    所谓反射,就是指对象成员的自我检查,使用反射编程(reflective programming),就可以编写出通用的操作,可以对具有不同结构的类进行操作. QMetaObject 元对象模式,描述一个 ...

  9. GCD的基本概念

    GCD是苹果在OS X Snow Leopard跟iOS4后引入的一个技术,利用GCD,我们可以将多线程代码编写的很优雅.在使用GCD前,我们可以简章回顾下传统的多线程技术. int main() { ...

  10. 性能测试工具 nGrinder 项目剖析及二次开发

    转:https://testerhome.com/topics/4225 0.背景 组内需要一款轻量级的性能测试工具,之前考虑过LR(太笨重,单实例,当然它的地位是不容置疑的),阿里云的PTS(htt ...