Hive Functions: Built-in & UDF (User Defined) Example
⚡ Smart Summary
Hive functions fall into two groups: built-in functions that ship with the engine and cover collection, date, mathematical, conditional, string and miscellaneous work, and user defined functions written in Java for logic Hive does not supply.
Functions are built for a specific purpose to perform operations like mathematical, arithmetic, logical and relational operations on the operands of table column names.
Built-in Functions
These are functions that are already available in Hive. First, we have to check the application requirement, and then we can use these built-in functions in our applications. We can call these functions directly in our application.
The syntax and types are mentioned in the following section.
Types of built-in functions in Hive:
- Collection Functions
- Date Functions
- Mathematical Functions
- Conditional Functions
- String Functions
- Misc. Functions
Each of the six families is covered below with its function signatures and return types.
Collection Functions
These functions are used for collections. Collections mean the grouping of elements, and they return a single element or an array of elements depending on the return type mentioned in the function name.
| Return Type | Function Name | Description |
|---|---|---|
| INT | size(Map<K.V>) | It will fetch and give the number of components in the map type |
| INT | size(Array<T>) | It will fetch and give the number of elements in the array type |
| Array<K> | map_keys(Map<K.V>) | It will fetch and give an array containing the keys of the input map. The array is unordered |
| Array<V> | map_values(Map<K.V>) | It will fetch and give an array containing the values of the input map. The array is unordered |
| Array<T> | sort_array(Array<T>) | Sorts the input array in ascending order of its elements and returns it |
| Boolean | array_contains(Array<T>, value) | Returns TRUE if the array contains the value passed as the second argument |
Date Functions
These are used to perform date manipulations and conversion of date types from one type to another type:
| Function Name | Return Type | Description |
|---|---|---|
| unix_timestamp() | BigInt | We will get the current Unix timestamp in seconds. The value is not fixed for the whole query |
| to_date(string timestamp) | date | It will fetch and give the date part of a timestamp string |
| year(string date) | INT | It will fetch and give the year part of a date or a timestamp string |
| quarter(date/timestamp/string) | INT | It will fetch and give the quarter of the year for a date, timestamp, or string in the range 1 to 4 |
| month(string date) | INT | It will give the month part of a date or a timestamp string |
| hour(string date) | INT | It will fetch and give the hour of the timestamp |
| minute(string date) | INT | It will fetch and give the minute of the timestamp |
| date_sub(string starting date, int days) | date | It will fetch and give the result of subtracting a number of days from the starting date |
| current_date | date | It will fetch and give the current date at the start of query evaluation |
| last_day(string date) | string | It will fetch and give the last day of the month to which the date belongs |
| trunc(string date, string format) | string | It will fetch and give the date truncated to the unit specified by the format. Supported formats: MONTH/MON/MM, YEAR/YYYY/YY. |
Mathematical Functions
These functions are used for mathematical operations. Instead of creating UDFs, we have some inbuilt mathematical functions in Hive.
| Function Name | Return Type | Description |
|---|---|---|
| round(DOUBLE X) | DOUBLE | It will fetch and return the rounded BIGINT value of X |
| round(DOUBLE X, INT d) | DOUBLE | It will fetch and return X rounded to d decimal places |
| bround(DOUBLE X) | DOUBLE | It will fetch and return the rounded BIGINT value of X using HALF_EVEN rounding mode, also known as bankers’ rounding |
| floor(DOUBLE X) | BIGINT | It will fetch and return the maximum BIGINT value that is equal to or less than the X value |
| ceil(DOUBLE a), ceiling(DOUBLE a) | BIGINT | It will fetch and return the minimum BIGINT value that is equal to or greater than the a value |
| rand(), rand(INT seed) | DOUBLE | It will fetch and return a random number that is distributed uniformly from 0 to 1. Supplying a seed makes the sequence repeatable |
Conditional Functions
These functions are used for conditional value checks.
| Function Name | Return Type | Description |
|---|---|---|
| if(Boolean testCondition, T valueTrue, T valueFalseOrNull) | T | It will give valueTrue when testCondition is true, and valueFalseOrNull otherwise. |
| isnull(X) | Boolean | It will fetch and give true if X is NULL and false otherwise. |
| isnotnull(X) | Boolean | It will fetch and give true if X is not NULL and false otherwise. |
| nvl(T value, T default_value) | T | It will give default_value when value is NULL, and value otherwise. |
String Functions
String manipulations and string operations are handled by the following functions.
| Function Name | Return Type | Description |
|---|---|---|
| reverse(string X) | string | It will give the reversed string of X |
| rpad(string str, int length, string pad) | string | It will fetch and give str right-padded with pad to a total length of length |
| rtrim(string X) | string | It will fetch and return the string resulting from trimming spaces from the end (right hand side) of X. For example, rtrim(‘ results ‘) results in ‘ results’ |
| space(INT n) | string | It will fetch and give a string of n spaces. |
| split(STRING str, STRING pat) | array | Splits str around pat (pat is a regular expression). |
| str_to_map(text[, delimiter1, delimiter2]) | map<String, String> | It will split text into key-value pairs using two delimiters. Delimiter1 separates the pairs and delimiter2 splits each pair. |
Misc. Functions
Several built-in functions belong to none of the families above. These cover hashing, session information and calling arbitrary Java methods.
| Function Name | Return Type | Description |
|---|---|---|
| hash(a1[, a2…]) | INT | Returns a hash value of the arguments |
| current_user() | string | Returns the current user name from the configured authenticator manager |
| current_database() | string | Returns the name of the current database |
| md5(string/binary) | string | Returns the MD5 128-bit checksum as a string of 32 hex digits, or NULL for a NULL argument |
| sha1(string/binary) | string | Returns the SHA-1 digest of the argument as a hex string |
| crc32(string/binary) | BigInt | Returns the cyclic redundancy check value of a string or binary argument |
| version() | string | Returns the Hive version as a build number followed by a build hash |
| reflect(class, method[, arg1…]) | varies | Calls a Java method by matching the argument signature, using reflection. java_method() is a synonym |
UDFs (User Defined Functions)
In Hive, users can define their own functions to meet certain client requirements. These are known as UDFs in Hive. User defined functions are written in Java for specific modules.
Some UDFs are specifically designed for the reusability of code in application frameworks. The developer writes these functions in Java and integrates those UDFs with Hive.
During query execution, the developer can directly use the code, and UDFs will return outputs according to the user-defined tasks. It provides high performance in terms of coding and execution.
For example, for string stemming we do not have any predefined function in Hive. For this, we can write a stem UDF in Java. Wherever we require stem functionality, we can directly call this stem UDF in Hive.
Here stem functionality means deriving words from their root words. A stemming algorithm reduces the words “wishing”, “wished” and “wishes” to the root word “wish”. For performing this type of functionality, we can write a UDF in Java and integrate it with Hive.
Depending on the use case, the UDF can be written to accept and produce different numbers of input and output values.
The general type of UDF will accept a single input value and produce a single output value. If the UDF is used in a query, then the UDF will be called once for each row in the result data set.
In the other direction, a function can accept a group of values as input and return a single output value as well. That difference is what separates the three custom function types described next.
UDF vs UDAF vs UDTF in Hive
Custom functions in Hive are grouped by how many rows go in and how many come out. Choosing the wrong type is the most common reason a custom function refuses to compile or returns a single row where a table was expected.
| Type | Rows in → rows out | Class to extend | Built-in examples |
|---|---|---|---|
| UDF | One row → one row | org.apache.hadoop.hive.ql.exec.UDF | length(), round(), reverse() |
| UDAF | Many rows → one row | org.apache.hadoop.hive.ql.udf.generic.AbstractGenericUDAFResolver | count(), min(), max() |
| UDTF | One row → many rows | org.apache.hadoop.hive.ql.udf.generic.GenericUDTF | explode(), json_tuple(), parse_url_tuple() |
Two practical rules follow from the table:
- A UDAF is almost always paired with a GROUP BY clause, because it collapses each group down to one row.
- A UDTF cannot be selected alongside other columns in the same SELECT list, so it is normally used with a LATERAL VIEW.
There is also a second, more capable base class for row-level work, GenericUDF, which accepts complex types such as arrays, maps and structs and a variable number of arguments.
How to Write and Register a UDF in Hive
The stem example described above can be built as a real function in four steps. Nothing beyond a Java compiler and a running Hive session is required.
Step 1) Write a Java class that extends UDF and implements a public evaluate() method. Hive calls evaluate() once per row, so the method must handle a NULL input.
package com.guru99.hive.udf; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.Text; public final class Stem extends UDF { public Text evaluate(final Text input) { if (input == null) { return null; } String word = input.toString().toLowerCase(); if (word.endsWith("ing")) { word = word.substring(0, word.length() - 3); } else if (word.endsWith("ed") || word.endsWith("es")) { word = word.substring(0, word.length() - 2); } return new Text(word); } }
Step 2) Compile the class and package it into a JAR file, for example hive-udf-1.0.jar, together with any classes it depends on.
Step 3) Put the JAR on the Hive classpath and bind a function name to the class. A temporary function lives only for the current session.
ADD JAR /home/hduser/hive-udf-1.0.jar; CREATE TEMPORARY FUNCTION stem AS 'com.guru99.hive.udf.Stem';
Step 4) Call the new function exactly like a built-in one. Applied to the words “wishing”, “wished” and “wishes”, this class returns “wish” for all three.
SELECT word, stem(word) FROM words;
To keep the function available to every session and every user, register it permanently against a database instead. The JAR must sit on a path that the whole cluster can read, which normally means HDFS.
CREATE FUNCTION default.stem AS 'com.guru99.hive.udf.Stem' USING JAR '/user/hive/udfs/hive-udf-1.0.jar';
A single class may declare more than one evaluate() method. Hive matches the call against the argument signatures, which is how one function can accept both a string and an integer.

