...
Note | ||
---|---|---|
| ||
When hive.cache.expr.evaluation is set to true (which is the default) a UDF can give incorrect results if it is nested in another UDF or a Hive function. This bug affects releases 0.12.0, 0.13.0, and 0.13.1. Release 0.14.0 fixed the bug (HIVE-7314). The problem relates to the UDF's implementation of the getDisplayString method, as discussed in the Hive user mailing list. |
Built-in Operators
Anchor | ||||
---|---|---|---|---|
|
Anchor | ||||
---|---|---|---|---|
|
Example | Operators | Description |
---|---|---|
A[B] , A.identifier | bracket_op([]), dot(.) | element selector, dot |
-A | unary(+), unary(-), unary(~) | unary prefix operators |
A IS (NOT) NULL[NOT] (NULL|TRUE|FALSE) | IS NULL,IS NOT NULL, ... | unary suffix |
A ^ B | bitwise xor(^) | bitwise xor |
A * B | star(*), divide(/), mod(%), div(DIV) | multiplicative operators |
A + B | plus(+), minus(-) | additive operators |
A || B | string concatenate(||) | string concatenate |
A & B | bitwise and(&) | bitwise and |
A | B | bitwise or(|) | bitwise or |
...
Operator | Operand types | Description |
---|---|---|
A = B | All primitive types | TRUE if expression A is equal to expression B otherwise FALSE. |
A == B | All primitive types | Synonym for the = operator. |
A <=> B | All primitive types | Returns same result with EQUAL(=) operator for non-null operands, but returns TRUE if both are NULL, FALSE if one of the them is NULL. (As of version 0.9.0.) |
A <> B | All primitive types | NULL if A or B is NULL, TRUE if expression A is NOT equal to expression B, otherwise FALSE. |
A != B | All primitive types | Synonym for the <> operator. |
A < B | All primitive types | NULL if A or B is NULL, TRUE if expression A is less than expression B, otherwise FALSE. |
A <= B | All primitive types | NULL if A or B is NULL, TRUE if expression A is less than or equal to expression B, otherwise FALSE. |
A > B | All primitive types | NULL if A or B is NULL, TRUE if expression A is greater than expression B, otherwise FALSE. |
A >= B | All primitive types | NULL if A or B is NULL, TRUE if expression A is greater than or equal to expression B, otherwise FALSE. |
A [NOT] BETWEEN B AND C | All primitive types | NULL if A, B or C is NULL, TRUE if A is greater than or equal to B AND A less than or equal to C, otherwise FALSE. This can be inverted by using the NOT keyword. (As of version 0.9.0.) |
A IS NULL | All types | TRUE if expression A evaluates to NULL, otherwise FALSE. |
A IS NOT NULL | All types | FALSE if expression A evaluates to NULL, otherwise TRUE. |
A IS [NOT] (TRUE|FALSE) | Boolean types | Evaluates to TRUE only if A mets the condition. (since:3.0.0 ) |
A [NOT] LIKE B | strings | NULL if A or B is NULL, TRUE if string A matches the SQL simple regular expression B, otherwise FALSE. The comparison is done character by character. The _ character in B matches any character in A (similar to . in posix regular expressions) while the % character in B matches an arbitrary number of characters in A (similar to .* in posix regular expressions). For example, 'foobar' like 'foo' evaluates to FALSE whereas 'foobar' like 'foo_ _ _' evaluates to TRUE and so does 'foobar' like 'foo%'. |
A RLIKE B | strings | NULL if A or B is NULL, TRUE if any (possibly empty) substring of A matches the Java regular expression B, otherwise FALSE. For example, 'foobar' RLIKE 'foo' evaluates to TRUE and so does 'foobar' RLIKE '^f.*r$'. |
A REGEXP B | strings | Same as RLIKE. |
...
Operator | Operand types | Description |
---|---|---|
A + B | All number types | Gives the result of adding A and B. The type of the result is the same as the common parent(in the type hierarchy) of the types of the operands. For example since every integer is a float, therefore float is a containing type of integer so the + operator on a float and an int will result in a float. |
A - B | All number types | Gives the result of subtracting B from A. The type of the result is the same as the common parent(in the type hierarchy) of the types of the operands. |
A * B | All number types | Gives the result of multiplying A and B. The type of the result is the same as the common parent(in the type hierarchy) of the types of the operands. Note that if the multiplication causing overflow, you will have to cast one of the operators to a type higher in the type hierarchy. |
A / B | All number types | Gives the result of dividing A by B. The result is a double type in most cases. When A and B are both integers, the result is a double type except when the hive.compat configuration parameter is set to "0.13" or "latest" in which case the result is a decimal type. |
A DIV B | Integer types | Gives the integer part resulting from dividing A by B. E.g 17 div 3 results in 5. |
A % B | All number types | Gives the reminder resulting from dividing A by B. The type of the result is the same as the common parent(in the type hierarchy) of the types of the operands. |
A & B | All number types | Gives the result of bitwise AND of A and B. The type of the result is the same as the common parent(in the type hierarchy) of the types of the operands. |
A | B | All number types | Gives the result of bitwise OR of A and B. The type of the result is the same as the common parent(in the type hierarchy) of the types of the operands. |
A ^ B | All number types | Gives the result of bitwise XOR of A and B. The type of the result is the same as the common parent(in the type hierarchy) of the types of the operands. |
~A | All number types | Gives the result of bitwise NOT of A. The type of the result is the same as the type of A. |
...
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 (as of Hive 1.3.0, 2.0.0). 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 (as of Hive 1.3.0, 2.0.0). 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 (see http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_bin). |
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 (see http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_conv). |
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 (as of Hive 1.2.0). Valid a is [0..20]. |
DOUBLE | cbrt(DOUBLE a) | Returns the cube root of a double value (as of Hive 1.2.0). |
INT BIGINT | shiftleft(TINYINT|SMALLINT|INT a, INT b) shiftleft(BIGINT a, INT b) | Bitwise left shift (as of Hive 1.2.0). 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 (as of Hive 1.2.0). 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 (as of Hive 1.2.0). Shifts Returns int for tinyint, smallint and int |
T | greatest(T v1, T v2, ...) | Returns the greatest value of the list of values (as of Hive 1.1.0). Fixed to return NULL when one or more arguments are NULL, and strict type restriction relaxed, consistent with ">" operator (as of Hive 2.0.0). |
T | least(T v1, T v2, ...) | Returns the least value of the list of values (as of Hive 1.1.0). Fixed to return NULL when one or more arguments are NULL, and strict type restriction relaxed, consistent with "<" operator (as of Hive 2.0.0). |
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 (as of Hive 3.0.0) |
Mathematical Functions Mathematical Functions and Operators for Decimal Datatypes
...
Return Type | Name(Signature) | Description | ||
---|---|---|---|---|
string | from_unixtime(bigint unixtime[, string format]) | Converts the number of seconds from unix epoch (1970-01-01 00:00:00 UTC) to a string representing the timestamp of that moment in the current system time zone in the format of "1970-01-01 00:00:00". | ||
bigint | unix_timestamp() | Gets 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 time string in format | ||
bigint | unix_timestamp(string date, string pattern) | Convert time string with given pattern (see [http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html]) to Unix time stamp (in seconds), return 0 if fail: unix_timestamp('2009-03-20', 'yyyy-MM-dd') = 1237532400. | ||
pre 2.1.0: string 2.1.0 on: date | to_date(string timestamp) | Returns the date part of a timestamp string (pre-Hive 2.1.0): to_date("1970-01-01 00:00:00") = "1970-01-01". As of Hive 2.1.0, returns a date object. Prior to Hive 2.1.0 (HIVE-13248) the return type was a String because no Date type existed when the method was created. | ||
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 (as of Hive 1.3.0). Example: quarter('2015-04-08') = 2. | ||
int | month(string date) | Returns the month part of a date or a timestamp string: 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: day("1970-11-01 00:00:00") = 1, day("1970-11-01") = 1. | ||
int | hour(string date) | Returns the hour of the timestamp: 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: weekofyear("1970-11-01 00:00:00") = 44, weekofyear("1970-11-01") = 44. | ||
int | extract(field FROM source) | Retrieve fields such as days or hours from source (as of Hive 2.2.0). Source must be a date, timestamp, interval or a 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 enddate: datediff('2009-03-01', '2009-02-27') = 2. | ||
pre 2.1.0: string 2.1.0 on: date | date_add(date/timestamp/string startdate, tinyint/smallint/int days) | Adds a number of days to startdate: date_add('2008-12-31', 1) = '2009-01-01'. Prior to Hive 2.1.0 (HIVE-13248) the return type was a String because no Date type existed when the method was created. | ||
pre 2.1.0: string 2.1.0 on: 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'. Prior to Hive 2.1.0 (HIVE-13248) the return type was a String because no Date type existed when the method was created. | ||
timestamp | from_utc_timestamp(timestamp{any primitive type} ts, string timezone) | Assumes given timestamp is UTC and converts to Converts a timestamp* in UTC to a given timezone (as of Hive 0.8.0). * 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-01 0830 16:00:00','PST') returns all return the timestamp 1970-01-01 0030 08:00:00. | ||
timestamp | to_utc_timestamp(timestamp{any primitive type} ts, string timezone) | Assumes given Converts a timestamp is * in a given timezone and converts to UTC (as of Hive 0.8.0). For example, to_utc_timestamp( * 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-01 0030 16:00:00','PST') returns all return the timestamp 1970-01-01 0831 00:00:00. | ||
date | current_date | Returns the current date at the start of query evaluation (as of Hive 1.2.0). 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 (as of Hive 1.2.0). 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 (as of Hive 1.1.0). start_date is a string, date or timestamp. num_months is an integer. The time part of start_date is ignored. 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. | ||
string | last_day(string date) | Returns the last day of the month which the date belongs to (as of Hive 1.1.0). date is a string in the format 'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd'. The time part of date is ignored. | ||
The default output format is 'yyyy-MM-dd'. 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 which the date belongs to (as of Hive 1.1.0). date is a string in the format 'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd'. The time part of date is ignored. | ||
string | next_day(string start_date | 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 (as of Hive 1.2.0). 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 (as of Hive 1.2.0). Supported formats: MONTH/MON/MM, YEAR/YYYY/YY. Example: trunc('2015-03-17', 'MM') = 2015-03-01. | ||
double | months_between(date1, date2) | Returns number of months between dates date1 and date2 (as of Hive 1.2.0). If date1 is later than date2, then the result is positive. If date1 is earlier than date2, 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 fmt) | Converts a date/timestamp/string to a value of string in the format specified by the date format fmt (as of Hive 1.2.0). Supported formats are Java SimpleDateFormat formats – https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html. The second argument fmt should be constant. Example: date_format('2015-04-08', 'y') = '2015'. date_format can be used to implement other UDFs, e.g.:
|
...
Return Type | Name(Signature) | Description |
---|---|---|
T | if(boolean testCondition, T valueTrue, T valueFalseOrNull) | Returns valueTrue when testCondition is true, returns valueFalseOrNull otherwise. |
boolean | isnull( a ) | Returns true if a is NULL and false otherwise. |
boolean | isnotnull ( a ) | Returns true if a is not NULL and false otherwise. |
T | nvl(T value, T default_value) | Returns default value if value is null else returns value (as of HIve 0.11). |
T | COALESCE(T v1, T v2, ...) | Returns the first v that is not NULL, or NULL if all v's are NULL. |
T | CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END | When a = b, returns c; when a = d, returns e; else returns f. |
T | CASE WHEN a THEN b [WHEN c THEN d]* [ELSE e] END | When a = true, returns b; when c = true, returns d; else returns e. |
T | nullif( a, b ) | Returns NULL if a=b; otherwise returns a (as of Hive 2.23.0). Shorthand for: CASE WHEN a = b then NULL else a |
void | assert_true(boolean condition) | Throw an exception if 'condition' is not true, otherwise return null . For example (as of Hive 0.8.0). For example, select assert_true (2<1). |
String Functions
The following built-in String functions are supported in Hive:
Return Type | Name(Signature) | Description |
---|---|---|
int | ascii(string str) | Returns the numeric value of the first character of str. |
string | base64(binary bin) | Converts the argument from binary to a base 64 string (as of Hive 0.12.0). |
int | character_length(string str) | Returns the number of UTF-8 characters contained in str (as of Hive 2.2.0). The function char_length is shorthand for this function. |
string | chr(bigint|double A) | Returns the ASCII character having the binary equivalent to A (as of Hive 1.3.0 and 2.1.0). If A is larger than 256 the result is equivalent to chr(A % 256). Example: select chr(88); returns "X". |
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. For example, 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<string>>, array<string>, 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<string>) | Like concat_ws() above, but taking an array of strings. (as of Hive 0.9.0) |
string | decode(binary bin, string charset) | Decodes the first argument into a String using the provided character set (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). If either argument is null, the result will also be null. (As of Hive 0.12.0.) |
string | elt(N int,str1 string,str2 string,str3 string,...) | Return string at index number. For example elt(2,'hello','world') returns 'world'. Returns NULL if N is less than 1 or greater than the number of arguments. (see https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_elt) |
binary | encode(string src, string charset) | Encodes the first argument into a BINARY using the provided character set (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). If either argument is null, the result will also be null. (As of Hive 0.12.0.) |
int | field(val T,val1 T,val2 T,val3 T,...) | Returns the index of val in the val1,val2,val3,... list or 0 if not found. For example field('world','say','hello','world') returns 3. (see https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_field) |
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. For example, 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; bug with float types fixed in Hive 0.14.0, decimal type support added in Hive 0.14.0) |
string | get_json_object(string json_string, string path) | Extracts json object from a json string based on json path specified, and returns 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 occurrence of |
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) | Returns the string resulting from converting all characters of B to lower case. For example, lower('fOoBaR') results in 'foobar'. |
string | lpad(string str, int len, string pad) | Returns str, left-padded with pad to a length of len. If str is longer than len, the return value is shortened to len characters. In case of empty pad string, the return value is null. |
string | ltrim(string A) | Returns the string resulting from trimming spaces from the beginning(left hand side) of A. For example, ltrim(' foobar ') results in 'foobar '. |
array<struct<string,double>> | ngrams(array<array<string>>, 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. |
int | octet_length(string str) | Returns the number of octets required to hold the string str in UTF-8 encoding (since Hive 2.2.0). Note that octet_length(str) can be larger than character_length(str). |
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. For example, 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, for example, 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. For example, 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. For example, 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) | Repeats str n times. |
string | replace(string A, string OLD, string NEW) | Returns the string A with all non-overlapping occurrences of OLD replaced with NEW (as of Hive 1.3.0 and 2.1.0). Example: select replace("ababab", "abab", "Z"); returns "Zab". |
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. If str is longer than len, the return value is shortened to len characters. In case of empty pad string, the return value is null. |
string | rtrim(string A) | Returns the string resulting from trimming spaces from the end(right hand side) of A. For example, rtrim(' foobar ') results in ' foobar'. |
array<array<string>> | 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. For example, sentences('Hello there! How are you?') returns ( ("Hello", "there"), ("How", "are", "you") ). |
string | space(int n) | Returns a string of n spaces. |
array | split(string str, string pat) | Splits 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. For example, substr('foobar', 4) results in 'bar' (see [http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substr]). |
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. For example, substr('foobar', 4, 1) results in 'b' (see [http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substr]). |
string | substring_index(string A, string delim, int count) | Returns the substring from string A before count occurrences of the delimiter delim (as of Hive 1.3.0). If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned. Substring_index performs a case-sensitive match when searching for delim. Example: substring_index('www.apache.org', '.', 2) = 'www.apache'. |
string | translate(string|char|varchar input, string|char|varchar from, string|char|varchar to) | Translates the input string by replacing the characters present in the Char/varchar support added as of Hive 0.14.0. |
string | trim(string A) | Returns the string resulting from trimming spaces from both ends of A. For example, trim(' foobar ') results in 'foobar' |
binary | unbase64(string str) | Converts the argument from a base 64 string to BINARY. (As of Hive 0.12.0.) |
string | upper(string A) ucase(string A) | Returns the string resulting from converting all characters of A to upper case. For example, upper('fOoBaR') results in 'FOOBAR'. |
string | initcap(string A) | Returns string, with the first letter of each word in uppercase, all other letters in lowercase. Words are delimited by whitespace. (As of Hive 1.1.0.) |
int | levenshtein(string A, string B) | Returns the Levenshtein distance between two strings (as of Hive 1.2.0). For example, levenshtein('kitten', 'sitting') results in 3. |
string | soundex(string A) | Returns soundex code of the string (as of Hive 1.2.0). For example, soundex('Miller') results in M460. |
...
Return Type | Name(Signature) | Description |
---|---|---|
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. Execution of this can be optimized with hive.optimize.distinct.rewrite. |
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<double> | 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<double> | 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<struct { | 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. |
array | collect_list(col) | Returns a list of objects with duplicates. (As of Hive 0.13.0.) |
INTEGER | ntile(INTEGER x) | Divides an ordered partition into |
Built-in Table-Generating Functions (UDTF)
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.
double | regr_avgx(independent, dependent) | Equivalent to avg(dependent). As of Hive 2.2.0. | |
double | regr_avgy(independent, dependent) | Equivalent to avg(independent). As of Hive 2.2.0. | |
double | regr_count(independent, dependent) | Returns the number of non-null pairs used to fit the linear regression line. As of Hive 2.2.0. | |
double | regr_intercept(independent, dependent) | Returns the y-intercept of the linear regression line, i.e. the value of b in the equation dependent = a * independent + b. As of Hive 2.2.0. | |
double | regr_r2(independent, dependent) | Returns the coefficient of determination for the regression. As of Hive 2.2.0. | |
double | regr_slope(independent, dependent) | Returns the slope of the linear regression line, i.e. the value of a in the equation dependent = a * independent + b. As of Hive 2.2.0. | |
double | regr_sxx(independent, dependent) | Equivalent to regr_count(independent, dependent) * var_pop(dependent). As of Hive 2.2.0. | |
double | regr_sxy(independent, dependent) | Equivalent to regr_count(independent, dependent) * covar_pop(independent, dependent). As of Hive 2.2.0. | |
double | regr_syy(independent, dependent) | Equivalent to regr_count(independent, dependent) * var_pop(independent). As of Hive 2.2.0. | |
array<struct { | 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. | |
array | collect_list(col) | Returns a list of objects with duplicates | |
Return Type | Name(Signature) | Description | |
---|---|---|---|
N rows | explode(ARRAY) | Returns one row for each element from the array. | |
N rows | 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. (As of Hive 0.8.0.) | |
| inline(ARRAY<STRUCT[,STRUCT]>) | Explodes an array of structs into a table. (As of Hive 0.10.) | |
Array Type | explode(array<TYPE> a) | For each element in a, generates a row containing that element. | |
tuple | json_tuple(jsonStr, k1, k2, ...) | Takes a set of names (keys) and a JSON string, and returns a tuple of values. This is a more efficient version of the | |
tuple | parse_url_tuple(url, p1, p2, ...) | This is similar to the | |
N rows | posexplode(ARRAY) | Behaves like | |
INTEGER | 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.ntile(INTEGER x) | Divides an ordered partition into |
Built-in Table-Generating Functions (UDTF)
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.
Row-set columns types | Name(Signature) | Description |
---|---|---|
T | explode(ARRAY<T> a) | Explodes an array to multiple rows. Returns a row-set with a single column (col), one row for each element from the array. |
Tkey,Tvalue | explode(MAP<Tkey,Tvalue> m) | Explodes a map to multiple rows. Returns a row-set with a two columns (key,value) , one row for each key-value pair from the input map. (As of Hive 0.8.0.). |
int,T | posexplode(ARRAY<T> a) | Explodes an array to multiple rows with additional positional column of int type (position of items in the original array, starting with 0). Returns a row-set with two columns (pos,val), one row for each element from the array. |
T1,...,Tn | inline(ARRAY<STRUCT<f1:T1,...,fn:Tn>> a) | Explodes an array of structs to multiple rows. Returns a row-set with N columns (N = number of top level elements in the struct), one row per struct from the array. (As of Hive 0.10.) |
T1,...,Tn/r | stack(int r,T1 V1,...,Tn/r Vn) | Breaks up n values V1,...,Vn into r rows. Each row will have n/r columns. r must be constant. |
string1,...,stringn | json_tuple(string jsonStr,string k1,...,string kn) | Takes JSON string and a set of n keys, and returns a tuple of n values. This is a more efficient version of the |
string 1,...,stringn | parse_url_tuple(string urlStr,string p1,...,string pn) | Takes URL string and a set of n URL parts, and returns a tuple of n values. This is similar to the |
Usage Examples
explode (array)
Code Block | ||
---|---|---|
| ||
select explode(array('A','B','C'));
select explode(array('A','B','C')) as col;
select tf.* from (select 0) t lateral view explode(array('A','B','C')) tf;
select tf.* from (select 0) t lateral view explode(array('A','B','C')) tf as col; |
HTML | ||
---|---|---|
| ||
<table><tbody><tr><th>col</th></tr><tr><td>A</td></tr><tr><td>B</td></tr><tr><td>C</td></tr></tbody></table> |
explode (map)
Code Block | ||
---|---|---|
| ||
select explode(map('A',10,'B',20,'C',30));
select explode(map('A',10,'B',20,'C',30)) as (key,value);
select tf.* from (select 0) t lateral view explode(map('A',10,'B',20,'C',30)) tf;
select tf.* from (select 0) t lateral view explode(map('A',10,'B',20,'C',30)) tf as key,value; |
HTML | ||
---|---|---|
| ||
<table><tbody><tr><th>key</th><th>value</th></tr><tr><td>A</td><td>10</td></tr><tr><td>B</td><td>20</td></tr><tr><td>C</td><td>30</td></tr></tbody></table> |
posexplode (array)
Code Block | ||
---|---|---|
| ||
select posexplode(array('A','B','C'));
select posexplode(array('A','B','C')) as (pos,val);
select tf.* from (select 0) t lateral view posexplode(array('A','B','C')) tf;
select tf.* from (select 0) t lateral view posexplode(array('A','B','C')) tf as pos,val; |
HTML | ||
---|---|---|
| ||
<table><tbody><tr><th>pos</th><th>val</th></tr><tr><td>0</td><td>A</td></tr><tr><td>1</td><td>B</td></tr><tr><td>2</td><td>C</td></tr></tbody></table> |
inline (array of structs)
Code Block | ||
---|---|---|
| ||
select inline(array(struct('A',10,date '2015-01-01'),struct('B',20,date '2016-02-02')));
select inline(array(struct('A',10,date '2015-01-01'),struct('B',20,date '2016-02-02'))) as (col1,col2,col3);
select tf.* from (select 0) t lateral view inline(array(struct('A',10,date '2015-01-01'),struct('B',20,date '2016-02-02'))) tf;
select tf.* from (select 0) t lateral view inline(array(struct('A',10,date '2015-01-01'),struct('B',20,date '2016-02-02'))) tf as col1,col2,col3; |
HTML | ||
---|---|---|
| ||
<table><tbody><tr><th>col1</th><th>col2</th><th>col3</th></tr><tr><td>A</td><td>10</td><td>2015-01-01</td></tr><tr><td>B</td><td>20</td><td>2016-02-02</td></tr></tbody></table> |
stack (values)
Code Block | ||
---|---|---|
| ||
select stack(2,'A',10,date '2015-01-01','B',20,date '2016-01-01');
select stack(2,'A',10,date '2015-01-01','B',20,date '2016-01-01') as (col0,col1,col2);
select tf.* from (select 0) t lateral view stack(2,'A',10,date '2015-01-01','B',20,date '2016-01-01') tf;
select tf.* from (select 0) t lateral view stack(2,'A',10,date '2015-01-01','B',20,date '2016-01-01') tf as col0,col1,col2; |
HTML | ||
---|---|---|
| ||
<table><tbody><tr><th>col0</th><th>col1</th><th>col2</th></tr><tr><td>A</td><td>10</td><td>2015-01-01</td></tr><tr><td>B</td><td>20</td><td>2016-01-01</td></tr></tbody></table> |
Using the syntax "SELECT udtf(col) AS colAlias..." has a few limitations:
...
For information about how to create a custom UDF, see Hive Plugins and Create Function.
select explode(array('A','B','C'));select explode(array('A','B','C')) as col;select tf.* from (select 0) t lateral view explode(array('A','B','C')) tf;select tf.* from (select 0) t lateral view explode(array('A','B','C')) tf as col;