scala - 在 DataFrame 上定义自定义方法的最佳方法是什么?

标签 scala apache-spark apache-spark-sql

我需要在 DataFrame 上定义自定义方法。什么是更好的方法?该解决方案应该是可扩展的,因为我打算定义大量的自定义方法。

我目前的方法是用 MyClass 创建一个类(比如 DataFrame )作为参数,在其中定义我的自定义方法(比如 customMethod )并定义一个隐式方法来转换 DataFrameMyClass .

implicit def dataFrametoMyClass(df: DataFrame): MyClass = new MyClass(df)

因此我可以调用:
dataFrame.customMethod()

这是正确的方法吗?打开建议。

最佳答案

你的方式就是要走的路(见[1])。尽管我解决的方法略有不同,但方法保持相似:

可能性 1

隐含

object ExtraDataFrameOperations {
  object implicits {
    implicit def dFWithExtraOperations(df: DataFrame) = DFWithExtraOperations(df)
  }
}

case class DFWithExtraOperations(df: DataFrame) {
  def customMethod(param: String) : DataFrame = {
    // do something fancy with the df
    // or delegate to some implementation
    //
    // here, just as an illustrating example: do a select
    df.select( df(param) )
  }
}

用法

使用新customMethod DataFrame 上的方法:
import ExtraDataFrameOperations.implicits._
val df = ...
val otherDF = df.customMethod("hello")

可能性2

而不是使用 implicit method (见上文),你也可以使用 implicit class :

隐式类
object ExtraDataFrameOperations {
  implicit class DFWithExtraOperations(df : DataFrame) {
     def customMethod(param: String) : DataFrame = {
      // do something fancy with the df
      // or delegate to some implementation
      //
      // here, just as an illustrating example: do a select
      df.select( df(param) )
    }
  }
}

用法
import ExtraDataFrameOperations._
val df = ...
val otherDF = df.customMethod("hello")

备注

如果您想阻止额外的 import ,转object ExtraDataFrameOperationspackage object并将其存储在名为 package.scala 的文件中在您的包裹内。

官方文档/引用

[1] M. Odersky 的原始博客“Pimp my library”位于 http://www.artima.com/weblogs/viewpost.jsp?thread=179766

关于scala - 在 DataFrame 上定义自定义方法的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32585670/

相关文章:

scala - 模式匹配中的小写变量

Scala:过滤器强制评估整个流

java - 如何将每个 RDD 分区限制为仅 'n' 条记录?

python-2.7 - 使用最后两列作为分区将 Spark 数据帧转换为 pyspark 中的配置单元分区创建表

python - 如何为 python/pyspark 数据帧中的所有列添加后缀和前缀

scala - 在 Scala 中将嵌套案例类转换为嵌套映射

scala - 为什么 Scala 编译器不使用抽象类型推断类型

scala - 为什么 Spark 应用程序以 "ClassNotFoundException: Failed to find data source: jdbc"作为带有 sbt 程序集的 uber-jar 失败?

java - Spark : reduce causes StackOverflowError

apache-spark - Spark SQL 如何优化连接?有哪些优化技巧?