首页技术文章正文

Hive:内置函数和用户定义函数

更新时间:2022-12-30 来源:黑马程序员 浏览量:

Hive的函数分为两大类:内置函数(Built-in Functions)、用户定义函数UDF(User-Defined Functions):

 内置函数可分为:数值类型函数、日期类型函数、字符串类型函数、集合函数、条件函数等;

 用户定义函数根据输入输出的行数可分为3类:UDF、UDAF、UDTF。

1672386890978_81.png

用户定义函数UDF分类标准, 可以根据函数输入输出的行数划分:

UDF(User-Defined-Function)普通函数,一进一出。

UDAF(User-Defined Aggregation Function)聚合函数,多进一出。

UDTF(User-Defined Table-Generating Functions)表生成函数,一进多出。

UDF分类标准本来针对的是用户自己编写开发实现的函数。UDF分类标准可以扩大到Hive的所有函数中:包括内置函数和用户自定义函数。

因为不管是什么类型的函数,一定满足于输入输出的要求,那么从输入几行和输出几行上来划分没有任何问题。千万不要被UD(User-Defined)这两个字母所迷惑,照成视野的狭隘。比如Hive官方文档中,针对聚合函数的标准就是内置的UDAF类型。

1672387136499_83.png

内置函数(build-in)指的是Hive开发实现好,直接可以使用的函数,也叫做内建函数。内置函数根据应用归类整体可以分为8大种类型,我们将列举其中重要的,使用频率高的函数的进行详细讲解。

(1)String Functions 字符串函数

•字符串长度函数:length
•字符串反转函数:reverse
•字符串连接函数:concat
•带分隔符字符串连接函数:concat_ws
•字符串截取函数:substr,substring
------------String Functions 字符串函数------------
select length("itcast");
select reverse("itcast");
select concat("angela","baby");
--带分隔符字符串连接函数:concat_ws(separator, [string | array(string)]+)
select concat_ws('.', 'www', array('itcast', 'cn'));
--字符串截取函数:substr(str, pos[, len]) 或者substring(str, pos[, len])
select substr("angelababy",-2); --pos是从1开始的索引,如果为负数则倒着数select substr("angelababy",2,2);
--分割字符串函数: split(str, regex)
select split('apache hive', ' ');

(2)Date Functions 日期函数

-----------Date Functions 日期函数-----------------
--获取当前日期: current_date
select current_date();
--获取当前UNIX时间戳函数: unix_timestamp
select unix_timestamp();
--日期转UNIX时间戳函数: unix_timestamp
select unix_timestamp("2011-12-07 13:01:03");
--指定格式日期转UNIX时间戳函数: unix_timestamp
select unix_timestamp('20111207 13:01:03','yyyyMMdd HH:mm:ss');
--UNIX时间戳转日期函数: from_unixtime
select from_unixtime(1618238391);
select from_unixtime(0, 'yyyy-MM-dd HH:mm:ss');
--日期比较函数: datediff  日期格式要求'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd'select datediff('2012-12-08','2012-05-09');
--日期增加函数: date_add
select date_add('2012-02-28',10);
--日期减少函数: date_sub
select date_sub('2012-01-1',10);
----Mathematical Functions 数学函数-------------
--取整函数: round  返回double类型的整数值部分(遵循四舍五入)
select round(3.1415926);
--指定精度取整函数: round(double a, int d) 返回指定精度d的double类型select round(3.1415926,4);
--取随机数函数: rand 每次执行都不一样返回一个0到1范围内的随机数select rand();
--指定种子取随机数函数: rand(int seed) 得到一个稳定的随机数序列
select rand(3);

(4)Conditional Functions 条件函数

主要用于条件判断、逻辑判断转换这样的场合

-----Conditional Functions 条件函数------------------
--使用之前课程创建好的student表数据
select * from student limit 3;
--if条件判断: if(boolean testCondition, T valueTrue, T valueFalseOrNull)
select if(1=2,100,200);
select if(sex ='男','M','W') from student limit 3;
--空值转换函数: nvl(T value, T default_value)
select nvl("allen","itcast");
select nvl(null,"itcast");
--条件转换函数: CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END 
select case 100 when 50 then 'tom' when 100 then 'mary' else 'tim' end;
select case sex when '男' then 'male' else 'female' end from student limit 3;


分享到:
在线咨询 我要报名
和我们在线交谈!