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.

  • 📚 Six built-in families: Collection, date, mathematical, conditional, string and miscellaneous functions are callable directly inside HiveQL.
  • 🧾 Signatures matter: Every function has a fixed argument list and a documented return type, so the return type decides where it can be used.
  • 🧩 UDF fills the gaps: When no built-in function exists, a Java class extending org.apache.hadoop.hive.ql.exec.UDF supplies the missing operation.
  • 🔢 Three shapes of custom function: UDF returns one row per row, UDAF collapses many rows into one, and UDTF expands one row into many.
  • 🛠️ Registration in two steps: ADD JAR puts the code on the classpath and CREATE TEMPORARY FUNCTION binds a name to the class.
  • ♻️ Reuse is the point: One tested UDF, such as a stemmer, can be called from every query instead of being rewritten each time.

Hive Functions: Built-in and User Defined Functions

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.

FAQs

SHOW FUNCTIONS lists every registered name, including custom ones. DESCRIBE FUNCTION name prints a one-line signature, and DESCRIBE FUNCTION EXTENDED name adds usage examples where the implementing class supplies them.

Almost always a name or scope problem: the string after AS must be the fully qualified class name, and ADD JAR only applies to the session that ran it. Reconnecting drops both the JAR and any temporary function.

Use GenericUDF when the function takes complex types such as arrays, maps or structs, a variable number of arguments, or needs to validate argument types itself. The simple UDF class resolves types by reflection and handles only primitive Writables.

A true UDF must run on the JVM. For other languages, Hive offers the TRANSFORM clause, which streams each row through an external script such as Python over standard input and output. It is slower but avoids Java entirely.

They can. evaluate() runs once per row, so expensive logic is multiplied by the row count, and object allocation inside the method adds garbage-collection pressure. Prefer a built-in function when one exists, and keep evaluate() free of I/O.

No. Function names resolve case-insensitively, so ROUND(), Round() and round() are the same function. The Java class name in the AS clause is a different matter and must match the compiled class exactly, including its package.

Machine learning assistants map a plain-language description onto candidate signatures and warn when a return type will not fit the target column. Verify the suggestion against the documented signature, because generated names sometimes belong to another SQL dialect.

It produces a usable skeleton — the class declaration, imports and an evaluate() method — from a comment describing the operation. Null handling, Writable types and the packaging step still need review, and the function must be tested on real rows.

Summarize this post with: