在 expr() 中使用 lit()

Use of lit() in expr()

行:

df.withColumn("test", expr("concat(lon, lat)")) 

按预期工作但

df.withColumn("test", expr("concat(lon, lit(','), lat)"))

产生以下异常:

org.apache.spark.sql.AnalysisException: Undefined function: 'lit'. This function is neither a registered temporary function nor a permanent function registered in the database 'default'.; line 1 pos 12 at org.apache.spark.sql.catalyst.analysis.Analyzer$LookupFunctions$$anonfun$apply$$anonfun$applyOrElse.apply(Analyzer.scala:1198)

为什么?解决方法是什么?

expr will be parsed as a SQL expression and used to construct a column. Since lit 的字符串参数不是有效的 SQL 命令,这会给您一个错误。 (lit 在 Spark 中用于将文字值转换为新列。)

要解决这个问题,只需删除 lit 部分:

df.withColumn("test", expr("concat(lon, ',', lat)")) 

或者不用expr直接使用内置的Spark concat函数:

df.withColumn("test", concat($"lon", lit(","), $"lat"))

由于 concat 将列作为参数,因此必须在此处使用 lit