【问题标题】:Using custom classes in Spark on datasets and dataframes在数据集和数据帧上使用 Spark 中的自定义类
【发布时间】:2021-06-16 23:48:56
【问题描述】:

我整理了一些我想用作本地数据类型的自定义类是 SparkSQL。我看到 UDT 刚刚向公众开放,但它们很难弄清楚。有什么办法可以做到吗?

示例

case class IPv4(ipAddress: String){
  // IPv4 converted to a number
  val addrL: Long = IPv4ToLong(ipAddress)
}

// Will read in a bunch of random IPs in the form {"ipAddress": "60.80.39.27"}
val IPv4DF: DataFrame = spark.read.json(path)
IPv4DF.createOrReplaceTempView("IPv4")

spark.sql(
    """SELECT *
     FROM IPv4
     WHERE ipAddress.addrL > 100000"""
    )

【问题讨论】:

    标签: scala apache-spark serialization apache-spark-sql user-defined-types


    【解决方案1】:

    您可以构造一个Dataset 并使用案例类addrL 属性进行过滤:

    case class IPv4(ipAddress: String){
      // IPv4 converted to a number
      val addrL: Long = IPv4ToLong(ipAddress)
    }
    
    val ds = Seq("60.80.39.27").toDF("ipAddress").as[IPv4]
    
    ds.filter(_.addrL > 100000).show
    +-----------+
    |  ipAddress|
    +-----------+
    |60.80.39.27|
    +-----------+
    

    【讨论】:

      猜你喜欢
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 2020-04-23
      • 2021-02-16
      • 2017-03-28
      • 1970-01-01
      相关资源
      最近更新 更多