2016-12-14 97 views
2

在星火SQL中使用JDBC数据源,我们尝试下面的查询运行火花 - NVL函数的数据类型不匹配错误

select nvl(columnName , 1.0) from tablename 

给出误差

cannot resolve 'nvl(tablename.`columnname`, 1.0BD)' due to data type mismatch: input to function coalesce should all be the same type, but it's [decimal(38,10), decimal(2,1)] 

我知道我们可以用

解决这个
select nvl(columnname , CAST(1.0 as decimal(38,10))) from tablename 

看起来像我需要找到每列的数据类型并投射到它。

  1. 有没有其他方法可以处理它?
  2. 我可以在加载数据框如csv格式时预先给出架构定义。 [https://issues.apache.org/jira/browse/SPARK-16848]
  3. 如何为每列转换加载的Dataframe数据类型。

回答

2
  1. 您可以在NVL上使用Coalesce。合并的输入被转换为“最佳”通用数据类型。
  2. JDBC连接使用数据库模式作为模式,所以不可能预先给出模式。
  3. 您可以通过添加另一个select投中的所有列到不同的数据类型,这是容易的数据帧/数据集的API:

    // Create some toy data. 
    val df = spark.range(100).select($"id", (rand(2) * 10).as("a")) 
    df.printSchema 
    
    // Define the casts. 
    val casts = Seq(col("id").cast("int"), col("a").cast("int")) 
    
    // Apply the casts. 
    df.select(casts: _*).printSchema 
    
+0

感谢您的答复。我明白第1点和第2点的答案,关于第3点'选择'行动的开销。 –

+0

'select'的开销很低(特别是当你使用代码生成时);它可能比在某些数据源中发生的转换更快。 –