Github user rxin commented on a diff in the pull request:
https://github.com/apache/spark/pull/6072#discussion_r30169143
--- Diff: sql/core/src/main/scala/org/apache/spark/sql/Column.scala ---
@@ -309,6 +309,62 @@ class Column(protected[sql] val expr: Expression)
extends Logging {
def eqNullSafe(other: Any): Column = this <=> other
/**
+ * Evaluates a list of conditions and returns one of multiple possible
result expressions.
+ * If otherwise is not defined at the end, null is returned for
unmatched conditions.
+ *
+ * {{{
+ * // Example: encoding gender string column into integer.
+ *
+ * // Scala:
+ * people.select(when(people("gender") === "male", 0)
+ * .when(people("gender") === "female", 1)
+ * .otherwise(2))
+ *
+ * // Java:
+ * people.select(when(col("gender").equalTo("male"), 0)
+ * .when(col("gender").equalTo("female"), 1)
+ * .otherwise(2))
+ * }}}
+ *
+ * @group expr_ops
+ */
+ def when(condition: Column, value: Any):Column = this.expr match {
+ case CaseWhen(branches: Seq[Expression]) =>
+ CaseWhen(branches ++ Seq(lit(condition).expr, lit(value).expr))
+ case _ =>
+ throw new IllegalArgumentException(
+ "when() can only be applied on a Column previously generated by
when() function")
+ }
+
+ /**
+ * Evaluates a list of conditions and returns one of multiple possible
result expressions.
+ * If otherwise is not defined at the end, null is returned for
unmatched conditions.
+ *
+ * {{{
+ * // Example: encoding gender string column into integer.
+ *
+ * // Scala:
+ * people.select(when(people("gender") === "male", 0)
+ * .when(people("gender") === "female", 1)
+ * .otherwise(2))
+ *
+ * // Java:
+ * people.select(when(col("gender").equalTo("male"), 0)
+ * .when(col("gender").equalTo("female"), 1)
+ * .otherwise(2))
+ * }}}
+ *
+ * @group expr_ops
+ */
+ def otherwise(value: Any):Column = this.expr match {
+ case CaseWhen(branches: Seq[Expression]) =>
+ CaseWhen(branches :+ lit(value).expr)
--- End diff --
Good point. It is too heavy weight to have a whole class dedicated to this,
but I will add code to throw exceptions if otherwise has been applied
previously.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]