Hive User-defined functions (UDFs) are custom functions that are developed in Java and integrated with Apache Hive. UDFs are routines that accept parameters, perform an action, and return the result of the action as a value. The return value can be a single scalar row or a result set, it depends on the UDF's code and implemented interface.
UDFs are powerful capability that extends the classical SQL functionality with custom code, that the Hive user can utilize. Hive has a bunch of built-in UDFs that you can utilize. Like other SQL-based solutions, Apache Hive also provides functionality to extend the current - rich- UDF set with custom if needed.
Important
Every UDF's evaluate method is one row at a time! This means if your UDFs has complex code, it could introduce performance issue in execution time.
To have an understanding of the UDF's let's start with one example to have an understanding of the execution pattern.
SELECT length(string_col) FROM table_name;
In this case, the length of the built-in UDF evaluates each row of the string_col values.
As we see how a built-in UDF works let's see what kind of built-in UDFs the Apache Hive has.
Tipp
All Hive keywords are case-insensitive, including the names of Hive operators and functions. I.e: length and LENGTH are also accepted by the Hive.
Mathematical Functions
The following built-in mathematical functions are supported in Hive.
Return Type | Name (Signature) | Description |
---|---|---|
double | round(DOUBLE a) | Returns the rounded |
double | round(DOUBLE a, INT d) | Returns |
double | bround(DOUBLE a) | Returns the rounded BIGINT value of a using HALF_EVEN rounding mode. Also known as Gaussian rounding or bankers' rounding. Example: bround(2.5) = 2, bround(3.5) = 4. |
double | bround(DOUBLE a, INT d) | Returns a rounded to d decimal places using HALF_EVEN rounding mode. Example: bround(8.25, 1) = 8.2, bround(8.35, 1) = 8.4. |
bigint | floor(DOUBLE a) | Returns the maximum |
bigint | ceil(DOUBLE a), ceiling(DOUBLE a) | Returns the minimum BIGINT value that is equal to or greater than |
double | rand(), rand(INT seed) | Returns a random number (that changes from row to row) that is distributed uniformly from 0 to 1. Specifying the seed will make sure the generated random number sequence is deterministic. |
double | exp(DOUBLE a), exp(DECIMAL a) | Returns |
double | ln(DOUBLE a), ln(DECIMAL a) | Returns the natural logarithm of the argument |
double | log10(DOUBLE a), log10(DECIMAL a) | Returns the base-10 logarithm of the argument |
double | log2(DOUBLE a), log2(DECIMAL a) | Returns the base-2 logarithm of the argument |
double | log(DOUBLE base, DOUBLE a) log(DECIMAL base, DECIMAL a) | Returns the base- |
double | pow(DOUBLE a, DOUBLE p), power(DOUBLE a, DOUBLE p) | Returns |
double | sqrt(DOUBLE a), sqrt(DECIMAL a) | Returns the square root of |
string | bin(BIGINT a) | Returns the number in binary format. |
string | hex(BIGINT a) hex(STRING a) hex(BINARY a) | If the argument is an |
binary | unhex(STRING a) | Inverse of hex. Interprets each pair of characters as a hexadecimal number and converts to the byte representation of 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 or double | pmod(INT a, INT b), pmod(DOUBLE a, DOUBLE b) | Returns the positive value of |
double | sin(DOUBLE a), sin(DECIMAL a) | Returns the sine of |
double | asin(DOUBLE a), asin(DECIMAL a) | Returns the arc sin of |
double | cos(DOUBLE a), cos(DECIMAL a) | Returns the cosine of |
double | acos(DOUBLE a), acos(DECIMAL a) | Returns the arccosine of |
double | tan(DOUBLE a), tan(DECIMAL a) | Returns the tangent of |
double | atan(DOUBLE a), atan(DECIMAL a) | Returns the arctangent of |
double | degrees(DOUBLE a), degrees(DECIMAL a) | Converts value of |
double | radians(DOUBLE a), radians(DOUBLE a) | Converts value of |
int or double | positive(INT a), positive(DOUBLE a) | Returns |
int or double | negative(INT a), negative(DOUBLE a) | Returns |
double or int | sign(DOUBLE a), sign(DECIMAL a) | Returns the sign of |
double | e() | Returns the value of |
double | pi() | Returns the value of |
bigint | factorial(INT a) | Returns the factorial of a Valid a is [0..20]. |
double | cbrt(DOUBLE a) | Returns the cube root of a double value. |
int bigint | shiftleft(TINYINT|SMALLINT|INT a, INT b) shiftleft(BIGINT a, INT b) | Bitwise left shift. Shifts Returns int for tinyint, smallint and int |
int bigint | shiftright(TINYINT|SMALLINT|INT a, INT b) shiftright(BIGINT a, INT b) | Bitwise right shift. Shifts Returns int for tinyint, smallint and int |
int bigint | shiftrightunsigned(TINYINT|SMALLINT|INT a, INT b), shiftrightunsigned(BIGINT a, INT b) | Bitwise unsigned right shift. Shifts Returns int for tinyint, smallint and int |
T | greatest(T v1, T v2, ...) | Returns the greatest value of the list of values. Fixed to return NULL when one or more arguments are NULL, and strict type restriction relaxed, consistent with ">" operator. |
T | least(T v1, T v2, ...) | Returns the least value of the list of values. Fixed to return NULL when one or more arguments are NULL, and strict type restriction relaxed, consistent with "<" operator. |
int | width_bucket(NUMERIC expr, NUMERIC min_value, NUMERIC max_value, INT num_buckets) | Returns an integer between 0 and num_buckets+1 by mapping expr into the ith equally sized bucket. Buckets are made by dividing [min_value, max_value] into equally sized regions. If expr < min_value, return 1, if expr > max_value return num_buckets+1. See https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions214.htm |
Collection Functions
The following built-in collection functions are supported in Hive.
Return Type | Name(Signature) | Description |
---|---|---|
int | size(Map<K.V>) | Returns the number of elements in the map type. |
int | size(Array<T>) | Returns the number of elements in the array type. |
array<K> | map_keys(Map<K.V>) | Returns an unordered array containing the keys of the input map. |
array<V> | map_values(Map<K.V>) | Returns an unordered array containing the values of the input map. |
boolean | array_contains(Array<T>, value) | Returns TRUE if the array contains the provided paramter value. |
array<t> | sort_array(Array<T>) | Sorts the input array in ascending order according to the natural ordering of the array elements and returns it. |
Date Functions
Date is one of the most used built-in functions in Hive. The following list contains the supported built-in date functions in Hive.
Return Type | Name(Signature) | Description |
---|---|---|
string | from_unixtime(bigint unixtime[, string pattern]) | Converts a number of seconds since epoch (1970-01-01 00:00:00 UTC) to a string representing the timestamp of that moment in the current time zone(using config "hive.local.time.zone") using the specified pattern. If the pattern is missing the default is used ('uuuu-MM-dd HH:mm:ss' or yyyy-MM-dd HH:mm:ss'). Example: from_unixtime(0)=1970-01-01 00:00:00 (hive.local.time.zone=Etc/GMT) NEW As of Hive 4.0.0 the "hive.datetime.formatter" property can be used to control the underlying formatter implementation and as a consequence the accepted patterns and their behavior. Earlier versions used https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html as the underlying formatter. |
bigint | unix_timestamp() | Gets the current Unix timestamp in seconds. This function is not deterministic and its value is not fixed for the scope of a query execution, therefore prevents proper optimization of queries - this has been deprecated since 2.0 in favour of CURRENT_TIMESTAMP constant. |
bigint | unix_timestamp(string date) | Converts a DateTime string to unix time (seconds since epoch) using the default pattern(s). The default accepted patterns depend on the underlying formatter implementation. The datetime string does not contain a timezone so the conversion uses the local time zone as specified by "hive.local.time.zone" property. Returns null when the conversion fails. Example: unix_timestamp('2009-03-20 11:30:01') = 1237573801 NEW As of Hive 4.0.0 the "hive.datetime.formatter" property can be used to control the underlying formatter implementation and as a consequence the accepted patterns and their behavior. Earlier versions used https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html as the underlying formatter. |
bigint | unix_timestamp(string date, string pattern) | Converts a datetime string to unix time (seconds since epoch) using the specified pattern. The accepted patterns and their behavior depend on the underlying formatter implementation. Returns null when the conversion fails. Example: unix_timestamp('2009-03-20', 'uuuu-MM-dd') = 1237532400 NEW As of Hive 4.0.0 the "hive.datetime.formatter" property can be used to control the underlying formatter implementation, and as a consequence the accepted patterns and their behavior. Earlier versions used https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html as the underlying formatter. |
date | to_date(string timestamp) | Returns the date part of a timestamp date object. Example: to_date("1970-01-01 00:00:00") |
int | year(string date) | Returns the year part of a date or a timestamp string: year("1970-01-01 00:00:00") = 1970, year("1970-01-01") = 1970. |
int | quarter(date/timestamp/string) | Returns the quarter of the year for a date, timestamp, or string in the range 1 to 4. Example: quarter('2015-04-08') = 2. |
int | month(string date) | Returns the month part of a date or a timestamp string. Example: month("1970-11-01 00:00:00") = 11, month("1970-11-01") = 11. |
int | day(string date) dayofmonth(date) | Returns the day part of a date or a timestamp string. Example: day("1970-11-01 00:00:00") = 1, day("1970-11-01") = 1. |
int | hour(string date) | Returns the hour of the timestamp: Example: hour('2009-07-30 12:58:59') = 12, hour('12:58:59') = 12. |
int | minute(string date) | Returns the minute of the timestamp. |
int | second(string date) | Returns the second of the timestamp. |
int | weekofyear(string date) | Returns the week number of a timestamp string. Example: weekofyear("1970-11-01 00:00:00") = 44 or weekofyear("1970-11-01") = 44. |
int | extract(field FROM source) | Retrieve fields such as days or hours from the source. The source must be a date, timestamp, interval, or string that can be converted into either a date or timestamp. Supported fields include: day, dayofweek, hour, minute, month, quarter, second, week and year. Examples:
|
int | datediff(string enddate, string startdate) | Returns the number of days from startdate to end date. Example: datediff('2009-03-01', '2009-02-27') = 2. |
date | date_add(date/timestamp/string startdate, tinyint/smallint/int days) | Adds a number of days to startdate. Example: date_add('2008-12-31', 1) = '2009-01-01'. |
date | date_sub(date/timestamp/string startdate, tinyint/smallint/int days) | Subtracts a number of days to startdate: date_sub('2008-12-31', 1) = '2008-12-30'. |
timestamp | from_utc_timestamp({any primitive type} ts, string timezone) | Converts a timestamp* in UTC to a given timezone. * timestamp is a primitive type, including timestamp/date, tinyint/smallint/int/bigint, float/double and decimal. Fractional values are considered as seconds. Integer values are considered as milliseconds. For example, from_utc_timestamp(2592000.0,'PST'), from_utc_timestamp(2592000000,'PST') and from_utc_timestamp(timestamp '1970-01-30 16:00:00','PST') all return the timestamp 1970-01-30 08:00:00. |
timestamp | to_utc_timestamp({any primitive type} ts, string timezone) | Converts a timestamp* in a given timezone to UTC. * timestamp is a primitive type, including timestamp/date, tinyint/smallint/int/bigint, float/double and decimal. Fractional values are considered as seconds. Integer values are considered as milliseconds. For example, to_utc_timestamp(2592000.0,'PST'), to_utc_timestamp(2592000000,'PST') and to_utc_timestamp(timestamp '1970-01-30 16:00:00','PST') all return the timestamp 1970-01-31 00:00:00. |
date | current_date | Returns the current date at the start of query evaluation. All calls of current_date within the same query return the same value. |
timestamp | current_timestamp | Returns the current timestamp at the start of query evaluation. All calls of current_timestamp within the same query return the same value. |
string | add_months(string start_date, int num_months, output_date_format) | Returns the date that is num_months after start_date. start_date is a string, date or timestamp. num_months is an integer. If start_date is the last day of the month or if the resulting month has fewer days than the day component of start_date, then the result is the last day of the resulting month. Otherwise, the result has the same day component as start_date. The default output format is 'yyyy-MM-dd'. NEW Before Hive 4.0.0, the time part of the date is ignored. As of Hive 4.0.0, add_months supports an optional argument output_date_format, which accepts a String that represents a valid date format for the output. This allows to retain the time format in the output. For example : add_months('2009-08-31', 1) returns '2009-09-30'. |
string | last_day(string date) | Returns the last day of the month to which the date belongs. date is a string in the format 'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd'. The time part of the date is ignored! |
string | next_day(string start_date, string day_of_week) | Returns the first date which is later than start_date and named as day_of_week. start_date is a string/date/timestamp. day_of_week is 2 letters, 3 letters or full name of the day of the week (e.g. Mo, tue, FRIDAY). The time part of start_date is ignored. Example: next_day('2015-01-14', 'TU') = 2015-01-20. |
string | trunc(string date, string format) | Returns date truncated to the unit specified by the format. Supported formats: MONTH/MON/MM, YEAR/YYYY/YY. Example: trunc('2015-03-17', 'MM') = 2015-03-01. |
double | months_between(date1, date2) | Returns the number of months between dates date1 and date2 . If date1 is later than date2 , then the result is positive. If date1 is earlier than date , then the result is negative. If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer. Otherwise, the UDF calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2. date1 and date2 type can be date, timestamp or string in the format 'yyyy-MM-dd' or 'yyyy-MM-dd HH:mm:ss'. The result is rounded to 8 decimal places. Example: months_between('1997-02-28 10:30:00', '1996-10-30') = 3.94959677 |
string | date_format(date/timestamp/string ts, string pattern) | Converts a date/timestamp/string to a value of string using the specified pattern. The accepted patterns and their behavior depend on the underlying formatter implementation. The pattern argument should be constant. Example: date_format('2015-04-08', 'y') = '2015'. date_format can be used to implement other UDFs, e.g.:
NEW As of Hive 4.0.0 the "hive.datetime.formatter" property can be used to control the underlying formatter implementation and as a consequence the accepted patterns and their behavior. Earlier versions used https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html as the underlying formatter. |