hive的内部函数
获取0-1的随机数:
select rand();
select rand(); //固定值
切割split
select split(rand()*100,’\\.’)[0] //获取0-100随机数的整数
四舍五入
select round(rand()*100,x); //x是保留几位小数,默认是取(整数.0)
截取
select substring(rand()*100,0,2);
select substr(rand()*100,0,2); //同上
正则替代
select regexp_replace(“a.jpg”,“jpg”,“png”);
类型转换
select cast(1 as double);
case when
select
case
when 1=1 then"男"
when 1=2 then"女"
else "aaa"
end;
--------写法二--------
SELECT
(CASE 3
WHEN 1 THEN"男"
when 2 then"女"
else "aaa"
end);
select if(1=1,"","")
select if(1=1,"",if(,))
字符串拼接
select(1+2+3) // 6
select (“1”+“2”+“3”); //6.0
select concat(“1”,“2”,“3”) //123
select concat_ws("|",“1”,“2”,“3”) //1|2|3
select length(“asdasdas”);
select size(array(1,2,3));
排名函数
rank() //有并列名次,并且名次空位置
dense_rank() //有并列名次,并列名次后不空位
row_number() //没有相同名次,名次不空位
自定义函数
常见的自定义函数:
udf:用户自定义函数,一个输入一个输出。常用。
udaf:用户自定义聚合函数。多个输入,一个输出
udtf:用户表生成函数。一个输入,多个输出。
udf的使用
1.需要继承UDF,重写evaluate()方法,该方法可以重载
2.(老版)继承GenricUDF,重写evaluate、getDisplayString()、initlize()
udf使用案例
1.拼接字符串 MyConcatUdf
public class MyConcatUdf extends UDF{
public static void main(String[] args) {
System.out.println(new MyConcatUdf().evaluate ("online"));
}
public String evaluate(String word) {
if(word == null) {
return "null";
}
return word+"_class";
}
}
2.根据key获取value KeyToValue
sex=1&weight=123&sla=33333
sla 33333
sex 1
aaa null
public class KeyToValue extends UDF{
public String evaluate(String a,String key) throws JSONException {
}
public static void main(String[] args) throws JSONException {
}
}
udf的几种部署方法
一、当前session有效(退出重新进入hive失效)
1.将udf的jar包上传到服务器
2.将jar包添加到hive中
hive> add jar /xx/xx.jar
3.创建临时函数
hive>create temporary function myconcat as 'hive.MyConcatUdf'
4.测试临时函数是否可用
show functions;
desc function myconcat;
select myconcat("online"); //输出online_class
5.确定无用可以销毁函数
drop function if exists myconcat;
第二种方式
1.将udf的jar包上传到服务器
//放在此目录的jar包会自动启动
//hive-site.xml的hive.aux.jars.path
//1.目前只支持file://也就是本地文件,暂不支持HDFS,也不支持文件夹。
//2.多个文件使用逗号分隔。
//3.不能换行。
<property>
<name>hive.aux.jars.path</name>
<value>$HIVE_HOME/auxlib/</value>
</property>
2.在hive的安装目录下的bin下创建一个文件:.hiverc
cd到hive目录
vi ./bin/.hiverc
add jar /xxx/xxx/xx.jar
create temporary function ktv as 'hive.KeyToValue';
//重启
3.测试
select ktv("sex=1&weight=123&sla=33333","sal");