关于Spark Dataset API中的Typed transformations和Untyped transformations

版权声明:欢迎转载,注明出处即可 https://blog.csdn.net/yolohohohoho/article/details/88624894

前言

学习Spark源代码的过程中遇到了Typed transformations和Untyped transformations两个概念,整理了以下相关的笔记。
对于这两个概念,不知道怎么翻译好,个人理解为强类型转换和弱类型转换,也不知道对不对,欢迎各位大神指正。

关于Dataset

Dataset是特定领域对象(domain-specific object)的强类型集合,它可以使用函数或关系运算进行并行转换。 每个Dataset还有一个名为DataFrame的弱类型视图,相当于Dataset[Row]
对于Spark(Scala),DataFrames只是类型为Row的Dataset。 “Row”类型是Spark中用于计算的,优化过的,in-memory的一种内部表达。

Dataset上可用的操作分为 转换(transformation)执行(action) 两种。

  • Transformation操作可以产生新的Dataset,如map,filter,select和aggregate(groupBy)等。
  • Action操作触发计算和返回结果。 如count,show或写入文件系统等。

关于Dataset API

Typed and Un-typed APIs

实质上,在Saprk的结构化API中,可以分成两类,“无类型(untyped)”的DataFrame API和“类型化(typed)”的Dataset API。
确切的说Dataframe并不是”无类型”的, 它们有类型,只是类型检查没有那么严格,只检查这些类型是否在 运行时(run-time) 与schema中指定的类型对齐。
而Dataset在 编译时(compile-time) 就会检查类型是否符合规范。

Dataset API仅适用于 基于JVM的语言(Scala和Java)。我们可以使用Scala 中的case class或Java bean来进行类型指定。

关于不同语言中的可用API可参考下表。

Language Main Abstraction
Scala Dataset[T] & DataFrame (alias for Dataset[Row])
Java Dataset[T]
Python* DataFrame
R* DataFrame

由于Python和R没有compile-time type-safety,因此只有 Untyped API,即DataFrames。

关于Transformations

转换(transformation)可以被分为:

  • 强类型转换(Typed transformations)
  • 弱类型转换(Untyped transformations)

Typed transformations vs Untyped transformations

简单来说,如果转换是弱类型的,它将返回一个Dataframe(确切的说弱类型转换的返回类型还有 Column, RelationalGroupedDataset, DataFrameNaFunctionsDataFrameStatFunctions),而强类型转换返回的是一个Dataset。
在源代码中,我们可以看到弱类型转换API的返回类型是Dataframe而不是Dataset,且带有@group untypedrel的注释。 因此,我们可以通过检查该方法的签名来确定它是否是弱类型的(untyped)。

强类型转换API带有@group typedrel的注释

例如Dataset.scala类中的join方法就属于弱类型转换(untyped transformations).

  /**
   * Join with another `DataFrame`.
   *
   * Behaves as an INNER JOIN and requires a subsequent join predicate.
   *
   * @param right Right side of the join operation.
   *
   * @group untypedrel
   * @since 2.0.0
   */
  def join(right: Dataset[_]): DataFrame = withPlan {
    Join(logicalPlan, right.logicalPlan, joinType = Inner, None, JoinHint.NONE)
  }

总结

通常,任何更改Dataset列类型或添加新列的的转换是弱类型。 当我们需要修改Dataset的schema时,我们就需要退回到Dataframe进行操作。

参考资料

Structured API Overview
Difference-between-Typed-and-untyped-transformation-in-dataset-API
RDDs vs DataFrames and Datasets
spark-sql-dataset-operators
org.apache.spark.sql.Dataset

猜你喜欢

转载自blog.csdn.net/yolohohohoho/article/details/88624894