Hive2.0函数大全(中文版)
摘要
Hive内部提供了很多函数给开发者使用,包括数学函数,类型转换函数,条件函数,字符函数,聚合函数,表生成函数等等,这些函数都统称为内置函数。
目录
数学函数
Return Type | Name (Signature) | Description |
---|---|---|
DOUBLE | round(DOUBLE a) | Returns the rounded 返回对a四舍五入的BIGINT值 |
DOUBLE | round(DOUBLE a, INT d) | Returns 返回DOUBLE型d的保留n位小数的DOUBLW型的近似值 |
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.银行家舍入法(1~4:舍,6~9:进,5->前位数是偶:舍,5->前位数是奇:进) |
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.银行家舍入法,保留d位小数 |
BIGINT | floor(DOUBLE a) | Returns the maximum 向下取整,最数轴上最接近要求的值的左边的值 如:6.10->6 -3.4->-4 |
BIGINT | ceil(DOUBLE a), ceiling(DOUBLE a) | Returns the minimum BIGINT value that is equal to or greater than 求其不小于小给定实数的最小整数如:ceil(6) = ceil(6.1)= ceil(6.9) = 6 |
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型随机数seed是随机因子 |
DOUBLE | exp(DOUBLE a), exp(DECIMAL a) | Returns 返回e的a幂次方, a可为小数 |
DOUBLE | ln(DOUBLE a), ln(DECIMAL a) | Returns the natural logarithm of the argument 以自然数为底d的对数,a可为小数 |
DOUBLE | log10(DOUBLE a), log10(DECIMAL a) | Returns the base-10 logarithm of the argument 以10为底d的对数,a可为小数 |
DOUBLE | log2(DOUBLE a), log2(DECIMAL a) | Returns the base-2 logarithm of the argument 以2为底数d的对数,a可为小数 |
DOUBLE | log(DOUBLE base, DOUBLE a) log(DECIMAL base, DECIMAL a) | Returns the base- 以base为底的对数,base 与 a都是DOUBLE类型 |
DOUBLE | pow(DOUBLE a, DOUBLE p), power(DOUBLE a, DOUBLE p) | Returns 计算a的p次幂 |
DOUBLE | sqrt(DOUBLE a), sqrt(DECIMAL a) | Returns the square root of 计算a的平方根 |
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). 计算二进制a的STRING类型,a为BIGINT类型 |
STRING | hex(BIGINT a) hex(STRING a) hex(BINARY a) | If the argument is an 计算十六进制a的STRING类型,如果a为STRING类型就转换成字符相对应的十六进制 |
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. ( hex的逆方法 |
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). 将GIGINT/STRING类型的num从from_base进制转换成to_base进制 |
DOUBLE | abs(DOUBLE a) | Returns the absolute value. 计算a的绝对值 |
INT or DOUBLE | pmod(INT a, INT b), pmod(DOUBLE a, DOUBLE b) | Returns the positive value of a对b取模 |
DOUBLE | sin(DOUBLE a), sin(DECIMAL a) | Returns the sine of 求a的正弦值 |
DOUBLE | asin(DOUBLE a), asin(DECIMAL a) | Returns the arc sin of 求d的反正弦值 |
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 返回a |
INT or DOUBLE | negative(INT a), negative(DOUBLE a) | Returns 返回a的相反数 |
DOUBLE or INT | sign(DOUBLE a), sign(DECIMAL a) | Returns the sign of 如果a是正数则返回1.0,是负数则返回-1.0,否则返回0.0 |
DOUBLE | e() | Returns the value of 数学常数e |
DOUBLE | pi() | Returns the value of 数学常数pi |
BIGINT | factorial(INT a) | Returns the factorial of a (as of Hive 1.2.0). Valid a is [0..20].求a的阶乘 |
DOUBLE | cbrt(DOUBLE a) | Returns the cube root of a double value (as of Hive 1.2.0).求a的立方根 |
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, INTb) 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|INTa, 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). 求最小值 |
集合函数
Return Type | Name(Signature) | Description |
---|---|---|
int | size(Map<K.V>) | Returns the number of elements in the map type. 求map的长度 |
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. 返回map中的所有key |
array<V> | map_values(Map<K.V>) | Returns an unordered array containing the values of the input map. 返回map中的所有value |
boolean | array_contains(Array<T>, value) | Returns TRUE if the array contains value. 如该数组Array<T>包含value返回true。,否则返回false |
array | sort_array(Array<T>) | 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). 按自然顺序对数组进行排序并返回 |
类型转换函数
Return Type | Name(Signature) | Description |
---|---|---|
binary | binary(string|binary) | Casts the parameter into a binary. 将输入的值转换成二进制 |
Expected "=" to follow "type" | cast(expr as <type>) | Converts the results of the expression expr to <type>. For example, cast('1' as BIGINT) will convert the string '1' to its integral representation. A null is returned if the conversion does not succeed. If cast(expr as boolean) Hive returns true for a non-empty string. 将expr转换成type类型 如:cast("1" as BIGINT) 将字符串1转换成了BIGINT类型,如果转换失败将返回NULL |
日期函数
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". 将时间的秒值转换成format格式(format可为“yyyy-MM-dd hh:mm:ss”,“yyyy-MM-dd hh”,“yyyy-MM-dd hh:mm”等等)如from_unixtime(1250111000,"yyyy-MM-dd") 得到2009-03-12 |
bigint | unix_timestamp() | Gets current Unix timestamp in seconds. 获取本地时区下的时间戳 |
bigint | unix_timestamp(string date) | Converts time string in format 将格式为yyyy-MM-dd HH:mm:ss的时间字符串转换成时间戳 如unix_timestamp('2009-03-20 11:30:01') = 1237573801 |
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. 将指定时间字符串格式字符串转换成Unix时间戳,如果格式不对返回0 如:unix_timestamp('2009-03-20', 'yyyy-MM-dd') = 1237532400 |
string | to_date(string timestamp) | Returns the date part of a timestamp string: to_date("1970-01-01 00:00:00") = "1970-01-01". 返回时间字符串的日期部分 |
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. 返回当前时间属性哪个季度 如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. 返回时间字符串位于一年中的第几个周内 如weekofyear("1970-11-01 00:00:00") = 44, weekofyear("1970-11-01") = 44 |
int | datediff(string enddate, string startdate) | Returns the number of days from startdate to enddate: datediff('2009-03-01', '2009-02-27') = 2. 计算开始时间startdate到结束时间enddate相差的天数 |
string | date_add(string startdate, int days) | Adds a number of days to startdate: date_add('2008-12-31', 1) = '2009-01-01'. 从开始时间startdate加上days |
string | date_sub(string startdate, int days) | Subtracts a number of days to startdate: date_sub('2008-12-31', 1) = '2008-12-30'. 从开始时间startdate减去days |
timestamp | from_utc_timestamp(timestamp, string timezone) | Assumes given timestamp is UTC and converts to given timezone (as of Hive 0.8.0). For example, from_utc_timestamp('1970-01-01 08:00:00','PST') returns 1970-01-01 00:00:00. 如果给定的时间戳并非UTC,则将其转化成指定的时区下时间戳 |
timestamp | to_utc_timestamp(timestamp, string timezone) | Assumes given timestamp is in given timezone and converts to UTC (as of Hive 0.8.0). For example, to_utc_timestamp('1970-01-01 00:00:00','PST') returns 1970-01-01 08:00:00. 如果给定的时间戳指定的时区下时间戳,则将其转化成UTC下的时间戳 |
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) | 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. 返回当前时间下再增加num_months个月的日期 |
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. 返回这个月的最后一天的日期,忽略时分秒部分(HH:mm:ss) |
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 Hive1.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. 返回当前时间的下一个星期X所对应的日期 如:next_day('2015-01-14', 'TU') = 2015-01-20 以2015-01-14为开始时间,其下一个星期二所对应的日期为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. 返回时间的最开始年份或月份 如trunc("2016-06-26",“MM”)=2016-06-01 trunc("2016-06-26",“YY”)=2016-01-01 注意所支持的格式为MONTH/MON/MM, YEAR/YYYY/YY |
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 返回date1与date2之间相差的月份,如date1>date2,则返回正,如果date1<date2,则返回负,否则返回0.0 如:months_between('1997-02-28 10:30:00', '1996-10-30') = 3.94959677 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. 如果testCondition 为true就返回valueTrue,否则返回valueFalseOrNull ,(valueTrue,valueFalseOrNull为泛型) |
T | nvl(T value, T default_value) | Returns default value if value is null else returns value (as of HIve 0.11). 如果value值为NULL就返回default_value,否则返回value |
T | COALESCE(T v1, T v2, ...) | Returns the first v that is not NULL, or NULL if all v's are NULL. 返回第一非null的值,如果全部都为NULL就返回NULL 如:COALESCE (NULL,44,55)=44/strong> |
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. 如果a=b就返回c,a=d就返回e,否则返回f 如CASE 4 WHEN 5 THEN 5 WHEN 4 THEN 4 ELSE 3 END 将返回4 |
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. 如果a=ture就返回b,c= ture就返回d,否则返回e 如:CASE WHEN 5>0 THEN 5 WHEN 4>0 THEN 4 ELSE 0 END 将返回5;CASE WHEN 5<0 THEN 5 WHEN 4<0 THEN 4 ELSE 0 END 将返回0 |
boolean | isnull( a ) | Returns true if a is NULL and false otherwise. 如果a为null就返回true,否则返回false |
boolean | isnotnull ( a ) | Returns true if a is not NULL and false otherwise. 如果a为非null就返回true,否则返回false |
字符函数
Return Type | Name(Signature) | Description |
---|---|---|
int | ascii(string str) | Returns the numeric value of the first character of str. 返回str中首个ASCII字符串的整数值 |
string | base64(binary bin) | Converts the argument from binary to a base 64 string (as of Hive 0.12.0).. 将二进制bin转换成64位的字符串 |
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.. 与ngram类似,但context_ngram()允许你预算指定上下文(数组)来去查找子序列,具体看StatisticsAndDataMining(这里的解释更易懂) |
string | concat_ws(string SEP, string A, string B...) | Like concat() above, but with custom separator SEP.. 与concat()类似,但使用指定的分隔符喜进行分隔 |
string | concat_ws(string SEP, array<string>) | Like concat_ws() above, but taking an array of strings. (as of Hive 0.9.0). 拼接Array中的元素并用指定分隔符进行分隔 |
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.). 使用指定的字符集charset将二进制值bin解码成字符串,支持的字符集有:'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16',如果任意输入参数为NULL都将返回NULL |
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.). 使用指定的字符集charset将字符串编码成二进制值,支持的字符集有:'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16',如果任一输入参数为NULL都将返回NULL |
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.. 返回以逗号分隔的字符串中str出现的位置,如果参数str为逗号或查找失败将返回0,如果任一参数为NULL将返回NULL回 |
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). 将数值X转换成"#,###,###.##"格式字符串,并保留d位小数,如果d为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.. 从指定路径上的JSON字符串抽取出JSON对象,并返回这个对象的JSON格式,如果输入的JSON是非法的将返回NULL,注意此路径上JSON字符串只能由数字 字母 下划线组成且不能有大写字母和特殊字符,且key不能由数字开头,这是由于Hive对列名的限制 |
boolean | in_file(string str, string filename) | Returns true if the string str appears as an entire line in filename.. 如果文件名为filename的文件中有一行数据与字符串str匹配成功就返回true |
int | instr(string str, string substr) | Returns the position of the first occurrence of 查找字符串str中子字符串substr出现的位置,如果查找失败将返回0,如果任一参数为Null将返回null,注意位置为从1开始的 |
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.. 查找字符串str中的pos位置后字符串substr第一次出现的位置 |
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'.. 将字符串A的所有字母转换成小写字母 |
string | lpad(string str, int len, string pad) | Returns str, left-padded with pad to a length of len.. 从左边开始对字符串str使用字符串pad填充,最终len长度为止,如果字符串str本身长度比len大的话,将去掉多余的部分 |
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 '.. 去掉字符串A前面的空格 |
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.. 返回出现次数TOP K的的子序列,n表示子序列的长度,具体看StatisticsAndDataMining (这里的解释更易懂) |
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'.. 返回从URL中抽取指定部分的内容,参数url是URL字符串,而参数partToExtract是要抽取的部分,这个参数包含(HOST, PATH, QUERY, REF, PROTOCOL, AUTHORITY, FILE, and USERINFO,例如:parse_url('http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1', 'HOST') ='facebook.com',如果参数partToExtract值为QUERY则必须指定第三个参数key 如:parse_url('http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1', 'QUERY', 'k1') =‘v1’ |
string | printf(String format, Obj... args) | Returns the input formatted according do printf-style format strings (as of Hive0.9.0).. 按照printf风格格式输出字符串 |
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.. 抽取字符串subject中符合正则表达式pattern的第index个部分的子字符串,注意些预定义字符的使用,如第二个参数如果使用'\s'将被匹配到s,'\\s'才是匹配空格 |
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.. 按照Java正则表达式PATTERN将字符串INTIAL_STRING中符合条件的部分成REPLACEMENT所指定的字符串,如里REPLACEMENT这空的话,抽符合正则的部分将被去掉 如:regexp_replace("foobar", "oo|ar", "") = 'fb.' 注意些预定义字符的使用,如第二个参数如果使用'\s'将被匹配到s,'\\s'才是匹配空格 |
string | repeat(string str, int n) | Repeats str n times.. 重复输出n次字符串str |
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.. 从右边开始对字符串str使用字符串pad填充,最终len长度为止,如果字符串str本身长度比len大的话,将去掉多余的部分 |
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") ).. 字符串str将被转换成单词数组,如:sentences('Hello there! How are you?') =( ("Hello", "there"), ("How", "are", "you") ) |
string | space(int n) | Returns a string of n spaces.. 返回n个空格 |
array | split(string str, string pat) | Splits str around pat (pat is a regular expression).. 按照正则表达式pat来分割字符串str,并将分割后的数组字符串的形式返回 |
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.. 将字符串str按照指定分隔符转换成Map,第一个参数是需要转换字符串,第二个参数是键值对之间的分隔符,默认为逗号;第三个参数是键值之间的分隔符,默认为"=" |
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]).. 对于字符串A,从start位置开始截取字符串并返回 |
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]).. 对于二进制/字符串A,从start位置开始截取长度为length的字符串并返回 |
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'.. 截取第count分隔符之前的字符串,如count为正则从左边开始截取,如果为负则从右边开始截取 |
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.. 将input出现在from中的字符串替换成to中的字符串 如:translate("MOBIN","BIN","M")="MOM" |
string | trim(string A) | Returns the string resulting from trimming spaces from both ends of A. For example, trim(' foobar ') results in 'foobar'. 将字符串A前后出现的空格去掉 |
binary | unbase64(string str) | Converts the argument from a base 64 string to BINARY. (As of Hive 0.12.0.). 将64位的字符串转换二进制值 |
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'.. 将字符串A中的字母转换成大写字母 |
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.). 将字符串A转换第一个字母大写其余字母的字符串 |
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.. 计算两个字符串之间的差异大小 如:levenshtein('kitten', 'sitting') = 3 |
string | soundex(string A) | Returns soundex code of the string (as of Hive 1.2.0). For example, soundex('Miller') results in M460.. 将普通字符串转换成soundex字符串 |
聚合函数
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. 统计总行数,包括含有NULL值的行 count(expr) - Returns the number of rows for which the supplied expression is non-NULL. 统计提供非NULL的expr表达式值的行数 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. 统计提供非NULL且去重后的expr表达式值的行数 |
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. sum(col),表示求指定列的和,sum(DISTINCT col)表示求去重后的列的和 |
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. avg(col),表示求指定列的平均值,avg(DISTINCT col)表示求去重后的列的平均值 |
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. 返回col的p%分位数 |
表生成函数
Return Type | Name(Signature) | Description |
---|---|---|
Array Type | explode(array<TYPE> a) | For each element in a, generates a row containing that element. 对于a中的每个元素,将生成一行且包含该元素 |
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.). 每行对应每个map键-值,其中一个字段是map的键,另一个字段是map的值 |
N rows | posexplode(ARRAY) | Behaves like 与explode类似,不同的是还返回各元素在数组中的位置 |
N rows | 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.. 把M列转换成N行,每行有M/N个字段,其中n必须是个常数 |
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 从一个JSON字符串中获取多个键并作为一个元组返回,与get_json_object不同的是此函数能一次获取多个键值 |
tuple | parse_url_tuple(url, p1, p2, ...) | This is similar to the 返回从URL中抽取指定N部分的内容,参数url是URL字符串,而参数p1,p2,....是要抽取的部分,这个参数包含HOST, PATH, QUERY, REF, PROTOCOL, AUTHORITY, FILE, USERINFO, QUERY:<KEY> |
| inline(ARRAY<STRUCT[,STRUCT]>) | Explodes an array of structs into a table. (As of Hive 0.10.). 将结构体数组提取出来并插入到表中 |
参考资料
LanguageManual UDF
《Hive权威指南》
聚合函数
hive函数的分类
hive的客户端
显示当前会话有多少函数可用SHOW FUNCTIONS;
如:
hive> show functions ;
OK
!
!=
%
显示函数的描述信息DESC FUNCTION concat;
如:
hive> DESC FUNCTION concat;
OK
concat(str1, str2, ... strN) - returns the concatenation of str1, str2, ... strN or concat(bin1, bin2, ... binN) - returns the concatenation of bytes in binary data bin1, bin2, ... binN
Time taken: 0.005 seconds, Fetched: 1 row(s)
显示函数的扩展描述信息DESC FUNCTION EXTENDED concat;
一.简单函数
1.数学函数
返回对a四舍五入的BIGINT值
1 返回值: 2 hive> select round(2.5); 3 OK 4 3.0 5 Time taken: 0.093 seconds, Fetched: 1 row(s)
返回DOUBLE型d的保留n位小数的DOUBLW型的近似值 round(DOUBLE a, INT d)
1 返回值:double 2 hive> select round(0.5002,2); 3 OK 4 0.5 5 Time taken: 0.074 seconds, Fetched: 1 row(s)
银行家舍入法(1~4:舍,6~9:进,5->前位数是偶:舍,5->前位数是奇:进) bround(DOUBLE a)
返回值:double bround(2.5) = 2, bround(3.5) = 4.
银行家舍入法,保留d位小数 bround(DOUBLE a, INT d)
1 返回值:double 2 bround(8.25, 1) = 8.2, bround(8.35, 1) = 8.4
向下取整,最数轴上最接近要求的值的左边的值 如:6.10->6 -3.4->-4 floor(DOUBLE a)
1 返回值:double 2 hive> select floor(6.10); 3 OK 4 6 5 Time taken: 0.07 seconds, Fetched: 1 row(s) 6 hive> select floor(-3.4); 7 OK 8 -4 9 Time taken: 0.104 seconds, Fetched: 1 row(s)
求其不小于小给定实数的最小整数如:ceil(6) = ceil(6.1)= ceil(6.9) = 6 ceil(DOUBLE a), ceiling(DOUBLE a)
1 返回值:BIGINT 2 hive> select ceil(6); 3 OK 4 6 5 Time taken: 0.2 seconds, Fetched: 1 row(s) 6 hive> select ceil(6.1); 7 OK 8 7 9 Time taken: 0.061 seconds, Fetched: 1 row(s) 10 hive> select ceil(6.9); 11 OK 12 7 13 Time taken: 0.153 seconds, Fetched: 1 row(s)
每行返回一个DOUBLE型随机数seed是随机因子 rand(), rand(INT seed)
1 返回值:DOUBLE 2 hive> select rand(2); 3 OK 4 0.7311469360199058 5 Time taken: 0.068 seconds, Fetched: 1 row(s) 6 hive> select rand(); 7 OK 8 0.7859071491095923 9 Time taken: 0.064 seconds, Fetched: 1 row(s)
返回e的a幂次方, a可为小数 exp(DOUBLE a), exp(DECIMAL a)
1 返回值:double 2 hive> select exp(2); 3 OK 4 7.38905609893065 5 Time taken: 0.1 seconds, Fetched: 1 row(s)
以自然数为底d的对数,a可为小数 ln(DOUBLE a), ln(DECIMAL a)
1 返回值:double 2 ln(DOUBLE a), ln(DECIMAL a) 3 > select ln(3); 4 OK 5 1.0986122886681098 6 Time taken: 0.081 seconds, Fetched: 1 row(s) 7 hive> select ln(3.2); 8 OK 9 1.1631508098056809 10 Time taken: 0.067 seconds, Fetched: 1 row(s)
以10为底d的对数,a可为小数 log10(DOUBLE a), log10(DECIMAL a)
1 返回值:double 2 hive> select log10(3.2); 3 OK 4 0.505149978319906 5 Time taken: 0.084 seconds, Fetched: 1 row(s) 6 hive> select log10(3); 7 OK 8 0.47712125471966244 9 Time taken: 0.075 seconds, Fetched: 1 row(s)
以2为底数d的对数,a可为小数 log2(DOUBLE a), log2(DECIMAL a)
1 返回值:double 2 hive> 3 > select log2(3); 4 OK 5 1.5849625007211563 6 Time taken: 0.083 seconds, Fetched: 1 row(s) 7 hive> select log2(3.2); 8 OK 9 1.6780719051126378 10 Time taken: 0.07 seconds, Fetched: 1 row(s)
以base为底的对数,base 与 a都是DOUBLE类型
log(DOUBLE base, DOUBLE a)
log(DECIMAL base, DECIMAL a)
1 返回值:double 2 hive> select log(2,3.2); 3 OK 4 1.6780719051126378 5 Time taken: 0.084 seconds, Fetched: 1 row(s) 6 hive> select log(2,3); 7 OK 8 1.5849625007211563 9 Time taken: 0.066 seconds, Fetched: 1 row(s)
计算a的p次幂 pow(DOUBLE a, DOUBLE p), power(DOUBLE a, DOUBLE p)
1 返回值:double 2 hive> select pow(2,4); 3 OK 4 16.0 5 Time taken: 0.065 seconds, Fetched: 1 row(s)
计算a的平方根 sqrt(DOUBLE a), sqrt(DECIMAL a)
1 返回值:double 2 select sqrt(2);
计算二进制a的STRING类型,a为BIGINT类型 bin(BIGINT a)
返回值:string hive> select bin(2); OK 10 Time taken: 0.194 seconds, Fetched: 1 row(s)
计算十六进制a的STRING类型,如果a为STRING类型就转换成字符相对应的十六进制 hex(BIGINT a) hex(STRING a) hex(BINARY a)
1 返回值:STRING 2 hive> select hex(2); 3 OK 4 2 5 Time taken: 0.097 seconds, Fetched: 1 row(s)
hex的逆方法
unhex(STRING a)
1 返回值:BINARY 2 hive> select unhex(2); 3 OK 4 5 Time taken: 0.077 seconds, Fetched: 1 row(s)
将GIGINT/STRING类型的num从from_base进制转换成to_base进制 conv(BIGINT num, INT from_base, INT to_base), conv(STRING num, INT from_base, INT to_base)
1 返回值:STRING 2 hive> select conv(2,10,2); 3 OK 4 10 5 Time taken: 0.075 seconds, Fetched: 1 row(s)
计算a的绝对值 abs(DOUBLE a)
1 返回值:DOUBLE 2 hive> select abs(-2); 3 OK 4 2 5 Time taken: 0.077 seconds, Fetched: 1 row(s)
a对b取模 pmod(INT a, INT b), pmod(DOUBLE a, DOUBLE b)
1 返回值:double 2 hive> select pmod(4,2); 3 OK 4 0 5 Time taken: 0.077 seconds, Fetched: 1 row(s)
求a的正弦值 sin(DOUBLE a), sin(DECIMAL a)
1 返回值:double 2 hive> select sin(2.5); 3 OK 4 0.5984721441039564 5 Time taken: 0.092 seconds, Fetched: 1 row(s)
求d的反正弦值 asin(DOUBLE a), asin(DECIMAL a)
1 返回值:double 2 hive> select asin(2.5); 3 OK 4 NaN 5 Time taken: 0.097 seconds, Fetched: 1 row(s)
求余弦值 cos(DOUBLE a), cos(DECIMAL a)
1 返回值:double 2 hive> select cos(2.5); 3 OK 4 -0.8011436155469337 5 Time taken: 0.087 seconds, Fetched: 1 row(s)
求反余弦值 acos(DOUBLE a), acos(DECIMAL a)
1 返回值:double 2 hive> select acos(2.5); 3 OK 4 NaN 5 Time taken: 0.091 seconds, Fetched: 1 row(s)
求正切值 tan(DOUBLE a), tan(DECIMAL a)
1 返回值:double 2 hive> select tan(2.5); 3 OK 4 -0.7470222972386603 5 Time taken: 0.076 seconds, Fetched: 1 row(s)
求反正切值 atan(DOUBLE a), atan(DECIMAL a)
1 返回值:double 2 hive> select atan(2.5); 3 OK 4 1.1902899496825317 5 Time taken: 0.074 seconds, Fetched: 1 row(s)
奖弧度值转换角度值 degrees(DOUBLE a), degrees(DECIMAL a)
1 返回值:DOUBLE 2 hive> select degrees(30); 3 OK 4 1718.8733853924698 5 Time taken: 0.114 seconds, Fetched: 1 row(s)
将角度值转换成弧度值 radians(DOUBLE a), radians(DOUBLE a)
1 返回值:double 2 hive> select radians(30); 3 OK 4 0.5235987755982988 5 Time taken: 0.093 seconds, Fetched: 1 row(s)
返回a positive(INT a), positive(DOUBLE a)
1 返回值:INT or DOUBLE 2 hive> select positive(2); 3 OK 4 2 5 Time taken: 0.124 seconds, Fetched: 1 row(s)
返回a的相反数 negative(INT a), negative(DOUBLE a)
1 返回值:double 2 hive> select negative(2); 3 OK 4 -2 5 Time taken: 0.066 seconds, Fetched: 1 row(s)
如果a是正数则返回1.0,是负数则返回-1.0,否则返回0.0 sign(DOUBLE a), sign(DECIMAL a)
1 返回值:DOUBLE or INT 2 hive> select sign(2); 3 OK 4 1.0 5 Time taken: 0.091 seconds, Fetched: 1 row(s)
数学常数e e()
1 返回值:double 2 hive> select e(); 3 OK 4 2.718281828459045 5 Time taken: 0.07 seconds, Fetched: 1 row(s)
数学常数pi pi()
1 返回值:double 2 hive> select pi(); 3 OK 4 3.141592653589793 5 Time taken: 0.082 seconds, Fetched: 1 row(s)
求a的阶乘 factorial(INT a)
1 返回值:BIGINT 2 select factorial(2);
求a的立方根 cbrt(DOUBLE a)
1 返回值:DOUBLE 2 select cbrt(2);
按位左移
shiftleft(TINYINT|SMALLINT|INT a, INT b)
shiftleft(BIGINT a, INT b)
1 返回值:int bigint 2 hive> select shiftleft(2,3);
按拉右移
shiftright(TINYINT|SMALLINT|INT a, INTb)
shiftright(BIGINT a, INT b)
1 返回值:INT BIGINT 2 hive> select shiftrigth(2,3);
无符号按位右移(<<<)
shiftrightunsigned(TINYINT|SMALLINT|INTa, INT b),
shiftrightunsigned(BIGINT a, INT b)
1 返回值:INT BIGINT 2 select shiftrightunsigned(2,3);
求最大值 greatest(T v1, T v2, ...)
1 返回值:T 2 hive> select greatest(2,3,6,7); 3 OK 4 7 5 Time taken: 0.072 seconds, Fetched: 1 row(s)
求最小值 least(T v1, T v2, ...)
1 返回值:double 2 hive> select least(2,3,6,7); 3 OK 4 2 5 Time taken: 0.079 seconds, Fetched: 1 row(s)
2.类型转换函数
将输入的值转换成二进制 binary(string|binary)
1 返回值:binary 2 hive> select binary('4'); 3 OK 4 4 5 Time taken: 0.08 seconds, Fetched: 1 row(s)
将expr转换成type类型 如:cast("1" as BIGINT) 将字符串1转换成了BIGINT类型,如果转换失败将返回NULL cast(expr as <type>)
1 返回值:Expected "=" to follow "type" 2 hive> select cast("1" as BIGINT) ; 3 OK 4 1 5 Time taken: 0.266 seconds, Fetched: 1 row(s)
3.日期函数
日期函数UNIX时间戳转日期函数: from_unixtime语法: from_unixtime(bigint unixtime[, string format])
1 返回值: string 2 说明: 转化UNIX时间戳(从1970-01-01 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式 3 举例: 4 hive> select from_unixtime(1323308943,'yyyyMMdd'); 5 OK 6 20111208 7 Time taken: 0.152 seconds, Fetched: 1 row(s)
获取当前UNIX时间戳函数: unix_timestamp语法: unix_timestamp()
1 返回值: bigint 2 说明: 获得当前时区的UNIX时间戳 3 举例: 4 Time taken: 0.152 seconds, Fetched: 1 row(s) 5 hive> select unix_timestamp(); 6 OK 7 1487931871 8 Time taken: 0.106 seconds, Fetched: 1 row(s)
日期转UNIX时间戳函数: unix_timestamp语法: unix_timestamp(string date)
1 返回值: bigint 2 说明: 转换格式为“yyyy-MM-dd HH:mm:ss“的日期到UNIX时间戳。如果转化失败,则返回0。 3 举例: 4 hive> select unix_timestamp('2011-12-07 13:01:03'); 5 OK 6 1323234063 7 Time taken: 0.083 seconds, Fetched: 1 row(s)
指定格式日期转UNIX时间戳函数: unix_timestamp语法: unix_timestamp(string date, string pattern)
1 返回值: bigint 2 说明: 转换pattern格式的日期到UNIX时间戳。如果转化失败,则返回0。 3 举例: 4 hive> select unix_timestamp('20111207 13:01:03','yyyyMMdd HH:mm:ss'); 5 OK 6 1323234063 7 Time taken: 0.079 seconds, Fetched: 1 row(s)
日期时间转日期函数: to_date语法: to_date(string timestamp)
1 返回值: string 2 说明: 返回日期时间字段中的日期部分。 3 举例: 4 hive> select to_date('2011-12-08 10:03:01') ; 5 OK 6 2011-12-08 7 Time taken: 0.194 seconds, Fetched: 1 row(s)
日期转年函数: year语法: year(string date)
1 返回值: int 2 说明: 返回日期中的年。 3 举例: 4 hive> select year('2011-12-08 10:03:01'); 5 OK 6 2011 7 Time taken: 0.168 seconds, Fetched: 1 row(s)
日期转月函数: month语法: month (string date)
1 返回值: int 2 说明: 返回日期中的月份。 3 举例: 4 hive> select month('2011-12-08 10:03:01'); 5 OK 6 12 7 Time taken: 0.084 seconds, Fetched: 1 row(s)
1 hive> select month('2011-08-08'); 2 OK 3 8 4 Time taken: 0.095 seconds, Fetched: 1 row(s)
日期转天函数: day语法: day (string date)
1 返回值: int 2 说明: 返回日期中的天。 3 举例: 4 hive> select day('2011-12-08 10:03:01'); 5 OK 6 8 7 Time taken: 0.115 seconds, Fetched: 1 row(s)
1 hive> select day('2011-12-24'); 2 OK 3 24 4 Time taken: 0.294 seconds, Fetched: 1 row(s)
日期转小时函数: hour语法: hour (string date)
1 返回值: int 2 说明: 返回日期中的小时。 3 举例: 4 hive> select hour('2011-12-08 10:03:01'); 5 OK 6 10 7 Time taken: 0.082 seconds, Fetched: 1 row(s)
日期转分钟函数: minute语法: minute (string date)
1 返回值: int 2 说明: 返回日期中的分钟。 3 举例: 4 hive> select minute('2011-12-08 10:03:01'); 5 OK 6 3 7 Time taken: 0.181 seconds, Fetched: 1 row(s)
日期转秒函数: second语法: second (string date)
1 返回值: int 2 说明: 返回日期中的秒。 3 举例: 4 hive> select second('2011-12-08 10:03:01'); 5 OK 6 1 7 Time taken: 0.693 seconds, Fetched: 1 row(s)
日期转周函数: weekofyear语法: weekofyear (string date)
1 返回值: int 2 说明: 返回日期在当前的周数。 3 举例: 4 hive> select weekofyear('2011-12-08 10:03:01') 5 > ; 6 OK 7 49 8 Time taken: 0.119 seconds, Fetched: 1 row(s)
日期比较函数: datediff语法: datediff(string enddate, string startdate)
1 返回值: int 2 说明: 返回结束日期减去开始日期的天数。 3 举例: 4 hive> select datediff('2012-12-08','2012-05-09'); 5 OK 6 213 7 Time taken: 0.082 seconds, Fetched: 1 row(s)
日期增加函数: date_add语法: date_add(string startdate, int days)
1 返回值: string 2 说明: 返回开始日期startdate增加days天后的日期。 3 举例: 4 hive> select date_add('2012-12-08',10); 5 OK 6 2012-12-18 7 Time taken: 0.201 seconds, Fetched: 1 row(s)
日期减少函数: date_sub语法: date_sub (string startdate, int days)
1 返回值: string 2 说明: 返回开始日期startdate减少days天后的日期。 3 举例: 4 hive> select date_sub('2012-12-08',10); 5 OK 6 2012-11-28 7 Time taken: 0.125 seconds, Fetched: 1 row(s)
返回这个月的最后一天的日期,忽略时分秒部分(HH:mm:ss) last_day(string date)
1 返回值:string 2 hive> select last_day('2017-02-17 08:34:23'); 3 OK 4 2017-02-28 5 Time taken: 0.082 seconds, Fetched: 1 row(s)
返回当前时间的下一个星期X所对应的日期 如:next_day('2015-01-14', 'TU') = 2015-01-20 以2015-01-14为开始时间,其下一个星期二所对应的日期为2015-01-20
1 返回值:string 2 hive> select next_day('2015-01-14', 'TU') ; 3 OK 4 2015-01-20 5 Time taken: 0.319 seconds, Fetched: 1 row(s)
返回当前时间属性哪个季度 如quarter('2015-04-08') = 2
1 返回值:int 2 quarter(date/timestamp/string)
返回当前时间日期
返回值:date hive> select current_date; OK 2017-02-25 Time taken: 0.087 seconds, Fetched: 1 row(s)
如果给定的时间戳并非UTC,则将其转化成指定的时区下时间戳
1 返回值:timestamp 2 from_utc_timestamp(timestamp, string timezone) 3 hive> select from_utc_timestamp('1970-01-01 08:00:00','PST'); 4 OK 5 1970-01-01 00:00:00 6 Time taken: 0.122 seconds, Fetched: 1 row(s)
如果给定的时间戳指定的时区下时间戳,则将其转化成UTC下的时间戳 to_utc_timestamp(timestamp, string timezone)
1 返回值:timestamp 2 hive> select to_utc_timestamp('1970-01-01 00:00:00','PST'); 3 OK 4 1970-01-01 08:00:00 5 Time taken: 0.099 seconds, Fetched: 1 row(s)
返回当前时间戳
1 返回值:timestamp 2 hive> select current_timestamp; 3 OK 4 2017-02-25 00:28:46.724 5 Time taken: 0.069 seconds, Fetched: 1 row(s)
返回当前时间下再增加num_months个月的日期 add_months(string start_date, int num_months)
1 返回值:string 2 hive> select add_months('2017-02-10', 2); 3 OK 4 2017-04-10 5 Time taken: 0.061 seconds, Fetched: 1 row(s)
5.条件函数
如果testCondition 为true就返回valueTrue,否则返回valueFalseOrNull ,(valueTrue,valueFalseOrNull为泛型)
if(boolean testCondition, T valueTrue, T valueFalseOrNull)
1 返回值:T
如果value值为NULL就返回default_value,否则返回value
nvl(T value, T default_value)
1 返回值:T
返回第一非null的值,如果全部都为NULL就返回NULL 如:COALESCE (NULL,44,55)=44/strong>
COALESCE(T v1, T v2, ...)
1 返回值:T
如果a=b就返回c,a=d就返回e,否则返回f 如CASE 4 WHEN 5 THEN 5 WHEN 4 THEN 4 ELSE 3 END 将返回4
CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END
1 返回值:T
如果a=ture就返回b,c= ture就返回d,否则返回e 如:CASE WHEN 5>0 THEN 5 WHEN 4>0 THEN 4 ELSE 0 END 将返回5;CASE WHEN 5<0 THEN 5 WHEN 4<0 THEN 4 ELSE 0 END 将返回0
CASE WHEN a THEN b [WHEN c THEN d]* [ELSE e] END
1 返回值:T
如果a为null就返回true,否则返回false
isnull( a )
1 返回值:boolean
如果a为非null就返回true,否则返回false
isnotnull ( a )
1 返回值:boolean
6.字符函数
返回str中首个ASCII字符串的整数值
ascii(string str)
1 返回值:int
将二进制bin转换成64位的字符串
base64(binary bin)
1 返回值:string
对二进制字节码或字符串按次序进行拼接
concat(string|binary A, string|binary B...)
1 返回值:string
与ngram类似,但context_ngram()允许你预算指定上下文(数组)来去查找子序列,具体看StatisticsAndDataMining(这里的解释更易懂)
context_ngrams(array<array<string>>, array<string>, int K, int pf)
1 返回值:array<struct<string,double>>
与concat()类似,但使用指定的分隔符喜进行分隔
concat_ws(string SEP, string A, string B...)
1 返回值:string
拼接Array中的元素并用指定分隔符进行分隔
concat_ws(string SEP, array<string>)
1 返回值:string
使用指定的字符集charset将字符串编码成二进制值,支持的字符集有:'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16',如果任一输入参数为NULL都将返回NULL
encode(string src, string charset)
1 返回值:binary
返回以逗号分隔的字符串中str出现的位置,如果参数str为逗号或查找失败将返回0,如果任一参数为NULL将返回NULL回
find_in_set(string str, string strList)
1 返回值:int
将数值X转换成"#,###,###.##"格式字符串,并保留d位小数,如果d为0,将进行四舍五入且不保留小数
format_number(number x, int d)
1 返回值:string
从指定路径上的JSON字符串抽取出JSON对象,并返回这个对象的JSON格式,如果输入的JSON是非法的将返回NULL,注意此路径上JSON字符串只能由数字 字母 下划线组成且不能有大写字母和特殊字符,且key不能由数字开头,这是由于Hive对列名的限制
get_json_object(string json_string, string path)
1 返回值:string
如果文件名为filename的文件中有一行数据与字符串str匹配成功就返回true
in_file(string str, string filename)
1 返回值:boolean
查找字符串str中子字符串substr出现的位置,如果查找失败将返回0,如果任一参数为Null将返回null,注意位置为从1开始的
instr(string str, string substr)
1 返回值:int
返回字符串的长度
length(string A)
1 返回值:int
查找字符串str中的pos位置后字符串substr第一次出现的位置
locate(string substr, string str[, int pos])
1 返回值:int
将字符串A的所有字母转换成小写字母
lower(string A) lcase(string A)
1 返回值:string
从左边开始对字符串str使用字符串pad填充,最终len长度为止,如果字符串str本身长度比len大的话,将去掉多余的部分
lpad(string str, int len, string pad)
1 返回值:string
去掉字符串A前面的空格
ltrim(string A)
1 返回值:string
返回出现次数TOP K的的子序列,n表示子序列的长度,具体看StatisticsAndDataMining (这里的解释更易懂)
ngrams(array<array<string>>, int N, int K, int pf)
1 返回值:array<struct<string,double>>
返回从URL中抽取指定部分的内容,参数url是URL字符串,而参数partToExtract是要抽取的部分,这个参数包含(HOST, PATH, QUERY, REF, PROTOCOL, AUTHORITY, FILE, and USERINFO,例如:parse_url('http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1', 'HOST') ='facebook.com',如果参数partToExtract值为QUERY则必须指定第三个参数key 如:parse_url('http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1', 'QUERY', 'k1') =‘v1’
parse_url(string urlString, string partToExtract [, string keyToExtract])
1 返回值:string
按照printf风格格式输出字符串
printf(String format, Obj... args)
1 返回值:string
抽取字符串subject中符合正则表达式pattern的第index个部分的子字符串,注意些预定义字符的使用,如第二个参数如果使用'\s'将被匹配到s,'\\s'才是匹配空格
regexp_extract(string subject, string pattern, int index)
1 返回值:string
按照Java正则表达式PATTERN将字符串INTIAL_STRING中符合条件的部分成REPLACEMENT所指定的字符串,如里REPLACEMENT这空的话,抽符合正则的部分将被去掉 如:regexp_replace("foobar", "oo|ar", "") = 'fb.' 注意些预定义字符的使用,如第二个参数如果使用'\s'将被匹配到s,'\\s'才是匹配空格
regexp_replace(string INITIAL_STRING, string PATTERN, string REPLACEMENT)
1 返回值:string
重复输出n次字符串str
repeat(string str, int n)
1 返回值: 2 string
反转字符串
reverse(string A)
1 返回值:string
从右边开始对字符串str使用字符串pad填充,最终len长度为止,如果字符串str本身长度比len大的话,将去掉多余的部分
rpad(string str, int len, string pad)
1 返回值:string
去掉字符串后面出现的空格
rtrim(string A)
1 返回值:string
字符串str将被转换成单词数组,如:sentences('Hello there! How are you?') =( ("Hello", "there"), ("How", "are", "you") )
sentences(string str, string lang, string locale)
1 返回值:array<array<string>>
返回n个空格
space(int n)
返回值:string
按照正则表达式pat来分割字符串str,并将分割后的数组字符串的形式返回
split(string str, string pat)
1 返回值:string
将字符串str按照指定分隔符转换成Map,第一个参数是需要转换字符串,第二个参数是键值对之间的分隔符,默认为逗号;第三个参数是键值之间的分隔符,默认为"="
str_to_map(text[, delimiter1, delimiter2])
1 返回值:map<string,string>
对于字符串A,从start位置开始截取字符串并返回
substr(string|binary A, int start) substring(string|binary A, int start)
1 返回值:string
对于二进制/字符串A,从start位置开始截取长度为length的字符串并返回
substr(string|binary A, int start, int len) substring(string|binary A, int start, int len)
1 返回值:string
截取第count分隔符之前的字符串,如count为正则从左边开始截取,如果为负则从右边开始截取
substring_index(string A, string delim, int count)
1 返回值:string
将input出现在from中的字符串替换成to中的字符串 如:translate("MOBIN","BIN","M")="MOM"
translate(string|char|varchar input, string|char|varchar from, string|char|varchar to)
1 返回值:string
将64位的字符串转换二进制值
unbase64(string str)
1 返回值:binary
将字符串A中的字母转换成大写字母
upper(string A) ucase(string A)
1 返回值:string
将字符串A转换第一个字母大写其余字母的字符串
initcap(string A)
1 返回值:string
计算两个字符串之间的差异大小 如:levenshtein('kitten', 'sitting') = 3
levenshtein(string A, string B)
1 返回值:int
将普通字符串转换成soundex字符串
soundex(string A)
1 返回值:string
7.字符串函数
分割字符串函数: split
语法: split(string str, string pat)
1 返回值: array 2 说明: 按照pat字符串分割str,会返回分割后的字符串数组 3 举例: 4 hive> select split('abtcdtef','t'); 5 OK 6 ["ab","cd","ef"] 7 Time taken: 0.118 seconds, Fetched: 1 row(s)
与GP,ORACLE不同,pad 不能默认
右补足函数:rpad
语法: rpad(string str, int len, string pad)
1 返回值: string 2 说明:将str进行用pad进行右补足到len位 3 举例: 4 hive> 5 > select rpad('abc',10,'td'); 6 OK 7 abctdtdtdt 8 Time taken: 0.077 seconds, Fetched: 1 row(s)
左补足函数:lpad
语法: lpad(string str, int len, string pad)
1 hive> 2 > select rpad('abc',10,'td'); 3 OK 4 abctdtdtdt 5 Time taken: 0.077 seconds, Fetched: 1 row(s)
首字符ascii函数:ascii
语法: ascii(string str)
1 返回值: int 2 说明:返回字符串str第一个字符的ascii码 3 举例: hive> select ascii('abcde'); 4 OK 5 97 6 Time taken: 0.066 seconds, Fetched: 1 row(s)
重复字符串函数:repeat
语法: repeat(string str, int n)
1 返回值: string 2 说明:返回重复n次后的str字符串 3 举例: 4 hive> select repeat('abc',5); 5 OK 6 abcabcabcabcabc 7 Time taken: 0.064 seconds, Fetched: 1 row(s)
空格字符串函数:space
语法: space(int n)
1 返回值: string 2 说明:返回长度为n的字符串 3 举例:hive> select space(10); 4 OK 5 6 Time taken: 0.101 seconds, Fetched: 1 row(s) 7 hive> select length(space(10)); 8 OK 9 10 10 Time taken: 1.905 seconds, Fetched: 1 row(s)
字符串长度函数:length
1 语法: length(string A) 2 返回值: int 3 说明:返回字符串A的长度 4 举例:hive> select length('abcedfg'); 5 OK 6 7 7 Time taken: 0.065 seconds, Fetched: 1 row(s)
字符串反转函数:reverse
语法: reverse(string A) 返回值: string 说明:返回字符串A的反转结果 举例: hive> select reverse('abcedfg'); OK gfdecba Time taken: 0.077 seconds, Fetched: 1 row(s)
字符串连接函数:concat
1 语法: concat(string A, string B…) 2 返回值: string 3 说明:返回输入字符串连接后的结果,支持任意个输入字符串 4 举例:hive> select concat('abc','def','gh'); 5 OK 6 abcdefgh 7 Time taken: 0.063 seconds, Fetched: 1 row(s)
带分隔符字符串连接函数:concat_ws
语法: concat_ws(string SEP, string A, string B…) 返回值: string 说明:返回输入字符串连接后的结果,SEP表示各个字符串间的分隔符 举例: hive> select concat_ws('-','abc','def','gh'); OK abc-def-gh Time taken: 0.06 seconds, Fetched: 1 row(s)
字符串截取函数:substr,substring
1 语法: substr(string A, int start),substring(string A, int start) 2 返回值: string 3 说明:返回字符串A从start位置到结尾的字符串 4 举例: hive> select substr('abcde',3); 5 OK 6 cde 7 Time taken: 0.062 seconds, Fetched: 1 row(s) 8 hive> select substring('abcde',3); 9 OK 10 cde 11 Time taken: 0.05 seconds, Fetched: 1 row(s) 12 hive> select substr('abcde',-1); 13 OK 14 e 15 Time taken: 0.061 seconds, Fetched: 1 row(s)
字符串截取函数:substr,substring
1 语法: substr(string A, int start, int len),substring(string A, int start, int len) 2 返回值: string 3 说明:返回字符串A从start位置开始,长度为len的字符串 4 举例: 5 hive> select substr('abcde',3,2); 6 OK 7 cd 8 Time taken: 0.07 seconds, Fetched: 1 row(s) 9 hive> select substring('abcde',3,2); 10 OK 11 cd 12 Time taken: 0.062 seconds, Fetched: 1 row(s) 13 hive> select substring('abcde',-2,2); 14 OK 15 de 16 Time taken: 0.113 seconds, Fetched: 1 row(s)
字符串转大写函数:upper,ucase
1 语法: upper(string A) ucase(string A) 2 返回值: string 3 说明:返回字符串A的大写格式 4 举例:hive> select upper('abSEd'); 5 OK 6 ABSED 7 Time taken: 0.059 seconds, Fetched: 1 row(s) 8 hive> select ucase('abSEd'); 9 OK 10 ABSED 11 Time taken: 0.058 seconds, Fetched: 1 row(s)
字符串转小写函数:lower,lcase
1 语法: lower(string A) lcase(string A) 2 返回值: string 3 说明:返回字符串A的小写格式 4 举例: 5 hive> select lower('abSEd'); 6 OK 7 absed 8 Time taken: 0.068 seconds, Fetched: 1 row(s) 9 hive> select lcase('abSEd'); 10 OK 11 absed 12 Time taken: 0.057 seconds, Fetched: 1 row(s)
去空格函数:trim
1 语法: trim(string A) 2 返回值: string 3 说明:去除字符串两边的空格 4 举例:hive> select trim(' abc '); 5 OK 6 abc 7 Time taken: 0.058 seconds, Fetched: 1 row(s)
左边去空格函数:ltrim
1 语法: ltrim(string A) 2 返回值: string 3 说明:去除字符串左边的空格 4 举例: hive> select ltrim(' abc '); 5 OK 6 abc 7 Time taken: 0.059 seconds, Fetched: 1 row(s)
右边去空格函数:rtrim
1 语法: rtrim(string A) 2 返回值: string 3 说明:去除字符串右边的空格 4 举例:hive> select rtrim(' abc '); 5 OK 6 abc 7 Time taken: 0.058 seconds, Fetched: 1 row(s)
正则表达式解析函数:regexp_extract
其中的index,是按照正则字符串()的位置
1 语法: regexp_extract(string subject, string pattern, int index) 2 返回值: string 3 说明:将字符串subject按照pattern正则表达式的规则拆分,返回index指定的字符。注意,在有些情况下要使用转义字符 4 举例: 5 hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 1); 6 OK 7 the 8 Time taken: 0.389 seconds, Fetched: 1 row(s) 9 hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 2); 10 OK 11 bar 12 Time taken: 0.051 seconds, Fetched: 1 row(s) 13 hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 0); 14 OK 15 foothebar 16 Time taken: 0.058 seconds, Fetched: 1 row(s)
函数parse_url,解析URL字符串
1 parse_url(url, partToExtract[, key]) - extracts a part from a URL 2 解析URL字符串,partToExtract的选项包含[HOST,PATH,QUERY,REF,PROTOCOL,FILE,AUTHORITY,USERINFO]。 3 举例: 4 hive> select parse_url('http://facebook.com/path/p1.php?query=1', 'HOST') ; 5 OK 6 facebook.com 7 Time taken: 0.286 seconds, Fetched: 1 row(s) 8 hive> select parse_url('http://facebook.com/path/p1.php?query=1', 'PATH'); 9 OK 10 /path/p1.php 11 Time taken: 0.069 seconds, Fetched: 1 row(s) 12 hive> select parse_url('http://facebook.com/path/p1.php?query=1', 'QUERY'); 13 OK 14 query=1 15 可以指定key来返回特定参数,例如 16 Time taken: 0.21 seconds, Fetched: 1 row(s) 17 hive> select parse_url('http://facebook.com/path/p1.php?query=1', 'QUERY','query'); 18 OK 19 1 20 Time taken: 0.057 seconds, Fetched: 1 row(s) 21 hive> select parse_url('http://facebook.com/path/p1.php?query=1#Ref', 'REF'); 22 OK 23 Ref 24 Time taken: 0.055 seconds, Fetched: 1 row(s) 25 hive> select parse_url('http://facebook.com/path/p1.php?query=1#Ref', 'PROTOCOL'); 26 OK 27 http 28 Time taken: 0.06 seconds, Fetched: 1 row(s)
1 hive> select parse_url_tuple('http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1', 'QUERY:k1', 'QUERY:k2'); 2 OK 3 v1 v2 4 Time taken: 0.2 seconds, Fetched: 1 row(s)
json解析函数:get_json_object
语法: get_json_object(string json_string, string path)
1 返回值: string 2 说明:解析json的字符串json_string,返回path指定的内容。如果输入的json字符串无效,那么返回NULL。 3 举例: hive> select get_json_object('{"store":{"fruit":\[{"weight":8,"type":"apple"},{"weight":9,"type":"pear"}],"bicycle":{"price":19.95,"color":"red"} }, "email":"amy@only_for_json_udf_test.net","owner":"amy"}','$.store'); 4 OK 5 {"fruit":[{"weight":8,"type":"apple"},{"weight":9,"type":"pear"}],"bicycle":{"price":19.95,"color":"red"}} 6 Time taken: 0.108 seconds, Fetched: 1 row(s) 7 8 hive> select get_json_object('{"store":{"fruit":\[{"weight":8,"type":"apple"},{"weight":9,"type":"pear"}],"bicycle":{"price":19.95,"color":"red"} }, "email":"amy@only_for_json_udf_test.net","owner":"amy"}','$.email'); 9 OK 10 amy@only_for_json_udf_test.net 11 12 hive> select get_json_object('{"store":{"fruit":\[{"weight":8,"type":"apple"},{"weight":9,"type":"pear"}],"bicycle":{"price":19.95,"color":"red"} }, "email":"amy@only_for_json_udf_test.net","owner":"amy"}','$.owner'); 13 OK 14 amy 15 Time taken: 0.499 seconds, Fetched: 1 row(s)
行转列:explode (posexplode Available as of Hive 0.13.0)
1 说明:将输入的一行数组或者map转换成列输出 2 语法:explode(array (or map)) 3 举例: 4 5 hive> select explode(split(concat_ws('-','1','2','3','4','5','6','7','8','9'),'-')); 6 OK 7 1 8 2 9 3 10 4 11 5 12 6 13 7 14 8 15 9 16 Time taken: 0.095 seconds, Fetched: 9 row(s)
二.集合函数
集合查找函数: find_in_set
语法: find_in_set(string str, string strList)
返回值: int 说明: 返回str在strlist第一次出现的位置,strlist是用逗号分割的字符串。如果没有找该str字符,则返回0 举例: hive> select find_in_set('ab','ef,ab,de'); OK 2 Time taken: 2.336 seconds, Fetched: 1 row(s) hive> select find_in_set('at','ef,ab,de'); OK 0 Time taken: 0.094 seconds, Fetched: 1 row(s)
hive提供了复合数据类型:
Structs: structs内部的数据可以通过DOT(.)来存取,例如,表中一列c的类型为STRUCT{a INT; b INT},我们可以通过c.a来访问域a
Maps(K-V对):访问指定域可以通过["指定域名称"]进行,例如,一个Map M包含了一个group-》gid的kv对,gid的值可以通过M[' group']来获取
Arrays:array中的数据为相同类型,例如,假如array A中元素['a','b','c'],则A[1]的值为'b'
Struct使用
1 create table qa_test.student_test(id INT, info struct<name:STRING, age:INT>) 2 ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' 3 COLLECTION ITEMS TERMINATED BY ':'; 4 5 hive> desc qa_test.student_test; 6 OK 7 id int 8 info struct<name:string,age:int> 9 Time taken: 0.048 seconds, Fetched: 2 row(s) 10 11 12 $cat test5.txt 13 1,zhou:30 14 2,yan:30 15 3,chen:20 16 4,li:80 17 18 19 LOAD DATA LOCAL INPATH '/home/hadoop/test/test5' INTO TABLE qa_test.student_test; 20 21 hive> select * from qa_test.student_test; 22 OK 23 1 {"name":"zhou","age":30} 24 2 {"name":"yan","age":30} 25 3 {"name":"chen","age":20} 26 4 {"name":"li","age":80} 27 28 29 hive> select info.age from qa_test.student_test; 30 OK 31 30 32 30 33 20 34 80 35 Time taken: 0.234 seconds, Fetched: 4 row(s) 36 hive> select info.name from qa_test.student_test; 37 OK 38 zhou 39 yan 40 chen 41 li 42 Time taken: 0.08 seconds, Fetched: 4 row(s)
Array使用
1 create table qa_test.class_test(name string, student_id_list array<INT>) 2 ROW FORMAT DELIMITED 3 FIELDS TERMINATED BY ',' 4 COLLECTION ITEMS TERMINATED BY ':'; 5 6 hive>desc qa_test.class_test; 7 OK 8 name string 9 student_id_list array<int> 10 Time taken: 0.052 seconds, Fetched: 2 row(s) 11 12 $ cat test6.txt 13 034,1:2:3:4 14 035,5:6 15 036,7:8:9:10 16 17 LOAD DATA LOCAL INPATH '/home/hadoop/test/test6' INTO TABLE qa_test.class_test; 18 19 hive> select * from qa_test.class_test; 20 OK 21 034 [1,2,3,4] 22 035 [5,6] 23 036 [7,8,9,10] 24 Time taken: 0.076 seconds, Fetched: 3 row(s) 25 26 select student_id_list[3] from qa_test.class_test; 27 28 hive> select student_id_list[3] from qa_test.class_test; 29 OK 30 4 31 NULL 32 10 33 Time taken: 0.12 seconds, Fetched: 3 row(s) 34 35 hive> select size(student_id_list) from qa_test.class_test; 36 OK 37 4 38 2 39 4 40 Time taken: 0.086 seconds, Fetched: 3 row(s) 41 42 43 hive> select array_contains(student_id_list,4) from qa_test.class_test; 44 OK 45 true 46 false 47 false 48 Time taken: 0.129 seconds, Fetched: 3 row(s) 49 50 hive> 51 > select sort_array(student_id_list) from qa_test.class_test; 52 OK 53 [1,2,3,4] 54 [5,6] 55 [7,8,9,10] 56 Time taken: 0.085 seconds, Fetched: 3 row(s)
Map使用
1 create table qa_test.employee(id string, perf map<string, int>) 2 ROW FORMAT DELIMITED 3 FIELDS TERMINATED BY '\t' 4 COLLECTION ITEMS TERMINATED BY ',' 5 MAP KEYS TERMINATED BY ':'; 6 7 8 $ cat test7.txt 9 1 job:80,team:60,person:70 10 2 job:60,team:80 11 3 job:90,team:70,person:100 12 13 LOAD DATA LOCAL INPATH '/home/hadoop/test/test7' INTO TABLE qa_test.employee; 14 15 hive> select * from qa_test.employee; 16 OK 17 1 {"job":80,"team":60,"person":70} 18 2 {"job":60,"team":80} 19 3 {"job":90,"team":70,"person":100} 20 Time taken: 0.075 seconds, Fetched: 3 row(s) 21 22 hive> select perf['job'] from qa_test.employee where perf['job'] is not null; 23 OK 24 80 25 60 26 90 27 Time taken: 0.096 seconds, Fetched: 3 row(s) 28 29 hive> select size(perf) from qa_test.employee; 30 OK 31 3 32 2 33 3 34 Time taken: 0.091 seconds, Fetched: 3 row(s) 35 36 hive> select map_keys(perf) from qa_test.employee; 37 OK 38 ["job","team","person"] 39 ["job","team"] 40 ["job","team","person"] 41 Time taken: 0.136 seconds, Fetched: 3 row(s) 42 43 hive> select map_values(perf) from qa_test.employee; 44 OK 45 [80,60,70] 46 [60,80] 47 [90,70,100] 48 Time taken: 0.077 seconds, Fetched: 3 row(s)
求map的长度 size(Map<K.V>)
1 返回值:int 2 hive> select size(perf) from qa_test.employee; 3 OK 4 3 5 2 6 3 7 Time taken: 0.091 seconds, Fetched: 3 row(s)
求数组的长度 size(Array<T>)
1 返回值:int 2 hive> select size(student_id_list) from qa_test.class_test; 3 OK 4 4 5 2 6 4 7 Time taken: 0.086 seconds, Fetched: 3 row(s)
返回map中的所有key
map_keys(Map<K.V>)
1 返回值:array<K> 2 hive> select map_keys(perf) from qa_test.employee; 3 OK 4 ["job","team","person"] 5 ["job","team"] 6 ["job","team","person"] 7 Time taken: 0.136 seconds, Fetched: 3 row(s)
返回map中的所有value map_values(Map<K.V>)
1 返回值:array<V> 2 hive> select map_values(perf) from qa_test.employee; 3 OK 4 [80,60,70] 5 [60,80] 6 [90,70,100] 7 Time taken: 0.077 seconds, Fetched: 3 row(s)
如该数组Array<T>包含value返回true。,否则返回false array_contains(Array<T>, value)
1 返回值:boolean 2 hive> select array_contains(student_id_list,4) from qa_test.class_test; 3 OK 4 true 5 false 6 false 7 Time taken: 0.129 seconds, Fetched: 3 row(s)
按自然顺序对数组进行排序并返回 sort_array(Array<T>)
1 返回值:array 2 hive> select sort_array(student_id_list) from qa_test.class_test; 3 OK 4 [1,2,3,4] 5 [5,6] 6 [7,8,9,10] 7 Time taken: 0.085 seconds, Fetched: 3 row(s)
二.聚合函数
统计总行数,包括含有NULL值的行 count(*)
统计提供非NULL的expr表达式值的行数 count(expr)
统计提供非NULL且去重后的expr表达式值的行数 count(DISTINCT expr[, expr])
1 返回值:BIGINT
sum(col),表示求指定列的和,sum(DISTINCT col)表示求去重后的列的和
1 返回值:DOUBLE
avg(col),表示求指定列的平均值,avg(DISTINCT col)表示求去重后的列的平均值
1 返回值:DOUBLE
求指定列的最小值 min(col)
1 返回值:DOUBLE
求指定列的最大值 max(col)
1 返回值:DOUBLE
求指定列数值的方差 variance(col), var_pop(col)
1 返回值:DOUBLE
求指定列数值的样本方差
var_samp(col)
1 返回值:DOUBLE
求指定列数值的标准偏差
stddev_pop(col)
1 返回值:DOUBLE
求指定列数值的样本标准偏差
stddev_samp(col)
1 返回值:DOUBLE
求指定列数值的协方差 covar_pop(col1, col2)
1 返回值:DOUBLE
求指定列数值的样本协方差 covar_samp(col1, col2)
1 返回值:DOUBLE
返回两列数值的相关系数 corr(col1, col2)
1 返回值:DOUBLE
返回col的p%分位数 percentile(BIGINT col, p)
1 返回值:DOUBLE
三.特殊函数
窗口函数
分析函数
混合函数
UDTF
多行转换:lateral view
说明:lateral view用于和json_tuple,parse_url_tuple,split, explode等UDTF一起使用,它能够将一行数据拆成多行数据,在此基础上可以对拆分后的数据进行聚合。
举例:
1 说明:lateral view用于和json_tuple,parse_url_tuple,split, explode等UDTF一起使用,它能够将一行数据拆成多行数据,在此基础上可以对拆分后的数据进行聚合。 2 举例: 3 4 hive> select s.x,sp from test.dual s lateral view explode(split(concat_ws(',','1','2','3','4','5','6','7','8','9'),',')) t as sp; 5 x sp 6 a 1 7 b 2 8 a 3 9 解释一下,from后面是你的表名,在表名后面加lateral view explode。。。(你的行转列sql) ,还必须要起一个别名,我这个字段的别名为sp。然后再看看select后面的 s.*,就是原表的字段,我这里面只有一个字段,且为X 10 11 多个lateral view的sql类如: 12 13 SELECT * FROM exampleTable LATERAL VIEW explode(col1) myTable1 AS myCol1 LATERAL VIEW explode(myCol1) myTable2 AS myCol2;
抽取一行数据转换到新表的多列样例:
http_referer是获取的带参数请求路径,其中非法字符用\做了转义,根据路径解析出地址,查询条件等存入新表中,
1 drop table if exists t_ods_tmp_referurl; 2 create table t_ ods _tmp_referurl as 3 SELECT a.*,b.* 4 FROM ods_origin_weblog a LATERAL VIEW parse_url_tuple(regexp_replace(http_referer, "\"", ""), 'HOST', 'PATH','QUERY', 'QUERY:id') b as host, path, query, query_id; 5 6 复制表,并将时间截取到日: 7 drop table if exists t_ods_tmp_detail; 8 create table t_ods_tmp_detail as 9 select b.*,substring(time_local,0,10) as daystr, 10 substring(time_local,11) as tmstr, 11 substring(time_local,5,2) as month, 12 substring(time_local,8,2) as day, 13 substring(time_local,11,2) as hour 14 From t_ ods _tmp_referurl b;
表生成函数
对于a中的每个元素,将生成一行且包含该元素
explode(array<TYPE> a)
1 返回值:Array Type
每行对应数组中的一个元素 explode(ARRAY)
1 返回值:N rows
每行对应每个map键-值,其中一个字段是map的键,另一个字段是map的值
explode(MAP)
1 返回值:N rows
explode类似,不同的是还返回各元素在数组中的位置
posexplode(ARRAY)
1 返回值:N rows
把M列转换成N行,每行有M/N个字段,其中n必须是个常数
stack(INT n, v_1, v_2, ..., v_k)
1 返回值:N rows
从一个JSON字符串中获取多个键并作为一个元组返回,与get_json_object不同的是此函数能一次获取多个键值
json_tuple(jsonStr, k1, k2, ...)
1 返回值:tuple
返回从URL中抽取指定N部分的内容,参数url是URL字符串,而参数p1,p2,....是要抽取的部分,这个参数包含HOST, PATH, QUERY, REF, PROTOCOL, AUTHORITY, FILE, USERINFO, QUERY:<KEY>
1 返回值;tuple
将结构体数组提取出来并插入到表中 inline(ARRAY<STRUCT[,STRUCT]>)
下表为Hive内置的聚合函数。
返回类型 | 函数名 | 描述 |
BIGINT | count(*) count(expr) count(DISTINCT expr[, expr_.]) | count(*) – 返回检索到的行的总数,包括含有NULL值的行。count(expr) – 返回expr表达式不是NULL的行的数量count(DISTINCT expr[, expr]) – 返回expr是唯一的且非NULL的行的数量 |
DOUBLE | sum(col) sum(DISTINCT col) | 对组内某列求和(包含重复值)或者对组内某列求和(不包含重复值) |
DOUBLE | avg(col), avg(DISTINCT col) | 对组内某列元素求平均值者(包含重复值或不包含重复值) |
DOUBLE | min(col) | 返回组内某列的最小值 |
DOUBLE | max(col) | 返回组内某列的最大值 |
DOUBLE | variance(col), var_pop(col) | 返回组内某个数字列的方差 |
DOUBLE | var_samp(col) | 返回组内某个数字列的无偏样本方差 |
DOUBLE | stddev_pop(col) | 返回组内某个数字列的标准差 |
DOUBLE | stddev_samp(col) | 返回组内某个数字列的无偏样本标准差 |
DOUBLE | covar_pop(col1, col2) | 返回组内两个数字列的总体协方差 |
DOUBLE | covar_samp(col1, col2) | 返回组内两个数字列的样本协方差 |
DOUBLE | corr(col1, col2) | 返回组内两个数字列的皮尔逊相关系数 |
DOUBLE | percentile(BIGINT col, p) | 返回组内某个列精确的第p位百分数,p必须在0和1之间 |
array<double> | percentile(BIGINT col, array(p1 [, p2]...)) | 返回组内某个列精确的第p1,p2,……位百分数,p必须在0和1之间 |
DOUBLE | percentile_approx(DOUBLE col, p [, B]) | 返回组内数字列近似的第p位百分数(包括浮点数),参数B控制近似的精确度,B值越大,近似度越高,默认值为10000。当列中非重复值的数量小于B时,返回精确的百分数 |
array<double> | percentile_approx(DOUBLE col, array(p1 [, p2]...) [, B]) | 同上,但接受并返回百分数数组 |
array<struct {'x','y'}> | histogram_numeric(col, b) | 使用b个非均匀间隔的箱子计算组内数字列的柱状图(直方图),输出的数组大小为b,double类型的(x,y)表示直方图的中心和高度 |
array | collect_set(col) | 返回消除了重复元素的数组 |
array | collect_list(col) | 返回允许重复元素的数组 |
INTEGER | ntile(INTEGER x) | 该函数将已经排序的分区分到x个桶中,并为每行分配一个桶号。这可以容易的计算三分位,四分位,十分位,百分位和其它通用的概要统计 |
内置 Table-Generating函数(UDTF)
正常的用户定义函数,如concat,输入一个单行然后输出一个单行,但table-generating函数将一个单输入行转换为多个输出行。下表为Hive内置的table-generating函数。
返回类型 | 函数名 | 描述 |
N rows | explode(ARRAY) | 参数列为数组类型,将数组数据中的每个元素做为一行返回 |
N rows | explode(MAP) | 将输入map中的每个键值对转换为两列,一列为key,另一列为value,然后返回新行 |
| inline(ARRAY<STRUCT[,STRUCT]>) | 分解struct数组到表中 |
Array Type | explode(array<TYPE> a) | 对于数组a中的每个元素,该函数产生包含该元素的行For |
元组 | json_tuple(jsonStr, k1, k2, ...) | 参数为一组键k1,k2……和JSON字符串,返回值的元组。该方法比 |
元组 | parse_url_tuple(url, p1, p2, ...) | 该方法同 |
N rows | posexplode(ARRAY) | 行为与参数为数组的explode方法相似,但包含项在原始数组中的位置,返回(pos,value)的二元组 |
| stack(INT n, v_1, v_2, ..., v_k) | 将v_1, ..., v_k 分为n行,每行包含n/k列,n必须为常数 |
使用语法”SELECT udtf(col) AS colAlias...”有以下几点限制:
- 在SELECT中不允许再有其他表达式:不支持SELECT pageid, explode(adid_list) AS myCol...
- UDTF不能够嵌套使用:不支持SELECT explode(explode(adid_list)) AS myCol...
- 不支持GROUP BY /CLUSTER BY / DISTRIBUTE BY / SORT BY:不支持SELECT explode(adid_list) AS myCol ... GROUP BY myCol