Hive函数学习

Hive函数学习

--- 查看所有函数或操作符
show functions;

--- 查看函数描述
describe function trim;
describe function extended trim;

​ Hive中提供了非常丰富的运算符和内置函数支撑,具体操作如下:

1.内置运算符

1.1关系运算符

运算符类型说明
A = B所有原始类型如果A与B相等,返回TRUE,否则返回FALSE
A == B失败,因为无效的语法。 SQL使用”=”,不使用”==”。
A <> B所有原始类型如果A不等于B返回TRUE,否则返回FALSE。如果A或B值为”NULL”,结果返回”NULL”。
A < B所有原始类型如果A小于B返回TRUE,否则返回FALSE。如果A或B值为”NULL”,结果返回”NULL”。
A <= B所有原始类型如果A小于等于B返回TRUE,否则返回FALSE。如果A或B值为”NULL”,结果返回”NULL”。
A > B所有原始类型如果A大于B返回TRUE,否则返回FALSE。如果A或B值为”NULL”,结果返回”NULL”。
A >= B所有原始类型如果A大于等于B返回TRUE,否则返回FALSE。如果A或B值为”NULL”,结果返回”NULL”。
A IS NULL所有类型如果A值为”NULL”,返回TRUE,否则返回FALSE
A IS NOT NULL所有类型如果A值不为”NULL”,返回TRUE,否则返回FALSE
A LIKE B字符串如 果A或B值为”NULL”,结果返回”NULL”。字符串A与B通过sql进行匹配,如果相符返回TRUE,不符返回FALSE。B字符串中 的”_”代表任一字符,”%”则代表多个任意字符。例如: (‘foobar’ like ‘foo’)返回FALSE,( ‘foobar’ like ‘foo_ _ _’或者 ‘foobar’ like ‘foo%’)则返回TURE
A RLIKE B字符串如 果A或B值为”NULL”,结果返回”NULL”。字符串A与B通过java进行匹配,如果相符返回TRUE,不符返回FALSE。例如:( ‘foobar’ rlike ‘foo’)返回FALSE,(’foobar’ rlike ‘^f.*r$’ )返回TRUE。
A REGEXP B字符串与RLIKE相同。
select ("foobar" like "foo%"); -- true
select ("foobar" like "foo___"); -- true

select ("foobar" rlike "foo.*"); -- true

select ("foobar" regexp "foo.*");  -- true

1.2算术运算符

运算符类型说明
A + B所有数字类型A和B相加。结果的与操作数值有共同类型。例如每一个整数是一个浮点数,浮点数包含整数。所以,一个浮点数和一个整数相加结果也是一个浮点数。
A – B所有数字类型A和B相减。结果的与操作数值有共同类型。
A * B所有数字类型A和B相乘,结果的与操作数值有共同类型。需要说明的是,如果乘法造成溢出,将选择更高的类型。
A / B所有数字类型A和B相除,结果是一个double(双精度)类型的结果。
A % B所有数字类型A除以B余数与操作数值有共同类型。
A & B所有数字类型运算符查看两个参数的二进制表示法的值,并执行按位”与”操作。两个表达式的一位均为1时,则结果的该位为 1。否则,结果的该位为 0。
A|B所有数字类型运算符查看两个参数的二进制表示法的值,并执行按位”或”操作。只要任一表达式的一位为 1,则结果的该位为 1。否则,结果的该位为 0。
A ^ B所有数字类型运算符查看两个参数的二进制表示法的值,并执行按位”异或”操作。当且仅当只有一个表达式的某位上为 1 时,结果的该位才为 1。否则结果的该位为 0。
~A所有数字类型对一个表达式执行按位”非”(取反)。
select 1+3 num;

select 1%3 div1;

select 1^4 ;

select ~4; -- 5

1.3逻辑运算符

运算符类型说明
A AND B布尔值A和B同时正确时,返回TRUE,否则FALSE。如果A或B值为NULL,返回NULL。
A && B布尔值与”A AND B”相同
A OR B布尔值A或B正确,或两者同时正确返返回TRUE,否则FALSE。如果A和B值同时为NULL,返回NULL。
A | B布尔值与”A OR B”相同
NOT A布尔值如果A为NULL或错误的时候返回TURE,否则返回FALSE。
! A布尔值与”NOT A”相同

1.4复杂类型函数

函数类型说明
map(key1, value1, key2, value2, …)通过指定的键/值对,创建一个map。
select map(“hello”,“world”,“foo”,“bar”) as my_map;
struct(val1, val2, val3, …)通过指定的字段值,创建一个结构。结构字段名称包含COL1,COL2,…
array(val1, val2, …)通过指定的元素,创建一个数组。
select array(“lol”,“sleep”);
select array("lol","sleep");

select map("hello","world");

1.5对复杂类型函数操作

函数类型说明
A[n]A是一个数组,n为int型返回数组A的第n个元素,第一个元素的索引为0。如果A数组为[‘foo’,‘bar’],则A[0]返回’foo’和A[1]返回”bar”。
M[key]M是Map<K, V>,关键K型返回关键值对应的值,例如mapM为 {‘f’ -> ‘foo’, ‘b’ -> ‘bar’, ‘all’ -> ‘foobar’},则M[‘all’] 返回’foobar’。
S.xS为struct返回结构x字符串在结构S中的存储位置。如 foobar {int foo, int bar} foobar.foo的领域中存储的整数。
select array("lol","sleep")[0];

select map("hello","world")["hello"];

2.内置函数

2.1数学函数

返回类型函数说明
BIGINTround(double a)四舍五入
DOUBLEround(double a, int d)小数部分d位之后数字四舍五入,例如round(21.263,2),返回21.26
BIGINTfloor(double a)对给定数据进行向下舍入最接近的整数。例如floor(21.2),返回21。
BIGINTceil(double a), ceiling(double a)将参数向上舍入为最接近的整数。例如ceil(21.2),返回23.
doublerand(), rand(int seed)返回大于或等于0且小于1的平均分布随机数(依重新计算而变)
doubleexp(double a)返回e的n次方
doubleln(double a)返回给定数值的自然对数
doublelog10(double a)返回给定数值的以10为底自然对数
doublelog2(double a)返回给定数值的以2为底自然对数
doublelog(double base, double a)返回给定底数及指数返回自然对数
doublepow(double a, double p) power(double a, double p)返回某数的乘幂
doublesqrt(double a)返回数值的平方根
stringbin(BIGINT a)返回二进制格式
stringhex(BIGINT a) hex(string a) hex(n, bin, or str)将整数或字符转换为十六进制格式
stringunhex(string a)十六进制字符转换由数字表示的字符。
stringconv(BIGINT num, int from_base, int to_base)将 指定数值,由原来的度量体系转换为指定的试题体系。例如CONV(‘a’,16,2),返回。参考:’1010′ http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_conv
doubleabs(double a)取绝对值
int doublepmod(int a, int b) pmod(double a, double b)返回a除b的余数的绝对值 select pmod(32,3); – 3
doublesin(double a)返回给定角度的正弦值
doubleasin(double a)返回x的反正弦,即是X。如果X是在-1到1的正弦值,返回NULL。
doublecos(double a)返回余弦
doubleacos(double a)返回X的反余弦,即余弦是X,,如果-1<= A <= 1,否则返回null.
int doublepositive(int a) positive(double a)返回A的值,例如positive(2),返回2。
int doublenegative(int a) negative(double a)返回A的相反数,例如negative(2),返回-2。
select int(round(rand() *23));

---随机数
select rand() * 23 ;
---种子
select rand(2);

--- 字符串拼接
select concat("a","B");

--- 子字符串
select substr("hello,world",3);
select substr("hello,world",3,3);

--- 大写
select upper("hello,world");
select ucase("hello,world");
select lower("HELlo,world");
select lcase("HELlo,world");

select trim(" HELlo,world  ");
select ltrim(" HELlo,world  ");
select rtrim(" HELlo,world  ");

--- 替换字符
select regexp_replace('13212345678foobar', '[0-9]{11}','');
select regexp_replace('A+W', 'A|W','U');

--- 占用空间
select size(array('a','b',1,2,34));
select size(map('a','b',1,2));

对数
select log10(100);

-- 类型转换
select cast("111" as bigint);

转二进制
select bin(8);

求余数
select mod(3,2);


2.2收集函数

返回类型函数说明
intsize(Map<K.V>)返回的map类型的元素的数量
intsize(Array)返回数组类型的元素数量
array Kmap_keys(Map<K.V>)返回键的集合
array Vmap_values(Map<K.V>)返回值的集合
booleanarray_contains(Array, value)array中是否包含值
array Tsort_array(Array T)排序
select size(map("hello","world"));

select size(array("hello","world"));

select map_keys(map("hello","world","num","22"));

select sort_array(array("hello","world","num","22"));

2.3类型转换函数

返回类型函数说明
指定 “type”cast(expr as type)类型转换。例如将字符”1″转换为整数:cast(’1′ as bigint),如果转换失败返回NULL。
select cast(1 as string);

select cast('12' as float);

2.4日期函数

返回类型函数说明
srtingcurrent_timestamp()当地时区的时间戳
stringfrom_unixtime(bigint unixtime[, string format])UNIX_TIMESTAMP参数表示返回一个值’YYYY- MM – DD HH:MM:SS’或YYYYMMDDHHMMSS.uuuuuu格式,这取决于是否是在一个字符串或数字语境中使用的功能。该值表示在当前的时区。
bigintunix_timestamp()如果不带参数的调用,返回一个Unix时间戳(从’1970- 01 – 0100:00:00′到现在的UTC秒数)为无符号整数。
bigintunix_timestamp(string date)指定日期参数调用UNIX_TIMESTAMP(),它返回参数值’1970- 01 – 0100:00:00′到指定日期的秒数。
bigintunix_timestamp(string date, string pattern)指定时间输入格式,返回到1970年秒数:unix_timestamp(‘2009-03-20’, ‘yyyy-MM-dd’)= 1237532400
stringto_date(string timestamp)返回时间中的年月日: to_date(“1970-01-01 00:00:00”)= “1970-01-01″
stringto_dates(string date)给定一个日期date,返回一个天数(0年以来的天数)
intyear(string date)返回指定时间的年份,范围在1000到9999,或为”零”日期的0。
intquarter(date/timestamp/string)返回季度
intmonth(string date)返回指定时间的月份,范围为1至12月,或0一个月的一部分,如’0000-00-00′或’2008-00-00′的日期。
intday(string date) dayofmonth(date)返回指定时间的日期
inthour(string date)返回指定时间的小时,范围为0到23。
intminute(string date)返回指定时间的分钟,范围为0到59。
intsecond(string date)返回指定时间的秒,范围为0到59。
intweekofyear(string date)返回指定日期所在一年中的星期号,范围为0到53。
intextract(field FROM source)提取时间 select extract(month from “2021-10-20”)
intdatediff(string enddate, string startdate)两个时间参数的日期之差。
intdate_add(string startdate, int days)给定时间,在此基础上加上指定的时间段。
intdate_sub(string startdate, int days)给定时间,在此基础上减去指定的时间段。
timestampfrom_utc_timestamp({any primitive type} ts, string timezone)返回时间戳转换的时间
timestampto_utc_timestamp({any primitive type} ts, string timezone)转时间戳
datecurrent_date当前日期 select current_date;
timestampcurrent_timestamp当前时间戳
stringadd_months(string start_date, int num_months, output_date_format)月份加减
stringlast_day(string date)这个月最后一天 select last_day(current_date);
stringnext_day(string start_date, string day_of_week)下个周的周几是几号
stringtrunc(string date, string format)格式清除formats: YEAR/MONTH/MON/MM , trunc(‘2015-03-17’, ‘MM’)
doublemonths_between(date1, date2)月份间隔 months_between(‘1997-02-28 10:30:00’, ‘1996-10-30’);
stringdate_format(date/timestamp/string ts, string fmt)格式化时间
select from_unixtime(unix_timestamp());

select current_timestamp(); -- 自动时区的时间戳

select unix_timestamp(); -- 1628573788 获取当前时间戳到秒

select unix_timestamp('2021-03-20 00:00:00'); -- 时间转时间戳
select unix_timestamp('2022-03-20', 'yyyy-MM-dd');

select CURRENT_DATE();
select CURRENT_TIMESTAMP();
select to_date("1970-01-01 00:00:00");
select to_date("2021-08-10");

select year('2021-03-23 05:30:23'); --2021
select year('2021-03-23'); --2021


select month('2021-03-23 05:30:23');

select day('2021-03-23 05:30:23'); --23
select dayofmonth('2021-03-23 05:30:23'); --23
select dayofweek('2021-03-23 05:30:23'); -- 3 周几 + 1

select extract(month from "2016-10-20");
select extract(hour from "2016-10-20 05:06:07");
select extract(dayofweek from "2016-10-20 05:06:07");
select extract(month from interval '1-3' year to month);
select extract(minute from interval '3 12:20:30' day to second); -- 20

select datediff('2021-08-10', '2021-08-08'); -- 间隔几天

select date_add(current_timestamp(),1); --明天
select date_sub(current_timestamp(),1); --昨天

--- 时间
select from_unixtime(1629965089849); -- 垃圾
select from_utc_timestamp(1629965089849,'Asia/Shanghai');
select from_utc_timestamp(1629965089849,'UTC');
select from_utc_timestamp(2592000.0,'PST');
select to_utc_timestamp(2592000.0,'UTC');
select to_utc_timestamp(2592000000,'PST');
select to_utc_timestamp(timestamp '1970-01-30 16:00:00','PST');

select add_months('2021-08-31', 1);
select add_months('2021-12-31 14:15:16', 2, 'YYYY-MM-dd HH:mm:ss')
select last_day(current_date);
select next_day(current_date,'MO');
select next_day(current_date,'MON');

select trunc('2015-03-17', 'YEAR');
select to_date("1970-01-01 00:00:00");
select to_date(from_utc_timestamp(1629965089849,'Asia/Shanghai'));
-- year(string date)
-- month(string date)
-- day(string date)

2.5条件函数

返回类型函数说明
Tif(boolean testCondition, T valueTrue, T valueFalseOrNull)判断是否满足条件,如果满足返回一个值,如果不满足则返回另一个值。
Booleanisnull( a )是否为空
booleanisnotnull(a)是否不为空
Tnvl(T value, T default_value)返回默认值 如果value为空
TCOALESCE(T v1, T v2, …)返回一组数据中,第一个不为NULL的值,如果均为NULL,返回NULL。
TCASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END当a=b时,返回c;当a=d时,返回e,否则返回f。
TCASE WHEN a THEN b [WHEN c THEN d]* [ELSE e] END当值为a时返回b,当值为c时返回d。否则返回e。
Tnullif( a, b )Returns NULL if a=b; otherwise returns a . 等价 case when a=b then null else a
voidassert_true(boolean condition)断言,会抛异常

select if(1>0,true,false); -- true

select coalesce(null,22); -- 22


2.6字符函数

返回类型函数说明
intlength(string A)返回字符串的长度
stringreverse(string A)返回倒序字符串
stringconcat(string A, string B…)连接多个字符串,合并为一个字符串,可以接受任意数量的输入字符串
stringconcat_ws(string SEP, string A, string B…)链接多个字符串,字符串之间以指定的分隔符分开。
stringsubstr(string A, int start) substring(string A, int start)从文本字符串中指定的起始位置后的字符。
stringsubstr(string A, int start, int len) substring(string A, int start, int len)从文本字符串中指定的位置指定长度的字符。
stringupper(string A) ucase(string A)将文本字符串转换成字母全部大写形式
stringlower(string A) lcase(string A)将文本字符串转换成字母全部小写形式
stringtrim(string A)删除字符串两端的空格,字符之间的空格保留
stringltrim(string A)删除字符串左边的空格,其他的空格保留
stringrtrim(string A)删除字符串右边的空格,其他的空格保留
stringregexp_replace(string A, string B, string C)字符串A中的B字符被C字符替代
stringregexp_extract(string subject, string pattern, int index)通过下标返回正则表达式指定的部分。regexp_extract(‘foothebar’, ‘foo(.*?)(bar)’, 2) returns ‘bar.’
stringparse_url(string urlString, string partToExtract [, string keyToExtract])返回URL指定的部分。parse_url(‘http://facebook.com/path1/p.php?k1=v1&k2=v2#Ref1′, ‘HOST’) 返回:’facebook.com’
stringget_json_object(string json_string, string path)select a.timestamp, get_json_object(a.appevents, ‘ . e v e n t i d ’ ) , g e t j s o n o b j e c t ( a . a p p e n v e t s , ‘ .eventid’), get_json_object(a.appenvets, ‘ .eventid),getjsonobject(a.appenvets,.eventname’) from log a;
stringspace(int n)返回指定数量的空格
stringrepeat(string str, int n)重复N次字符串
intascii(string str)返回字符串中首字符的数字值
stringlpad(string str, int len, string pad)返回指定长度的字符串,给定字符串长度小于指定长度时,由指定字符从左侧填补。
stringrpad(string str, int len, string pad)返回指定长度的字符串,给定字符串长度小于指定长度时,由指定字符从右侧填补。
arraysplit(string str, string pat)将字符串转换为数组。
intfind_in_set(string str, string strList)返回字符串str第一次在strlist出现的位置。如果任一参数为NULL,返回NULL;如果第一个参数包含逗号,返回0。
array<array>sentences(string str, string lang, string locale)将字符串中内容按语句分组,每个单词间以逗号分隔,最后返回数组。 例如sentences(‘Hello there! How are you?’) 返回:( (“Hello”, “there”), (“How”, “are”, “you”) )
array<struct<string,double>>ngrams(array<array>, int N, int K, int pf)SELECT ngrams(sentences(lower(tweet)), 2, 100 [, 1000]) FROM twitter;
array<struct<string,double>>context_ngrams(array<array>, array, int K, int pf)SELECT context_ngrams(sentences(lower(tweet)), array(null,null), 100, [, 1000]) FROM twitter;

3. 脱敏函数

返回类型函数说明
stringmask(string str[, string upper[, string lower[, string number]]])大写,小写,数字替换 mask(“abcd-EFGH-8765-4321”, “U”, “l”, “#”) results in llll-UUUU-####-####
stringmask_first_n(string str[, int n])前几个字符替换
stringmask_last_n(string str[, int n])后几个字符替换 mask_last_n(“1234-5678-8765-4321”, 4)
stringmask_show_first_n(string str[, int n])显示前几个字符,其余mask
stringmask_show_last_n(string str[, int n])显示最后几个字符,其余mask mask_show_last_n(“1234-5678-8765-4321”, 4) results in nnnn-nnnn-nnnn-4321.
stringmask_hash(stringchar

4. 杂项函数

返回类型函数说明
Tjava_method(class, method[, arg1[, arg2…]])反射
Treflect(class, method[, arg1[, arg2…]])反射
hashhash(a1[, a2…])返回hash值 select hash(“hello,world”);
stringcurrent_user()当前用户
stringcurrent_database()
stringmd5(string/binary)
stringsha1(string/binary) sha(string/binary)
stringsha2(string/binary, int)SHA-224, SHA-256, SHA-384, and SHA-512 sha2(‘ABC’, 256)
bigintcrc32(string/binary)
binaryaes_encrypt(input string/binary, key string/binary)base64(aes_encrypt(‘ABC’, ‘1234567890123456’)) = ‘y6Ss+zCYObpCbgfWfyNWTw==’.
strjngaes_decrypt(input binary, key string/binary)aes_decrypt(unbase64(‘y6Ss+zCYObpCbgfWfyNWTw==’), ‘1234567890123456’) = ‘ABC’.
stringget_json_object(json,"$.name.likes[0]")$根对象,.子对象 *通配符 []数组操作
select get_json_object('{"name": "chauncy","likes":[{"weight":8,"type":"apple"},{"weight":9,"type":"pear"}],"bicycle":{"price":19.95,"color":"red"}}',"$.likes[0]");

select get_json_object('{"name": "chauncy","likes":[{"weight":8,"type":"apple"},{"weight":9,"type":"pear"}],"bicycle":{"price":19.95,"color":"red"}}',"$.name");

5.内置的聚合函数(UDAF)

返回类型函数说明
bigintcount(*) , count(expr), count(DISTINCT expr[, expr_., expr_.])返回记录条数。
doublesum(col), sum(DISTINCT col)求和
doubleavg(col), avg(DISTINCT col)求平均值
doublemin(col)返回指定列中最小值
doublemax(col)返回指定列中最大值
doublevar_pop(col)返回指定列的方差
doublevar_samp(col)返回指定列的样本方差
doublestddev_pop(col)返回指定列的偏差
doublestddev_samp(col)返回指定列的样本偏差
doublecovar_pop(col1, col2)两列数值协方差
doublecovar_samp(col1, col2)两列数值样本协方差
doublecorr(col1, col2)返回两列数值的相关系数
doublepercentile(col, p)返回数值区域的百分比数值点。0<=P<=1,否则返回NULL,不支持浮点型数值。
array doublepercentile(col, array(p~1,\ [, p,2,]…))返回数值区域的一组百分比值分别对应的数值点。0<=P<=1,否则返回NULL,不支持浮点型数值。
doublepercentile_approx(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.
arraypercentile_approx(col, array(p~1, [, p,2_]…) [, B])Same as above, but accepts and returns an array of percentile values instead of a single one.
array<struct{‘x’,'y’}>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
arraycollect_set(col)返回无重复记录
intregr_avgx(independent, dependent)计算自变量的平均值
intregr_avgy(independent, dependent)计算因变量的平均值
intregr_count(independent, dependent)返回independent和dependent都非空的个数
Tregr_intercept(independent, dependent)返回线性回归的截距项
Tregr_r2(independent, dependent)返回线性回归的判决系数
regr_sloperegr_slope(independent, dependent)返回线性回归的斜率系数
regr_sxxregr_sxx(independent, dependent)
regr_syyregr_syy(independent, dependent)
histogram_numerichistogram_numeric(col, b)用于画直方图。返回一个长度为b的数组,数组中元素为(x,y)形式的键值对,x代表了直方图中该柱形的中心,y代表可其高度。
collect_setcollect_set(col)返回查询列col去重后的集合,与distinct不同,distinct查询结果为一列数据,collect_set查询后结果为一个集合形式的元素
collect_listcollect_list(col)返回查询列col的列表
ntilentile(INTEGER x)将有序分区划分为x个称为存储桶的组,并为该分区中的每一行分配存储桶编号

6.内置表生成函数(UDTF) 一进多出

返回类型函数说明
数组explode(array TYPE a)数组一条记录中有多个参数,将参数拆分,每个参数生成一列。
Tkey,Tvalueexplode(MAP<Tkey,Tvalue> m)map 映射为列
int,Tposexplode(ARRAY a)增加一列序号列
T1,…,Tninline(ARRAY<STRUCTf1:T1,...,fn:Tn> a)explodes and array and struct into a table
T1,…,Tn/rstack(int n,T1 V1,…,Tk Vk)将k列转成n行
string1,…,stringnjson_tuple(string jsonStr,string k1,…,string kn)比get_json_object高效,因为get_json_object只能获取一个键
string1,…,stringnparse_url_tuple(string urlStr,string p1,…,string pn)url获取json,获取多个键的值

select explode(likes) from psn2;
select explode(map('A',10,'B',20,'C',30));
select json_tuple('{"name": "chauncy","likes":[{"weight":8,"type":"apple"},{"weight":9,"type":"pear"}],"bicycle":{"price":19.95,"color":"red"}}','name','likes');

select explode(array('A','B','C'));
select posexplode(array('A','B','C'));
select tf.* from (select 0) t lateral view explode(array('A','B','C')) tf;
select inline(array(struct('A',10,date '2015-01-01'),struct('B',20,date '2016-02-02'))) as (col1,col2,col3);
select stack(2,'A',10,date '2015-01-01','B',20,date '2016-01-01');
select (date '2021-12-12');

SELECT udtf(col) AS colAlias...  语法的限制:
1. 不能查询其他的字段  如 SELECT pageid, explode(adid_list) AS myCol... 不支持
2. udtf函数不能嵌套 SELECT explode(explode(adid_list)) AS myCol... is not supported
3. GROUP BY / CLUSTER BY / DISTRIBUTE BY / SORT BY

使用 LateralView 语法 替代 https://cwiki.apache.org/confluence/display/Hive/LanguageManual+LateralView
create table pageads( pageid string,adid_list array<int> );
insert into table pageads values('front_page',array(1,2,3)),('contact_page',array(4,5,6));
select pageid,adid from pageads lateral view explode(adid_list) aa  as adid;
-- 防止没有结果 使用 outer关键字
select * from pageads lateral view outer explode(array()) C as a limit 10;

排序 https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
SELECT reducer_udf(my_col, distribute_col, sort_col) FROM
(SELECT my_col, distribute_col, sort_col FROM table_name DISTRIBUTE BY distribute_col SORT BY distribute_col, sort_col) t

7.自定义函数

自定义函数包括三种UDF、UDAF、UDTF

​ UDF(User-Defined-Function) :一进一出

​ UDAF(User- Defined Aggregation Funcation) :聚集函数,多进一出。Count/max/min

​ UDTF(User-Defined Table-Generating Functions) :一进多出,如explode()

7.1 UDF 开发

1、UDF函数可以直接应用于select语句,对查询结构做格式化处理后,再输出内容。

2、编写UDF函数的时候需要注意一下几点:

a)自定义UDF需要继承org.apache.hadoop.hive.ql.UDF。

b)需要实现evaluate函数,evaluate函数支持重载。

<dependency>
        <groupId>org.apache.hive</groupId>
        <artifactId>hive-exec</artifactId>
        <version>2.3.4</version>
</dependency>
package com.chauncy;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

public class TuoMin extends UDF{
    public Text evaluate(final Text s) {
        if (s == null) { return null; }
        String str = s.toString().substring(0,1) +"@chauncy";
        return new Text(str);
    }
}

3、步骤

(1)将jar包上传到虚拟机中:

​ a)把程序打包放到目标机器上去;

​ b)进入hive客户端,添加jar包:hive> add jar /home/god/tuomin-1.0-SNAPSHOT.jar;

​ c)创建临时函数:hive> create function tm as ‘com.chauncy.TuoMin’;

​ d)查询HQL语句:

​ select tm(name) from psn2;

​ e)销毁临时函数:hive> drop function tm;

​ 注意:此种方式创建的函数属于临时函数,当关闭了当前会话之后,函数会无法使用,因为jar的引用没有了,无法找到对应的java文件进行处理,因此不推荐使用。

(2)将jar包上传到hdfs集群中:

​ a)把程序打包上传到hdfs的某个目录下

​ hdfs dfs -mkdir /jar

​ hdfs dfs -put -f tuomin-1.0-SNAPSHOT.jar /jar/

​ b)创建函数:hive>create function tme as ‘com.chauncy.TuoMin’ using jar ‘hdfs://mycluster/jar/tuomin-1.0-SNAPSHOT.jar’;

​ d)查询HQL语句:

​ select tme(name) from psn2;

​ e)销毁函数:hive> DROP FUNCTION tme;

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值