apache-spark - 子字符串类型不匹配中的 Spark Length 函数
问题描述
在 Spark 3.0.1、Scala 2.12 中,我得到了以下信息:
import spark.implicits._
import org.apache.spark.sql.functions._
Seq(("1987.01.01"))
.toDF("Input")
.select(
col("Input"),
to_date(col("Input"), "yyyy.M.d").as("format"),
length(col("Input")),
substring(col("Input"),1, length(col("Input")).cast("int")+0 )
).show()
command-1067744798817014:7: error: type mismatch;
found : org.apache.spark.sql.Column
required: Int
substring(col("Input"),1, length(col("Input")).cast("int")+0 )
^
所以我想我有错误的“长度”函数,通过隐式导入或其他什么?
这有效
Seq(("1987.01.01"))
.toDF("Input")
.select(
col("Input"),
to_date(col("Input"), "yyyy.M.d").as("format"),
length(col("Input"))
).show()
+----------+----------+-------------+
| Input| format|length(Input)|
+----------+----------+-------------+
|1987.01.01|1987-01-01| 10|
+----------+----------+-------------+
解决方案
substring
Scala API 中的方法只接受整数作为第二个和第三个参数。如果要传递列,则需要expr
使用 Spark SQL APIsubstring
方法:
Seq(("1987.01.01"))
.toDF("Input")
.select(
col("Input"),
to_date(col("Input"), "yyyy.M.d").as("format"),
length(col("Input")),
expr("substring(Input, 1, length(Input) + 0)")
).show()
+----------+----------+-------------+----------------------------------------+
| Input| format|length(Input)|substring(Input, 1, (length(Input) + 0))|
+----------+----------+-------------+----------------------------------------+
|1987.01.01|1987-01-01| 10| 1987.01.01|
+----------+----------+-------------+----------------------------------------+
推荐阅读
- intellij-idea - 如何编写 Intellij 插件来显示来自静态分析的 Python 类方法返回值(对于非常简单的表达式)?
- jupyter-notebook - 无法在 Windows 10 的 jupyter notebook 中启动 ocaml-jupyter 内核
- javascript - 关于 JavaScript 代理和 getter 函数的奇怪问题
- php - MAMP Pro 3.3.1 为 windows 用户添加新的 PHP 版本
- javascript - 何时使用 AbortController 移除事件监听器?
- c++ - CComPtr 分配是线程安全的吗?
- react-native - 从反应本机应用程序向 Auth0 api 发出请求
- html - 如何在 CSS3 网格中将一个单元格覆盖在其他两个单元格上
- java - 从 Flutter 调用 Java 代码会引发未处理的异常:MissingPluginException(未找到方法的实现...)
- javascript - 切换时不显示菜单