【问题标题】:scala spark check fields dataTypescala火花检查字段数据类型
【发布时间】:2021-01-23 07:06:06
【问题描述】:

我只是想检查一个数据框的字段类型,所以我不得不写这个函数;

import scala.refelect.runtime.universe.TypeTag

import org.apache.spark.sql.DataFrame

def colCheck[T:TypeTag](data:DataFrame,colName:String):Boolean={
data.schema.exists(f->f.name==colName&f.dataType.isInstanceOf[T]
}

例如:data.schema.head 是StringType,名称是col1

我用 spark-shell 做这个

import org.apache.spark.sql.types.{IntegerType,StringType}

val data:DataFrame=spark.createDataFrame(List(("",1),("",2))).toDF("col1","col2")



data.schema.head.dataType.isInstanceOf[StringType]

> :Boolean =true  # write result


data.schema.head.dataType.isInstanceOf[IntegerType]

> :Boolean =false    # write result

colChek[IntegerType](data,"col1")

> :Boolean =true

我的预期是

colChek[IntegerType](data,"col1")

> :Boolean =false

colChek[StringType](data,"col1")

> :Boolean =false

但我得到了这个


colChek[IntegerType](data,"col1")

> :Boolean =true

这是什么原因造成的,如何解决,非常感谢

版本 火花2.4.5 scala的版本是2.11.12

【问题讨论】:

  • 您能否具体说明问题是什么以及您期望的输出是什么
  • 我已经更新了我的问题,非常感谢

标签: scala apache-spark apache-spark-sql


【解决方案1】:

您应该只传入IntegerType 作为值参数而不是类型参数,然后使用== 而不是isInstanceOf 进行比较。

import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.types.DataType

def colCheck(data: DataFrame, colName: String, tpe: DataType): Boolean =
  Option(data.schema(colName)).exists(_.dataType == tpe)
colCheck(df, "col1", IntegerType)

【讨论】:

    【解决方案2】:

    您需要避免如this answer 中所述的类型擦除:

    import scala.reflect.{classTag, ClassTag}
    import org.apache.spark.sql.DataFrame
    import org.apache.spark.sql.types.{DataType, IntegerType, StringType}
    
    def colCheck[T: ClassTag](data: DataFrame, colName: String): Boolean = {
        data.schema.exists(
            f => f.name == colName & classTag[T].runtimeClass.isInstance(f.dataType)
        )
    }
    
    val data: DataFrame = spark.createDataFrame(List(("",1),("",2))).toDF("col1","col2")
    
    colCheck[IntegerType](data, "col1")   // false
    colCheck[IntegerType](data, "col2")   // true
    colCheck[StringType](data, "col1")    // true
    colCheck[StringType](data, "col2")    // false
    

    【讨论】:

    • 它有效,如果 ArrayType 检查,它只适用于 colCheck[ArrayTyep](data,"cola"),如果我需要检查指定类型 colCheck[ArrayType(IntegerType,false)](data,"cola") 怎么办
    • @SummersKing 然后你可以使用其他答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 2016-05-01
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    相关资源
    最近更新 更多