在spark sql中查找字符串中的字符索引

use*_*795 5 apache-spark-sql databricks

我是 SQL 人员,Spark SQL 新手

我需要找到字符索引“-”在字符串中的位置(如果存在)那么我需要将字符的固定长度设置为否则长度为零

string name = 'john-smith'
Run Code Online (Sandbox Code Playgroud)

如果 '-' 位于字符位置 4 则为 10,否则长度为 0

我已经在 SQL Server 中完成,但现在需要在 Spark SQL 中完成。

select 
case 
when charindex('-', name) = 4 then 10
else 0 
end 
Run Code Online (Sandbox Code Playgroud)

我在 Spark SQL 中尝试过,但未能得到结果。

select find_in_set('-',name) 
Run Code Online (Sandbox Code Playgroud)

请帮忙。谢谢

abi*_*sis 10

您可以使用instr如下所示的函数。insrt检查第二个字符串参数是否是第一个字符串参数的一部分。如果是,则返回从 1 开始的索引。

#first create a temporary view if you don't have one already
df.createOrReplaceTempView("temp_table")

#then use instr to check if the name contains the - char
spark.sql("select if(instr(name, '-') = 4, 10, 0) from temp_table")
Run Code Online (Sandbox Code Playgroud)

该声明的论点if是:

  • instr(name, '-') = 4检查条件
  • 10 个有效条件结果
  • 错误条件有 0 个结果