Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to write if/else if/else if/else in HIVE?

Tags:

hql

hive

Hive uses IF(condition, expression, expression), so when I want to do if / else if / else if / else, I have to do:

IF(a, 1, IF(b, 2, IF(c, 3, 4)))

Is there a better way to do this that's more readable?

Looking for something similar to the standard

if (a) {
  1
} else if (b) {
  2
} else if (c) {
  3
} else {
  4
}
like image 974
Popcorn Avatar asked Sep 09 '15 06:09

Popcorn


People also ask

How do you write if else condition in Hive?

If condition/statement in Hive. Hive supports many conditional functions such as If, isnull, isnotnull, nvl, nullif, COALESCE and CASE. The If condition is used to validate the condition on the column values. In the if condition, we need to mention the true/false values to be returned.

What is NVL function in Hive?

Use nvl() function in Hive to replace all NULL values of a column with a default value, In this article, I will explain with an example. You can use this function to. Replace all NULL values with -1 or 0 or any number for the integer column. Replace all NULL values with empty space for string types.

IS NULL function in Hive?

An alternative to ISNULL() and NVL() functions in Hive This function accepts two arguments. If the first argument is null, then it returns the second argument. If the first argument is not null, it returns the first one and will ignore the second argument.


2 Answers

You can use Hive Conditional CASE WHEN function for if-else scenario. The CASE Statement will provide you better readability with the same functionality.

CASE
  WHEN (condition1) THEN result1
  WHEN (condition2) THEN result2
  WHEN (condition3) THEN result3 
  WHEN (condition4) THEN result4
  ELSE result_default 
END AS attribute_name
like image 172
YoungHobbit Avatar answered Sep 21 '22 06:09

YoungHobbit


You can easily achieve this using CASE WHEN statements.

CASE 
    WHEN a THEN 1
    WHEN b THEN 2
    WHEN c THEN 3
    ELSE 4
END AS attribute_name

For more information, refer official doc at https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-ConditionalFunctions

like image 39
Piyush Patel Avatar answered Sep 18 '22 06:09

Piyush Patel