Scala 如何使用 sqlContext 在查询中处理 isnull 或 ifnull



我有两个数据文件,如下所示:

course.txt 
id,course 
1,Hadoop
2,Spark
3,HBase
5,Impala
Fee.txt 
id,amount 
2,3900
3,4200
4,2900

我需要列出所有课程信息及其费用:

sqlContext.sql("select c.id, c.course, f.amount from course c left outer join fee f on f.id = c.id").show
+---+------+------+
| id|course|amount|
+---+------+------+
|  1|Hadoop|  null|
|  2| Spark|3900.0|
|  3| HBase|4200.0|
|  5|Impala|  null|
+---+------+------+

如果课程未在费用表中显示,则我想显示"N/A",而不是显示空。

我已经尝试了以下方法,但尚未得到:

命令 1:

sqlContext.sql("select c.id, c.course, ifnull(f.amount, 'N/A') from course c left outer join fee f on f.id = c.id").show

错误:org.apache.spark.sql.AnalysisException:未定义的函数 ifnull;第 1 行 pos 40

命令 2:

sqlContext.sql("select c.id, c.course, isnull(f.amount, 'N/A') from course c left outer join fee f on f.id = c.id").show

错误:org.apache.spark.sql.AnalysisException: 没有处理程序 for Hive udf class org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPNull 因为: 运算符 'IS NULL' 只接受 1 个参数..;1号线 POS 40

在 Scala 中的 sqlContext 中处理这个问题的正确方法是什么?谢谢。

使用 Spark DataFrame API,您可以将when/otherwiseisNull条件一起使用:

val course = Seq(
  (1, "Hadoop"),
  (2, "Spark"),
  (3, "HBase"),
  (5, "Impala")
).toDF("id", "course")
val fee = Seq(
  (2, 3900),
  (3, 4200),
  (4, 2900)
).toDF("id", "amount")
course.join(fee, Seq("id"), "left_outer").
  withColumn("amount", when($"amount".isNull, "N/A").otherwise($"amount")).
  show
// +---+------+------+
// | id|course|amount|
// +---+------+------+
// |  1|Hadoop|   N/A|
// |  2| Spark|  3900|
// |  3| HBase|  4200|
// |  5|Impala|   N/A|
// +---+------+------+

如果你更喜欢使用Spark SQL,这里有一个等效的SQL:

course.createOrReplaceTempView("coursetable")
fee.createOrReplaceTempView("feetable")
val result = spark.sql("""
  select
    c.id, c.course,
    case when f.amount is null then 'N/A' else f.amount end as amount
  from
    coursetable c left outer join feetable f on f.id = c.id
""")

如果是 Spark SQL,请使用合并 UDF

select 
  c.id, 
  c.course, 
  coalesce(f.amount, 'N/A') as amount 
from c 
left outer join f 
on f.id = c.id"

您可以使用ifisnull函数和 N/A 文字简单的 sql 查询中按如下方式执行此操作

course.createOrReplaceTempView("c")
fee.createOrReplaceTempView("f")
sqlContext.sql("select c.id, c.course, if(isnull(f.amount), 'N/A', f.amount) as amount from c left outer join f on f.id = c.id").show

您应该具有以下输出

+---+------+------+
| id|course|amount|
+---+------+------+
|  1|Hadoop|   N/A|
|  2| Spark|  3900|
|  3| HBase|  4200|
|  5|Impala|   N/A|
+---+------+------+

我希望答案对您有所帮助

使用 DataFrameNA 函数。联接完成后,可以使用 DataFrameNA 填充函数将所有空值替换为字符串

https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/sql/DataFrameNaFunctions.html

在sqlContext中,使用"NVL">

sqlContext.sql("""   
   SELECT c.id
      ,c.course
      ,NVL(f.amount, 'N/A')
      FROM course c
      LEFT OUTER
      JOIN fee f 
      ON f.id = c.id
    """).show()

最新更新