SparkSQL

Chanllenges with Spark

  • Spark的核心API建立在RDD这一底层抽象上,要求开发者自己定义transformation和action
  • RDD API也允许开发者将任意函数传给transformation,这些函数被当作黑盒处理
  • 因此引擎对于操作语义的可见性有限,限制了优化器生成高效的执行计划
  • 储存的通用对象是任意的Java/Python对象,对象本身往往比其中的数据要大好几倍

Dateframe and RDD

  • Spark+RDD: 使用RDD对不透明对象的partitioned collection做函数式transformation
  • SQL+Dataframes(SchemaRDDs): 对tuples的partitioned collections做声明式transformations

SparkSQL Architecture

  • SparkSQL作为Apache Spark中的一个模块引入,用于提供类SQL的接口,直接构建在Spark核心引擎之上,借Spark的分布式计算能力来处理大规模数据
  • 新增了DataFrame和Catalyst(可扩展优化器)

DataFrame

  • 按照named columns组织起来的dataset,在概念上等价于relational database中的table

  • 在Spark中。Dataframe是惰性的,每个Dataframe对象代表一个用于计算数据集的逻辑计划(计算过程), 在output operation之前不会产生执行

Dataframe vs RDD

  • RDD: 使用Python/Java/Scala Transformation(map/reduce)交给JVM后端执行
  • SparkSQL: DataFrame API或者SQL query先转化为Logical plan,经过Catalyst改写产出Physical plan执行

Dataframe advantage

  • optimization execution: schema信息使得优化成为可能
  • built-in optimization: 使用catalyst优化器进一步优化,包括predictive pushdowns/constant folding/loop unrolling等solution进行自动优化,相较RDD执行效率更高
  • compact binary representation: 使用列式存储,optimization across operators(跨算子优化)
  • easy of use: 提供high-level, 类SQL的接口与数据交互, 比复杂的RDD变换更简化
  • integrated with the rest of spark: 集成在Spark中接入Spark生态
  • interoperability: 可以方便的与其他数据格式互转

Dataframe operations

  • 支持所有常见的relational operators: projection(select), filter(where), join, groupBy
  • example
employees.join(dept, employees.deptId == dept.id)   # Join condition
    .where(employees.gender == "female")            # Filter condition
    .groupBy(dept.id, dept.name)                    # Group by
    .agg(count("name").alias("employee_count"))
  • 通过AST(sbstract syntax tree)组合算子,而不是立即触发计算

Dataframe creation

  • 通过读取csv文件创建dataframe
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Create-Dataframe")
csv_file_path = "./data/products.csv"
df = spark.read.csv(csv_file_path, header=True)
df.printSchema()    #display schema of dataframe
df.show(5)    #display content of dataframe
df.columns()    #display columns
  • 也可以直接通过python对象创建dataframe
my_list = [["a",1],["b",2]]
df = spark.createDataFrame(my_list,["letter","number"])
df.show()

Select

  • 挑选并打印出指定的列
# Select specific columns
selected_columns = df.select("id", "name", "price")
print("Selected Columns:")
selected_columns.show(10)

Filter

  • 施加条件筛选行
#Filter rows based on a condition
filtered_data = df.filter(df.quantity>20)
print("Filtered Data: ",filtered_data.count())
filtered_data.show()

GroupBy and Aggregations

  • 聚合
# GroupBy and Aggregations
grouped_data = df.groupBy("category").agg({"quantity": "sum", "price": "avg"})
print("Grouped and Aggregated Data:")
grouped_data.show()

toDF

  • 根据已有的Dataframe创建新的Dataframe
  • 此处取name和price两列改名为pname和price of product再显示前五行
  • df.select('name','price').toDF('pname','price of product').show(5)

Join

  • 按照指定的列把多个DataFrame组合起来
# Join with another DataFrame
df2 = df.select("id", "category").limit(10)
joined_data = df.join(df2, "id", "inner")
print("Joined Data:")
joined_data.show()

Sort

  • 顺序排列orderBy()
# sort by a column
sorted_data = df.orderBy("price")
print("Sorted Data:")
sorted_data.show(10)
  • 倒序排列同样使用orderBy()
  • 使用desc()表示倒序(需要从pyspark.sql.functions中import)
  • 但倒序有两种不同的表示
    • orderBy(desc("col1"))
    • orderBy(col("col2").desc())
# sort by a column desc
from pyspark.sql.functions import col,desc
sorted_data = df.orderBy(col("price").desc(),col("id").desc())
print("Sorted Data Descending:")
sorted_data.show(10)

Distinct

  • 取出不重复的行, 使用distinct()
# get distinct product category
distinct_rows = df.select("category").distinct()
print("Distinct Product Categoryies")
distinct_rows.show()

Drop

  • 移除指定的列, drop()
  • 由于dataframe是不可变的,因此此处的drop只是屏蔽列的显示,并不是删除
# drop column
dropped_column = df.drop("category")
print("dropped column")
dropped_column.show(10)

WithColumn

  • 添加新计算出来的列,常用于表示平均值/总和
# add a new calculated column
df_with_new_column = df.withColumn("sum",df.quantity*df.price)
print("Data frame with new column")
df_with_new_column.show(10)

Alias

  • 将列改名,常用withColumnRenamed
#rename columns using alias
df_with_alias = df.withColumnRenamed("old name","new name")
print("DataFrame with Aliased Column:")
df_with_alias.show(10)

Map

DataFrame to RDD

  • RDD可以转化为Dataframe. 反过来也可以将DataFrame变成RDD
data_file_path = "./data/stocks.txt"
df = spark.read.csv(data_file_path, header = True, interSchema = True)
df_rdd = df.rdd
df_rdds.take(5)

map() and mapValue()

  • map()将函数作用到RDD的每一个元素上,也就是说每个元素必须都是该函数所能接受的合法输入,返回的RDD以函数作用到元素上的输出作为他的新元素
  • mapValue()与map()不同,它要求RDD中的每个元素都具有键值对结构,并且mapValue()只会将函数作用到每个元素的值上
# retrieve the 'name' and 'quantity' columns from df
df_rdds_map = df_rdds.map(lambda x:(x['name'],x['quantity']))
print('map:\n',df_rdd_map.take(5),'\n')
 
#multiply each value in 'quantity' by 10
df_rdds_mapvalues = df_rdds_map.mapValues(lambda x: [x,x*10])
print('mapvalues:\n',df_rdd_mapvalue.take(5),'\n')

flatMapValues()

  • flatMapValue()将输入的元素转变为多个输出,例如将value列表中的值拆出将一个键值对变成多个键值对
  • flatMap()则相反,会将输出压缩,总是只有1个输出
# multiply each value in 'quantity' by 10
df_rdds_mapvalues = df_rdds_map.mapValues(lambda x: [x, x*10])
print('MapValues: \n', df_rdds_mapvalues.take(5), '\n')
 
#同样对df_rdds_map操作,但把mapvalue换成flatmapvalue
df_rdds_mapvalues = df_rdds_map.flatMapValues(lambda x: [x, x*10])
print('FlatMapValues: \n', df_rdds_mapvalues.take(5), '\n')
MapValues:
  [('iPhone', [10, 100]), ('Macbook', [5, 50]), ('iPad', [15, 150]), ('Samsung TV', [8, 80]), ('LG TV', [10, 100])]
 
FlatMapValues:
  [('iPhone', 10), ('iPhone', 100), ('Macbook', 5), ('Macbook', 50), ('iPad', 15)]

Merge Columns

  • 当需要将多列合并成一列或是将一列拆成多列时,可以先将dataframe转为RDD, 使用map()进行合并/拆分再转回dataframe
from pyspark,sql import Row
df_rdd_map = df_rdds_map(lambda x: Row(product = x[1],values = x[2:]))
# 此处将index=2后的元素全部合并进了values中
df_rdd_map.take(5)

链接