scala - 如何在 SPARK SQL 中使用 LEFT 和 RIGHT 关键字

标签 scala apache-spark apache-spark-sql

我是 spark SQL 的新手,

在 MS SQL 中,我们有 LEFT 关键字,LEFT(Columnname,1) in('D','A') then 1 else 0

如何在 SPARK SQL 中实现相同的功能。

最佳答案

你可以使用 substring 函数和正 pos 从左边取:

import org.apache.spark.sql.functions.substring

substring(column, 0, 1)

和负 pos 从右边取:

substring(column, -1, 1)

所以在Scala中你可以定义

import org.apache.spark.sql.Column
import org.apache.spark.sql.functions.substring

def left(col: Column, n: Int) = {
  assert(n >= 0)
  substring(col, 0, n)
}

def right(col: Column, n: Int) = {
  assert(n >= 0)
  substring(col, -n, n)
}

val df = Seq("foobar").toDF("str")

df.select(
  Seq(left _, right _).flatMap(f => (1 to 3).map(i => f($"str", i))): _*
).show
+--------------------+--------------------+--------------------+---------------------+---------------------+---------------------+
|substring(str, 0, 1)|substring(str, 0, 2)|substring(str, 0, 3)|substring(str, -1, 1)|substring(str, -2, 2)|substring(str, -3, 3)|
+--------------------+--------------------+--------------------+---------------------+---------------------+---------------------+
|                   f|                  fo|                 foo|                    r|                   ar|                  bar|
+--------------------+--------------------+--------------------+---------------------+---------------------+---------------------+

在 Python 中类似:

from pyspark.sql.functions import substring
from pyspark.sql.column import Column

def left(col, n):
    assert isinstance(col, (Column, str))
    assert isinstance(n, int) and n >= 0
    return substring(col, 0, n)

def right(col, n):
    assert isinstance(col, (Column, str))
    assert isinstance(n, int) and n >= 0
    return substring(col, -n, n)

关于scala - 如何在 SPARK SQL 中使用 LEFT 和 RIGHT 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40178951/

相关文章:

java - 在 Java/Scala 中重现 CouchDB 1.2.0 密码哈希函数

scala - 如何在 spark-shell 中注册 kryo 类

scala - 错误 : value is not a member of object using Scala on the shell

apache-spark - 在 Spark 中比较执行器之间的数据

python - PySpark:当函数具有多个输出时

scala - 在 Hadoop 上使用 Spark 运行 Scala 程序

scala - 如何在Scala控制台中使用宏?

python - 按行索引拆分 Spark 数据帧

hadoop - 将Hive转换为Spark

apache-spark-sql - 将宽数据帧转置为长数据帧