Github user cloud-fan commented on a diff in the pull request:
https://github.com/apache/spark/pull/6072#discussion_r30115116
--- 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 --
What if user mistakenly call `otherwise` twice? Then we will build a wrong
`CaseWhen` expression here. Maybe we should create a helper class like what we
did for NA functions and aggregate functions?
---
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]