检查列数据类型,并仅在Spark SQL中的Integer和Decimal上执行SQL

sab*_*bby 3 scala apache-spark spark-streaming apache-spark-sql

我正在尝试从输入Parquet文件中检查列的数据类型,如果数据类型是Integer或Decimal,则运行Spark SQL.

//get Array of structfields 
 val datatypes = parquetRDD_subset.schema.fields

//Check datatype of column
 for (val_datatype <- datatypes)  if (val_datatype.dataType.typeName == "integer" || val_datatype.dataType.typeName.contains("decimal"))  
{
 //get the field name
val x = parquetRDD_subset.schema.fieldNames

 val dfs = x.map(field => spark.sql(s"select 'DataProfilerStats' as Table_Name,(SELECT 100 * approx_count_distinct($field)/count(1) from parquetDFTable) as Percentage_Unique_Value from parquetDFTable"))

 }
Run Code Online (Sandbox Code Playgroud)

问题是,尽管数据类型验证是成功的,但在获取字段名称之后的for循环中,它实际上并不是将列限制为整数或小数,而是对所有列类型甚至字符串执行查询.我们如何得到只有十进制或整数的字段.我们如何解决这个问题.

Sha*_*ala 6

这是您使用整数和双精度类型过滤列的方法

// fiter the columns 
val columns = df.schema.fields.filter(x => x.dataType == IntegerType || x.dataType == DoubleType)

//use these filtered with select 
df.select(columns.map(x => col(x.name)): _*)
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!