DataFrame的目标是让开发大数据的并行程序更加简单,受众更加广泛。DF受R & Python(Pandas)启发,被设计成支持 Big Data & Data Science Application. 作为RDD API的扩展,他的特性如下:
* 高扩展性
* 广泛支持各种数据格式 & 存储系统
* Spark Sql Catalyst Optimizer提供执行优化和代码生成
* 和其他大数据工具和框架的无缝集成
* 支持Python, java, scala, R(SparkR) Api
什么是DataFrame
In Spark,DF 是一个通过列组织起来的分布式数据集合,它类似传统数据库的一个表。可以通过各种方式构建DF:stuctured File(json,parquet…), tables in Hive, external DB, or existing RDDs.
example:
# Constructs a DataFrame from the users table in Hive.
users = context.table("users")
# from JSON files in S3
logs = context.load("s3n://path/to/data.json", "json")
怎么使用DataFrame
创建DF之后,它针对分布式数据操作提供了一套domain-specific language支持。
example:
# Create a new DataFrame that contains “young users” only
young = users.filter(users.age < 21)
# Alternatively, using Pandas-like syntax
young = users[users.age < 21]
# Increment everybody’s age by 1
young.select(young.name, young.age + 1)
# Count the number of young users by gender
young.groupBy("gender").count()
# Join young users with another DataFrame called logs
young.join(logs, logs.userId == users.userId, "left_outer")
与spark sql集成的操作:
young.registerTempTable("young")
context.sql("SELECT count(*) FROM young")
与Pandas的相互转换
# Convert Spark DataFrame to Pandas
pandas_df = young.toPandas()
# Create a Spark DataFrame from Pandas
spark_df = context.createDataFrame(pandas_df)
DF的执行也是lazy的,这样执行可以进行各种优化: predict push-down & bytecode generation. 并且DF在集群中也是并行执行的。
支持的数据格式和数据源
支持的数据格式如下:
通过Spark Sql external data source API, DF 可以执行任意的第三方数据格式/数据源。比如:Avro, CSV, ES, Hbase, Cassandra….
支持各种数据源和数据格式后, DF可以将各种不同源的数据组合到一起,如下所示:
users = context.jdbc("jdbc:postgresql:production", "users")
logs = context.load("/path/to/traffic.log")
logs.join(users, logs.userId == users.userId, "left_outer") \
.groupBy("userId").agg({"*": "count"})
典型运用:Advanced Analysis & Machine Learning
与Machine Learning集成
// 构建 ML Pipeline
tokenizer = Tokenizer(inputCol="text", outputCol="words")
hashingTF = HashingTF(inputCol="words", outputCol="features")
lr = LogisticRegression(maxIter=10, regParam=0.01)
pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])
// 与DF 一起使用
df = context.load("/path/to/data")
model = pipeline.fit(df)
高级分析:
df = context.load("/path/to/people.json")
# RDD-style methods such as map, flatMap are available on DataFrames
# Split the bio text into multiple words.
words = df.select("bio").flatMap(lambda row: row.bio.split(" "))
# Create a new DataFrame to count the number of words
words_df = words.map(lambda w: Row(word=w, cnt=1)).toDF()
word_counts = words_df.groupBy("word").sum()
背后实现:Intelligent Optimization & Code Generation
DF会利用spark sql的执行引擎Catalyst optimizer来进行执行优化。主要体现在两点:
- 执行逻辑优化,比如PPD
- 编译成物理执行计划并生成JVM Bytecode. 比如自动选择broadcast join还是shuffle join.
DF执行逻辑直接编译成 JVM Bytecode的对比测试: