06 Spark SQL 及其DataFrame的基本操作

06 Spark SQL 及其DataFrame的基本操作

 

1.Spark SQL出现的 原因是什么?

由于MapReduce这种计算模型执行效率比较慢,所以Spark SQL的应运而生,它是将Spark SQL转换成RDD,然后提交到集群执行,执行效率非常快,同时Spark SQL也支持从Hive中读取数据。

2.用spark.read 创建DataFrame

3.观察从不同类型文件创建DataFrame有什么异同?

4.观察Spark的DataFrame与Python pandas的DataFrame有什么异同?

在工作方式上,Pandas不支持Hadoop,处理大量数据有瓶颈,而Spark支持Hadoop,能处理大量数据;在内存缓存上,Pandas是单机缓存的,Spark是用persist() or cache()将转换的RDDs保存在内存;在DataFrame可变性上,Pandas中DataFrame是可变的,而Spark中RDDs是不可变的,因此DataFrame也是不可变的;在index索引上,Pandas是自动创建的,而Spark没有index索引,若需要则需要额外创建该列;

Spark SQL DataFrame的基本操作

创建:

spark.read.text()

file='file:///usr/local/spark/examples/src/main/resources/people.txt'
df = spark.read.text(file)

spark.read.json()

file='file:///usr/local/spark/examples/src/main/resources/people.json'
df = spark.read.json(file)

打印数据

df.show()默认打印前20条数据,df.show(n)

text:

json:

打印概要

df.printSchema()

text:

json:

查询总行数

df.count()

df.head(3) #list类型,list中每个元素是Row类

text:

json:

输出全部行

df.collect() #list类型,list中每个元素是Row类

text:

json:

查询概况

df.describe().show()

text:

json:

取列

df[‘name’]

df.name

df.select()

df.select(df['name']).show()

df.filter()

df.filter(df.age>20).show()

df.groupBy()

df.groupBy('age').count().show()

df.sort()

df.sort(df['age']).show()

posted @ 2021-05-19 23:09  Fk020306  阅读(53)  评论(0编辑  收藏  举报