Table of Contents

**Hive Built In Functions**

Functions in Hive are categorized as below.

**Mathematical Functions:**These functions mainly used to perform mathematical calculations.**Date Functions:**These functions are used to perform operations on date data types like adding the number of days to the date etc.**String Functions:**These functions are used to perform operations on strings like finding the length of a string etc.**Conditional Functions:**These functions are used to test conditions and returns a value based on whether the test condition is true or false.**Collection Functions:**These functions are used to find the size of the complex types like array and map. The only collection function is SIZE. The SIZE function is used to find the number of elements in an array and map. The syntax of SIZE function is

1 2 |
SIZE(Array<A> ) and SIZE( MAP<key,value> ) |

**Type Conversion Function:**This function is used to convert from one data type to another. The only type conversion function is CAST. The syntax of CAST is

1 2 |
CAST(expr as <type> ) |

The CAST function converts the expr into the specified type.

**Table Generating Functions:**These functions transform a single row into multiple rows. EXPLODE is the only table generated function. This function takes array as an input and outputs the elements of array into separate rows. The syntax of EXPLODE is

1 2 |
EXPLODE(ARRAY<A> ) |

## Mathematical Functions

The Numerical functions are listed below in alphabetical order. Use these functions in SQL queries.

Return Type |
Name(Signature) |
Example |
---|---|---|

BIGINT | round(double a) | Returns the rounded BIGINT value of the double |

DOUBLE | round(double a, int d) | Returns the double rounded to d decimal places |

BIGINT | floor(double a) | Returns the maximum BIGINT value that is equal or less than the double |

BIGINT | ceil(double a), ceiling(double a) | Returns the minimum BIGINT value that is equal or greater than the double |

double | rand(), rand(int seed) | Returns a random number (that changes from row to row) that is distributed uniformly from 0 to 1. Specifiying the seed will make sure the generated random number sequence is deterministic. |

double | exp(double a) | Returns ea where e is the base of the natural logarithm |

double | ln(double a) | Returns the natural logarithm of the argument |

double | log10(double a) | Returns the base-10 logarithm of the argument |

double | log2(double a) | Returns the base-2 logarithm of the argument |

double | log(double base, double a) | Return the base “base” logarithm of the argument |

double | pow(double a, double p), power(double a, double p) | Return a to the power of p value |

double | sqrt(double a) | Returns the square root of a |

string | bin(BIGINT a) | Returns the number in binary format |

string | hex(BIGINT a) hex(string a) | If the argument is an int, hex returns the number as a string in hex format. Otherwise if the number is a string, it converts each character into its hex representation and returns the resulting string. |

string | unhex(string a) | Inverse of hex. Interprets each pair of characters as a hexidecimal number and converts to the character represented by the number. |

string | conv(BIGINT num, int from_base, int to_base), conv(STRING num, int from_base, int to_base) | Converts a number from a given base to another |

double | abs(double a) | Returns the absolute value |

int double | pmod(int a, int b) pmod(double a, double b) | Returns the positive value of a mod b |

double | sin(double a) | Returns the sine of a (a is in radians) |

double | asin(double a) | Returns the arc sin of x if -1<=a<=1 or null otherwise |

double | cos(double a) | Returns the cosine of a (a is in radians) |

double | acos(double a) | Returns the arc cosine of x if -1<=a<=1 or null otherwise |

tan(double a) | tan(double a) | Returns the tangent of a (a is in radians) |

double | atan(double a) | Returns the arctangent of a |

double | degrees(double a) | Converts value of a from radians to degrees |

double | radians(double a) | Converts value of a from degrees to radians |

int double | positive(int a), positive(double a) | Returns a |

int double | negative(int a), negative(double a) | Returns -a |

float | sign(double a) | Returns the sign of a as ‘1.0’ or ‘-1.0? |

double | e() | Returns the value of e |

double | ABS( double n ) | Returns the absolute value of a number |

double | pi() | Returns the value of pi |

## Date Functions

Date data types do not exist in Hive. In fact the dates are treated as strings in Hive. The date functions are listed below. Link for complete details on Date Functions —> Link

**String Functions**

Return Type |
Name(Signature) |
Example |
---|---|---|

int | ascii(string str) | Returns the numeric value of the first character of str |

string | concat(string|binary A, string|binary B…) | Returns the string or bytes resulting from concatenating the strings or bytes passed in as parameters in order. e.g. concat(‘foo’, ‘bar’) results in ‘foobar’. Note that this function can take any number of input strings. |

array<struct<string,double>> | context_ngrams(array<array>, array, int K, int pf) | Returns the top-k contextual N-grams from a set of tokenized sentences, given a string of “context”. See StatisticsAndDataMining for more information. |

string | concat_ws(string SEP, string A, string B…) | Like concat() above, but with custom separator SEP. |

string | concat_ws(string SEP, array) | Like concat_ws() above, but taking an array of strings. (as of Hive 0.9.0) |

int | find_in_set(string str, string strList) | Returns the first occurance of str in strList where strList is a comma-delimited string. Returns null if either argument is null. Returns 0 if the first argument contains any commas. e.g. find_in_set(‘ab’, ‘abc,b,ab,c,def’) returns 3 |

string | format_number(number x, int d) | Formats the number X to a format like ‘#,###,###.##’, rounded to D decimal places, and returns the result as a string. If D is 0, the result has no decimal point or fractional part. (as of Hive 0.10.0) |

string | get_json_object(string json_string, string path) | Extract json object from a json string based on json path specified, and return json string of the extracted json object. It will return null if the input json string is invalid.NOTE: The json path can only have the characters [0-9a-z_], i.e., no upper-case or special characters. Also, the keys *cannot start with numbers.* This is due to restrictions on Hive column names. |

boolean | in_file(string str, string filename) | Returns true if the string str appears as an entire line in filename. |

int | instr(string str, string substr) | Returns the position of the first occurence of substr in str |

int | length(string A) | Returns the length of the string |

int | locate(string substr, string str[, int pos]) | Returns the position of the first occurrence of substr in str after position pos |

string | lower(string A) lcase(string A) | |

string | lpad(string str, int len, string pad) | Returns str, left-padded with pad to a length of len |

string | ltrim(string A) | Returns the string resulting from trimming spaces from the beginning(left hand side) of A e.g. ltrim(‘ foobar ‘) results in ‘foobar ‘ |

array<struct<string,double>> | ngrams(array<array >, int N, int K, int pf) | Returns the top-k N-grams from a set of tokenized sentences, such as those returned by the sentences() UDAF. See StatisticsAndDataMining for more information. |

string | parse_url(string urlString, string partToExtract [, string keyToExtract]) | Returns the specified part from the URL. Valid values for partToExtract include HOST, PATH, QUERY, REF, PROTOCOL, AUTHORITY, FILE, and USERINFO. e.g. parse_url(‘http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1?, ‘HOST’) returns ‘facebook.com’. Also a value of a particular key in QUERY can be extracted by providing the key as the third argument, e.g. parse_url(‘http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1?, ‘QUERY’, ‘k1?) returns ‘v1?. |

string | printf(String format, Obj… args) | Returns the input formatted according do printf-style format strings (as of Hive 0.9.0) |

string | regexp_extract(string subject, string pattern, int index) | Returns the string extracted using the pattern. e.g. regexp_extract(‘foothebar’, ‘foo(.*?)(bar)’, 2) returns ‘bar.’ Note that some care is necessary in using predefined character classes: using ‘\s’ as the second argument will match the letter s; ‘s’ is necessary to match whitespace, etc. The ‘index’ parameter is the Java regex Matcher group() method index. See docs/api/java/util/regex/Matcher.html for more information on the ‘index’ or Java regex group() method. |

string | regexp_replace(string INITIAL_STRING, string PATTERN, string REPLACEMENT) | Returns the string resulting from replacing all substrings in INITIAL_STRING that match the java regular expression syntax defined in PATTERN with instances of REPLACEMENT, e.g. regexp_replace(“foobar”, “oo|ar”, “”) returns ‘fb.’ Note that some care is necessary in using predefined character classes: using ‘\s’ as the second argument will match the letter s; ‘s’ is necessary to match whitespace, etc. |

string | repeat(string str, int n) | Repeat str n times |

string | reverse(string A) | Returns the reversed string |

string | rpad(string str, int len, string pad) | Returns str, right-padded with pad to a length of len |

string | rtrim(string A) | Returns the string resulting from trimming spaces from the end(right hand side) of A e.g. rtrim(‘ foobar ‘) results in ‘ foobar’ |

array<array> | sentences(string str, string lang, string locale) | Tokenizes a string of natural language text into words and sentences, where each sentence is broken at the appropriate sentence boundary and returned as an array of words. The ‘lang’ and ‘locale’ are optional arguments. e.g. sentences(‘Hello there! How are you?’) returns ( (“Hello”, “there”), (“How”, “are”, “you”) ) |

string | space(int n) | Return a string of n spaces |

array | split(string str, string pat) | Split str around pat (pat is a regular expression) |

map<string,string> | str_to_map(text[, delimiter1, delimiter2]) | Splits text into key-value pairs using two delimiters. Delimiter1 separates text into K-V pairs, and Delimiter2 splits each K-V pair. Default delimiters are ‘,’ for delimiter1 and ‘=’ for delimiter2. |

string | substr(string|binary A, int start) substring(string|binary A, int start) | Returns the substring or slice of the byte array of A starting from start position till the end of string A e.g. substr(‘foobar’, 4) results in ‘bar’ |

string | substr(string|binary A, int start, int len) substring(string|binary A, int start, int len) | Returns the substring or slice of the byte array of A starting from start position with length len e.g. substr(‘foobar’, 4, 1) results in ‘b’ |

string | translate(string input, string from, string to) | Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translatefunction in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well |

string | trim(string A) | Returns the string resulting from trimming spaces from both ends of A e.g. trim(‘ foobar ‘) results in ‘foobar’ |

string | upper(string A) ucase(string A) | Returns the string resulting from converting all characters of A to upper case e.g. upper(‘fOoBaR’) results in ‘FOOBAR’ |

## Conditional Functions

Hive supports three types of conditional functions. These functions are listed below.

**IF( Test Condition, True Value, False Value )**

The IF condition evaluates the “Test Condition” and if the “Test Condition” is true, then it returns the “True Value”. Otherwise, it returns the False Value.

**Example:** IF(1=1, ‘working’, ‘not working’) returns ‘working’

**COALESCE( value1,value2,… )**

The COALESCE function returns the fist not NULL value from the list of values. If all the values in the list are NULL, then it returns NULL.

**Example:** COALESCE(NULL,NULL,5,NULL,4) returns 5

**CASE Statement**

The syntax for the case statement is:

1 2 3 4 5 6 7 8 |
CASE [ expression ] WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... WHEN conditionn THEN resultn ELSE result END |

Here expression is optional. It is the value that you are comparing to the list of conditions. (ie: condition1, condition2, … conditionn).

All the conditions must be of same datatype. Conditions are evaluated in the order listed. Once a condition is found to be true, the case statement will return the result and not evaluate the conditions any further.

All the results must be of same datatype. This is the value returned once a condition is found to be true.

IF no condition is found to be true, then the case statement will return the value in the ELSE clause. If the ELSE clause is omitted and no condition is found to be true, then the case statement will return NULL

**Example:**

1 2 3 4 5 6 |
CASE Fruit WHEN 'APPLE' THEN 'The owner is APPLE' WHEN 'ORANGE' THEN 'The owner is ORANGE' ELSE 'It is another Fruit' END |

- The other form of CASE is

1 2 3 4 5 6 7 |
CASE WHEN Fruit = 'APPLE' THEN 'The owner is APPLE' WHEN Fruit = 'ORANGE' THEN 'The owner is ORANGE' ELSE 'It is another Fruit' END |

## Collection Functions

The following built-in collection functions are supported in hive:

Return Type |
Name(Signature) |
Example |
---|---|---|

int | size(Map) | Returns the number of elements in the map type |

int | size(Array) | Returns the number of elements in the array type |

array | map_keys(Map) | Returns an unordered array containing the keys of the input map |

array | map_values(Map) | Returns an unordered array containing the values of the input map |

boolean | array_contains(Array, value) | Returns TRUE if the array contains value |

array | sort_array(Array) | Sorts the input array in ascending order according to the natural ordering of the array elements and returns it (as of version 0.9.0) |

**Type Conversion Function**

The following type conversion functions are supported in hive:

binary(string|binary)

Casts the parameter into a binary

- cast(expr as )

Converts the results of the expression expr to e.g. cast(‘1’ as BIGINT) will convert the string ‘1’ to it integral representation. A null is returned if the conversion does not succeed.

**Table Generating Functions**

Normal user-defined functions, such as concat(), take in a single input row and output a single output row. In contrast, table-generating functions transform a single input row to multiple output rows.

explode(ARRAY)

Returns one row for each element from the array

explode(MAP)

Returns one row for each key-value pair from the input map with two columns in each row: one for the key and another for the value.

inline(ARRAY<STRUCT[,STRUCT]>)

Explodes an array of structs into a table

explode(array a)

For each element in a, explode() generates a row containing that element

json_tuple(jsonStr, k1, k2, …)

It takes a set of names (keys) and a JSON string, and returns a tuple of values. This is a more efficient version of the get_json_object UDF because it can get multiple keys with just one call

parse_url_tuple(url, p1, p2, …)

This is similar to the parse_url() UDF but can extract multiple parts at once out of a URL. Valid part names are: HOST, PATH, QUERY, REF, PROTOCOL, AUTHORITY, FILE, USERINFO, QUERY:.

posexplode(ARRAY)

Behaves like explode for arrays, but includes the position of items in the original array by returning a tuple of (pos, value) (as of Hive 0.13.0)

stack(INT n, v_1, v_2, …, v_k)

Breaks up v_1, …, v_k into n rows. Each row will have k/n columns. n must be constant.

**Aggregate Functions**

The following are built-in aggregate functions are supported in Hive:

Return Type |
Name(Signature) |
Example |
---|---|---|

bigint | count(*), count(expr), count(DISTINCT expr[, expr_.]) | count(*) – Returns the total number of retrieved rows, including rows containing NULL values; count(expr) – Returns the number of rows for which the supplied expression is non-NULL; count(DISTINCT expr[, expr]) – Returns the number of rows for which the supplied expression(s) are unique and non-NULL. |

double | sum(col), sum(DISTINCT col) | Returns the sum of the elements in the group or the sum of the distinct values of the column in the group |

double | avg(col), avg(DISTINCT col) | Returns the average of the elements in the group or the average of the distinct values of the column in the group |

double | min(col) | Returns the minimum of the column in the group |

double | max(col) | Returns the maximum value of the column in the group |

double | variance(col), var_pop(col) | Returns the variance of a numeric column in the group |

double | var_samp(col) | Returns the unbiased sample variance of a numeric column in the group |

double | stddev_pop(col) | Returns the standard deviation of a numeric column in the group |

double | stddev_samp(col) | Returns the unbiased sample standard deviation of a numeric column in the group |

double | covar_pop(col1, col2) | Returns the population covariance of a pair of numeric columns in the group |

double | covar_samp(col1, col2) | Returns the sample covariance of a pair of a numeric columns in the group |

double | corr(col1, col2) | Returns the Pearson coefficient of correlation of a pair of a numeric columns in the group |

double | percentile(BIGINT col, p) | Returns the exact pth percentile of a column in the group (does not work with floating point types). p must be between 0 and 1. NOTE: A true percentile can only be computed for integer values. Use PERCENTILE_APPROX if your input is non-integral. |

array | percentile(BIGINT col, array(p1 [, p2]…)) | Returns the exact percentiles p1, p2, … of a column in the group (does not work with floating point types). pi must be between 0 and 1. NOTE: A true percentile can only be computed for integer values. Use PERCENTILE_APPROX if your input is non-integral. |

double | percentile_approx(DOUBLE col, p [, B]) | Returns an approximate pth percentile of a numeric column (including floating point types) in the group. The B parameter controls approximation accuracy at the cost of memory. Higher values yield better approximations, and the default is 10,000. When the number of distinct values in col is smaller than B, this gives an exact percentile value. |

array | percentile_approx(DOUBLE col, array(p1 [, p2]…) [, B]) | Same as above, but accepts and returns an array of percentile values instead of a single one. |

array | histogram_numeric(col, b) | Computes a histogram of a numeric column in the group using b non-uniformly spaced bins. The output is an array of size b of double-valued (x,y) coordinates that represent the bin centers and heights |

array | collect_set(col) | Returns a set of objects with duplicate elements eliminated |

HI Siva,

Thanks for the post.can you please give me some real time example for the above mostly using functions alone .it would be great to understanding clearly ..

Thanks!