Loading

Hive sql函数

date: 2018-11-16 19:03:08
updated: 2018-11-16 19:03:08

Hive sql函数

一、关系运算

  1. 等值比较: =
    select 1 from dual where 1 = 2;

  2. 等值比较:<=>
    a <=> b

  3. 不等值比较: <>和!=
    a != b || a <> b

  4. 小于比较: <
    a < b

  5. 小于等于比较: <=
    a <= b

  6. 大于比较: >
    a > b

  7. 大于等于比较: >=
    a >= b

  8. 区间比较?????

     # step1 设定区间分类个数,此处设置为10
     m=10
     
     # step2 求解字段 result 的最大值和最小值
     section=`hive -e "
     select max(result) as max_num,
        min(result) as min_num
     from  tmp
     "`
     max_num=`echo -e "${section}" | cut -f1`
     min_num=`echo -e "${section}" | cut -f2`
     
     # step3 求解区间的长度
     len_section=`hive -e "
     select (${max_num} - ${min_num}) / ${m}
     from   dual
     "`
     
     # step4 统计每个区间的个数
     hive -e "
     select ${min_num} + floor((result - ${min_num}) / ${len_section}) * ${len_section} as section_flag,
        count(*) as num  
     from   tmp
     "
    
  9. 空值判断: IS NULL
    select 1 from dual where A is null;

  10. 非空判断: IS NOT NULL
    select 1 from dual where A is not null;

  11. LIKE比较: A LIKE B
    B中字符"_"表示任意单个字符,而字符"%"表示任意数量的字符
    否定比较的时候用 NOT A LIKE B

    select 1 from dual where ‘key' like 'foot%';  
    select 1 from dual where ‘key ' like 'foot____';
    
  12. JAVA的LIKE操作: A RLIKE B
    如果字符串A或者字符串B为NULL,则返回NULL;如果字符串A符合JAVA正则表达式B的正则语法,则为TRUE;否则为FALSE

    select 1 from dual where '123456' rlike '^\\d+$'	判断一个字符串是否都是数字
    
  13. REGEXP操作: A REGEXP B
    功能和RLIKE一样

    select 1 from dual where ‘key' REGEXP '^f.*r$';
    

二、数学运算

  1. 加法操作: +

  2. 减法操作: –
    结果的数值类型等于A的类型和B的类型的最小父类型
    比如int ± int 一般结果为int类型,而int ± double 一般结果为double类型

  3. 乘法操作: *
    结果的数值类型等于A的类型和B的类型的最小父类型
    如果A乘以B的结果超过默认结果类型的数值范围,则需要通过cast将结果转换成范围更大的数值类型

  4. 除法操作: /?????
    返回A除以B的结果。结果的数值类型为double

     注意:hive 中最高精度的数据类型是 double, 只精确到小数点后16位,做除法运算时要特别注意  
     hive>select ceil(28.0/6.999999999999999999999) from dual limit 1;  
     结果为4  
     hive>select ceil(28.0/6.99999999999999) from dual limit 1;  
     结果为5
    
  5. 取余操作: %
    返回A除以B的余数。结果的数值类型等于A的类型和B的类型的最小父类型

     注意:精度在 hive 中是个很大的问题,类似这样的操作最好通过 round 指定精度  
     hive> select round(8.4 % 4 , 2) from dual;  
     0.4  
    
  6. 位与操作: &
    返回A和B按位进行与操作的结果。结果的数值类型等于A的类型和B的类型的最小父类型

     hive> select 4 & 8 from dual;  
     0  
     hive> select 6 & 4 from dual;  
     4
    
  7. 位或操作: |
    返回A和B按位进行或操作的结果。结果的数值类型等于A的类型和B的类型的最小父类型

     hive> select 4 | 8 from dual;  
     12  
     hive> select 6 | 8 from dual;  
     14
    
  8. 位异或操作: ^
    返回A和B按位进行异或操作的结果。结果的数值类型等于A的类型和B的类型的最小父类型

     hive> select 4 ^ 8 from dual;  
     12  
     hive> select 6 ^ 4 from dual;  
     2
    
  9. 位取反操作: ~
    返回A按位取反操作的结果。结果的数值类型等于A的类型。

     hive> select ~6 from dual;  
     -7  
     hive> select ~4 from dual;  
     -5  
    

所有正整数的按位取反是其本身+1的负数
所有负整数的按位取反是其本身+1的绝对值
零的按位取反是 -1

三、逻辑运算

  1. 逻辑与操作: AND 、&&

  2. 逻辑或操作: OR 、||

  3. 逻辑非操作: NOT、!
    NOT A:如果A为FALSE,或者A为NULL,则为TRUE;否则为FALSE

     select 1 from dual where  not 1=2 ;
    

四、复合类型构造函数

  1. map结构
    map (key1, value1, key2, value2,…)
    根据输入的key和value对构建map类型

     hive> Create table lxw_test as select map('100','tom','200','mary')as t from lxw_dual;
     hive> describe lxw_test;
     t   map<string,string>
     hive> select t from lxw_test;
     {"100":"tom","200":"mary"}
     
     hive> create table employee(id string, perf map<string, int>)   
     > ROW FORMAT DELIMITED  
     > FIELDS TERMINATED BY '\t'
     > COLLECTION ITEMS TERMINATED BY ','   
     > MAP KEYS TERMINATED BY ':';
     1   job:80,team:60,person:70  
     2   job:60,team:80  
     3   job:90,team:70,person:100
     hive> load data local inpath '/home/oracle/emp.txt' into table employee;
     hive> select perf['person'] from employee;
     OK  
     70  
     NULL  
     100
     hive> select perf['person'] from employee where perf['person'] is not null;
     70  
     100
    

'MAP KEYS TERMINATED BY' :key value分隔符

  1. struct结构
    struct(val1, val2, val3,…)
    根据输入的参数构建结构体struct类型

     hive> create table student_test(id INT, info struct<name:STRING, age:INT>)  
     > ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' 
     > COLLECTION ITEMS TERMINATED BY ':';
     hive>load data local inpath '/home/oracle/student_test.txt' into table student_test;
     1,zhou:30  
     2,yan:30  
     3,chen:20  
     4,li:80
     hive> select info.age from student_test;  
     30  
     30  
     20  
     80
    

'FIELDS TERMINATED BY' :字段与字段之间的分隔符
'COLLECTION ITEMS TERMINATED BY' :一个字段各个item的分隔符

  1. named_struct结构
    named_struct(name1,val1,name2,val2,name3,val3,…)
    使用给定的表达式,构造一个指定列名的 struct 数据结构

     hive> select named_struct('a',1,'b','aaa','c',FALSE) from lxw1234; 
     {"a":1,"b":"aaa","c":false}
    
  2. array结构
    array(val1, val2,…)
    根据输入的参数构建数组array类型

     hive> create table lxw_test as selectarray("tom","mary","tim") as t from lxw_dual;
     hive> describe lxw_test;
     t   array<string>
     hive> select t from lxw_test;
     ["tom","mary","tim"]
     
     hive> create table class_test(name string, student_id_list array<INT>)
     034,1:2:3:4  
     035,5:6  
     036,7:8:9:10
     hive> select student_id_list[3] from class_test;
     4  
     NULL  
     10
    
  3. create_union (tag, val1, val2, …)
    使用给定的 tag 和表达式,构造一个 uniontype 数据结构。tag 表示使用第 tag 个 表达式作为 uniontype 的 value

     hive> select create_union(0,'ss',array(1,2,3)) from lxw1234; 
     {0:"ss"}
     hive> select create_union(1,'ss',array(1,2,3)) from lxw1234; 
     {1:[1,2,3]}
    

五、复合类型操作符

  1. 获取array中的元素 A[n]
    返回数组A中的第n个变量值。数组的起始下标为0。比如,A是个值为['foo', 'bar']的数组类型,那么A[0]将返回'foo',而A[1]将返回'bar'

     hive> create table lxw_test as selectarray("tom","mary","tim") as t from lxw_dual;
     hive> select t[0],t[1],t[2] from lxw_test;
     tom   mary   tim
    
     hive> select array('a','b','c')[1] from lxw1234;  
     b
    
  2. 获取map中的元素 M[key]
    返回map类型M中,key值为指定值的value值。比如,M是值为{'f' -> 'foo', 'b'-> 'bar', 'all' -> 'foobar'}的map类型,那么M['all']将会返回'foobar'

     hive> Create table lxw_test as selectmap('100','tom','200','mary') as t from lxw_dual;
     hive> select t['200'],t['100'] from lxw_test;
     mary   tom
    
     hive> select map('k1','v1')['k1'];  
     v1
    
  3. 获取struct中的元素 S.x
    返回结构体S中的x字段。比如,对于结构体struct foobar {int foo, int bar},foobar.foo返回结构体中的foo字段

     hive> create table lxw_test as select struct('tom','mary','tim')as t from lxw_dual;
     hive> describe lxw_test;
     t   struct<col1:string,col2:string,col3:string>
     hive> select t.col1,t.col3 from lxw_test;
     tom tim
    
     hive> select named_struct('a',1,'b','aaa','c',FALSE).c;  
     false
    

六、数值计算函数

  1. 取整函数: round(double a)
    返回double类型的整数值部分 (遵循四舍五入)

     hive> select round(3.1415926) from dual;  
     3  
     hive> select round(3.5) from dual;  
     4
    
  2. 指定精度取整函数: round(double a, int d)
    返回指定精度d的double类型

     hive> select round(3.1415926,4) from dual;  
     3.1416
    
  3. 向下取整函数: floor(double a)
    返回等于或者小于该double变量的最大的整数

     hive> select floor(3.1415926) from dual;  
     3  
     hive> select floor(25) from dual;  
     25
    
  4. 向上取整函数: ceil(double a)
    返回等于或者大于该double变量的最小的整数

     hive> select ceil(3.1415926) from dual;  
     4  
     hive> select ceil(46) from dual;  
     46
    
  5. 向上取整函数: ceiling(double a)
    与ceil功能相同

     hive> select ceiling(3.1415926) from dual;  
     4  
     hive> select ceiling(46) from dual;  
     46
    
  6. 取随机数函数: rand(),rand(int seed)
    返回一个0到1范围内的随机数。如果指定种子seed,则会等到一个稳定的随机数序列

     hive> select rand() from dual;  
     0.5577432776034763
    
  7. 自然指数函数: exp(double a)
    返回自然对数e的a次方

     hive> select exp(2) from dual;  
     7.38905609893065
    
  8. 以10为底对数函数: log10(double a)
    返回以10为底的a的对数

     hive> select log10(100) from dual;  
     2.0
    
  9. 以2为底对数函数: log2(double a)
    返回以2为底的a的对数

     hive> select log2(8) from dual;  
     3.0
    
  10. 对数函数: log(double base, double a)
    返回以base为底的a的对数

    hive> select log(4,256) from dual;
    4.0
    
  11. 幂运算函数: pow(double a, double p)
    返回a的p次幂

    hive> select pow(2,4) from dual;
    16.0
    
  12. 幂运算函数: power(double a, double p)
    返回a的p次幂,与pow功能相同

    hive> select power(2,4) from dual;
    16.0
    
  13. 开平方函数: sqrt(double a)
    返回a的平方根

    hive> select sqrt(16) from dual;
    4.0
    
  14. 二进制函数: bin(BIGINT a)
    返回a的二进制代码表示

    hive> select bin(7) from dual;
    111
    
  15. 十六进制函数: hex(BIGINT a)
    如果变量是int类型,那么返回a的十六进制表示;如果变量是string类型,则返回该字符串的十六进制表示

    hive> select hex(17) from dual;
    11
    hive> select hex(‘abc’) from dual;
    616263
    
  16. 反转十六进制函数: unhex(string a)
    返回该十六进制字符串所代表的字符串

    hive> select unhex(‘616263’) from dual;
    abc
    hive> select unhex(‘11’) from dual;
    -
    hive> select unhex(616263) from dual;
    abc
    
  17. 进制转换函数: conv(BIGINT num, int from_base, int to_base)
    将数值num从from_base进制转化到to_base进制

    hive> select conv(17,10,16) from dual;
    11
    hive> select conv(17,10,2) from dual;
    10001
    
  18. 绝对值函数: abs(double a) || abs(int a)
    返回数值a的绝对值

    hive> select abs(-3.9) from dual;
    3.9
    hive> select abs(10.9) from dual;
    10.9
    
  19. 正取余函数: pmod(int a, int b) || pmod(double a, double b)
    返回正的a除以b的余数

    hive> select pmod(9,4) from dual;
    1
    hive> select pmod(-9,4) from dual;
    3
    // 如果参数是一正一负,先都看成正数 4 * 3 = 12 > 9,则余数是 12 - 9 = 3
    // 找到比负数大的数,减去负数的绝对值
    
  20. 正弦函数: sin(double a)
    返回a的正弦值

    hive> select sin(0.8) from dual;
    0.7173560908995228
    
  21. 反正弦函数: asin(double a)
    返回a的反正弦值

    hive> select asin(0.7173560908995228) from dual;
    0.8
    
  22. 余弦函数: cos(double a)
    返回a的余弦值

    hive> select cos(0.9) from dual;
    0.6216099682706644
    
  23. 反余弦函数: acos(double a)
    返回a的反余弦值

    hive> select acos(0.6216099682706644) from dual;
    0.9
    
  24. positive函数: positive(int a) || positive(double a)
    返回a

    hive> select positive(-10) from dual;
    -10
    hive> select positive(12) from dual;
    12
    
  25. negative函数: negative(int a) || negative(double a)
    返回-a

    hive> select negative(-5) from dual;
    5
    hive> select negative(8) from dual;
    -8
    

七、集合操作函数

  1. map类型大小:size(Map<K.V>)
    返回map类型的长度

     hive> select size(map('100','tom','101','mary')) from lxw_dual;
     2
    
  2. array类型大小:size(Array)
    返回array类型的长度

     hive> select size(array('100','101','102','103')) from lxw_dual;
     4
    
  3. 判断元素数组是否包含元素:array_contains(Array, value)
    返回 Array中是否包含元素 value

     hive> select array_contains(array(1,2,3,4,5),3) from lxw1234; 
     true
    
  4. 获取map中所有value集合
    map_values(Map)
    返回 Map中所有 value 的集合

     hive> select map_values(map('k1','v1','k2','v2')) from lxw1234; 
     ["v2","v1"]
    
  5. 获取map中所有key集合
    map_keys(Map)
    返回 Map中所有 key 的集合

     hive> select map_keys(map('k1','v1','k2','v2')) from lxw1234; 
     ["k2","k1"]
    
  6. 数组排序
    sort_array(Array)
    对 Array进行升序排序

     hive> select sort_array(array(5,7,3,6,9)) from lxw1234;
     [3,5,6,7,9]
    

八、类型转换函数

  1. 二进制转换:binary(string|binary)
    将输入的值转换成二进制

     hive> select binary('4');
     4
     hive> select binary('1111');
     1111
     hive> select binary('abd');
     abd
    
  2. 基础类型之间强制转换:cast(expr as )
    返回值:Expected "=" to follow "type"
    返回from之后的长度,如果是一张表就输出行数个expr

     hive> select cast(1 as float);
     1.0
     hive> select cast(2 as bigint) from tablss;
     2
     2
     2
     2
     2
     2
    

九、日期函数

  1. UNIX时间戳转日期函数: from_unixtime(bigint unixtime[, string format])
    转化UNIX时间戳(从1970-01-01 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式

     hive> select from_unixtime(1323308943,'yyyyMMdd') from dual;
     20111208
    
  2. 获取当前UNIX时间戳函数: unix_timestamp()
    获得当前时区的UNIX时间戳

     hive> select unix_timestamp() from dual;
     1323309615
    
  3. 日期转UNIX时间戳函数: unix_timestamp(string date)
    转换格式为"yyyy-MM-dd HH:mm:ss"的日期到UNIX时间戳。如果转化失败,则返回0

     hive> select unix_timestamp('2011-12-07 13:01:03') from dual;
     1323234063
    
  4. 指定格式日期转UNIX时间戳函数: unix_timestamp(string date, string pattern)
    转换pattern格式的日期到UNIX时间戳。如果转化失败,则返回0

     hive> select unix_timestamp('20111207 13:01:03','yyyyMMdd HH:mm:ss') from dual;
     1323234063
    
  5. 日期时间转日期函数: to_date(string timestamp)
    返回日期时间字段中的日期部分

     hive> select to_date('2011-12-08 10:03:01') from dual;
     2011-12-08
    
  6. 日期转年函数: year(string date)
    返回日期中的年

     hive> select year('2011-12-08 10:03:01') from dual;
     2011
     hive> select year('2012-12-08') from dual;
     2012
    
  7. 日期转月函数: month (string date)
    返回日期中的月份

     hive> select month('2011-12-08 10:03:01') from dual;
     12
     hive> select month('2011-08-08') from dual;
     8
    
  8. 日期转天函数: day (string date)
    返回日期中的天

     hive> select day('2011-12-08 10:03:01') from dual;
     8
     hive> select day('2011-12-24') from dual;
     24
    
  9. 日期转小时函数: hour (string date)
    返回日期中的小时

     hive> select hour('2011-12-08 10:03:01') from dual;
     10
    
  10. 日期转分钟函数: minute (string date)
    返回日期中的分钟

    hive> select minute('2011-12-08 10:03:01') from dual;
    3
    
  11. 日期转秒函数: second (string date)
    返回日期中的秒

    hive> select second('2011-12-08 10:03:01') from dual;
    1
    
  12. 日期转周函数: weekofyear (string date)
    返回日期在当前的周数

    hive> select weekofyear('2011-12-08 10:03:01') from dual;
    49
    
  13. 日期比较函数: datediff(string enddate, string startdate)
    返回结束日期减去开始日期的天数

    hive> select datediff('2012-12-08','2012-05-09') from dual;
    213
    
  14. 日期增加函数: date_add(string startdate, int days)
    返回开始日期startdate增加days天后的日期

    hive> select date_add('2012-12-08',10) from dual;
    2012-12-18
    
  15. 日期减少函数: date_sub (string startdate, int days)
    返回开始日期startdate减少days天后的日期

    hive> select date_sub('2012-12-08',10) from dual;
    2012-11-28
    

十、条件函数

  1. If函数: if(boolean testCondition, T valueTrue, T valueFalseOrNull)
    当条件testCondition为TRUE时,返回valueTrue;否则返回valueFalseOrNull

     hive> select if(1=2,100,200) from dual;
     200
     hive> select if(1=1,100,200) from dual;
     100
    
  2. 非空查找函数: COALESCE(T v1, T v2, …)
    返回参数中的第一个非空值;如果所有值都为NULL,那么返回NULL

     hive> select COALESCE(null,'100','50′) from dual;
     100
    
  3. 条件判断函数:CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END
    如果 a 等于 b ,那么返回 c ;如果 a 等于 d ,那么返回 e ;否则返回 f

     hive> Select case 100 when 50 then 'tom'   
     when 100 then 'mary'   
     else 'tim' end from dual;  
     mary
    

十一、字符串函数

  1. 字符ascii码函数:ascii(str)
    返回字符串str第一个字符的ascii码

     hive> select ascii(‘abcde’) from dual;  
     97
    
  2. base64字符串:base64(binary bin)
    将二进制bin转换成64位的字符串

     hive> select base64(binary(‘lxw1234’));
     bHh3MTIzNA==
    
  3. 字符串连接函数:concat(string A, string B…)
    返回输入字符串连接后的结果,支持任意个输入字符串

     hive> select concat(‘abc’,'def’,'gh’) from dual;  
     abcdefgh
    
  4. 带分隔符字符串连接函数:concat_ws(string SEP, string A, string B…)
    返回输入字符串连接后的结果,SEP表示各个字符串间的分隔符

     hive> select concat_ws(‘,’,'abc’,'def’,'gh’) from dual;  
     abc,def,gh
     hive> select concat_ws('.','www','iteblog','com') from iteblog;
     www.iteblog.com
    
  5. 数组转换成字符串的函数:concat_ws(string SEP, array)
    返回将数组链接成字符串后的结果,SEP 表示各个字符串间的分隔符

     hive> select concat_ws('|',array('a','b','c'));
     a|b|c
    
  6. 小数位格式化成字符串函数:format_number(number x, int d)
    将数值X转换成"#,###,###.##"格式字符串,并保留d位小数,如果d为0,将进行四舍五入且不保留小数

     hive> select format_number(5.23456,3) from lxw1234;
     5.235
    
  7. 字符串截取函数:substr(string A, int start) || substring(string A, int start)
    返回字符串A从start位置到结尾的字符串

     hive> select substr(‘abcde’,3) from dual;  
     cde  
     hive> select substring(‘abcde’,3) from dual;  
     cde  
     hive>  select substr(‘abcde’,-1) from dual;  (和ORACLE相同)  
     e
    
  8. 字符串截取函数:substr(string A, int start, int len) || substring(string A, int start, int len)
    返回字符串A从start位置开始,长度为len的字符串

     hiveselect substr(‘abcde’,3,2) from dual;  
     cd  
     hiveselect substring(‘abcde’,3,2) from dual;  
     cd  
     hive>select substring(‘abcde’,-2,2) from dual;  
     de
    
  9. 字符串查找函数:instr(string str, string substr)
    返回值为int
    查找字符串str中子字符串substr出现的位置,如果查找失败将返回0,如果任一参数为Null将返回null,注意位置为从1开始的

     hive> select instr('abcdf','df') from lxw1234;
     4
    
  10. 字符串长度函数:length(string A)
    返回字符串A的长度

    hive> select length('abcedfg') from dual;
    7
    
  11. 字符串查找函数:locate(string substr, string str[, int pos])
    查找字符串str中的pos位置后字符串substr第一次出现的位置

    hive> select locate('a','abcda',1) from lxw1234;
    1
    hive> select locate('a','abcda',2) from lxw1234;
    5
    
  12. 字符串格式化函数:printf(String format, Obj... args)
    按照printf风格格式输出字符串

    hive> select printf("%08X",123) from lxw1234; 
    0000007B
    
  13. 字符串转换成map函数:str_to_map(text[, delimiter1, delimiter2])
    返回值:map<string,string>
    将字符串str按照指定分隔符转换成Map,第一个参数是需要转换字符串,第二个参数是键值对之间的分隔符,默认为逗号;第三个参数是键值之间的分隔符,默认为"="

    hive> select str_to_map('k1:v1,k2:v2') from lxw1234;
    {"k2":"v2","k1":"v1"}
    hive> select str_to_map('k1=v1,k2=v2',',','=') from lxw1234;
    {"k2":"v2","k1":"v1"}
    
  14. base64解码函数:unbase64(string str)
    将64位的字符串转换二进制值

    hive> select unbase64('bHh3MTIzNA==') from lxw1234;
    lxw1234
    
  15. 字符串转大写函数:upper(string A) || ucase(string A)
    返回字符串A的大写格式

    hive> select upper(‘abSEd’) from dual;  
    ABSED  
    hive> select ucase(‘abSEd’) from dual;  
    ABSED
    
  16. 字符串转小写函数:lower(string A) || lcase(string A)
    返回字符串A的小写格式

    hive> select lower(‘abSEd’) from dual;  
    absed  
    hive> select lcase(‘abSEd’) from dual;  
    absed
    
  17. 去空格函数:trim(string A)
    去除字符串两边的空格

    hive> select trim(‘ abc ‘) from dual;  
    abc
    
  18. 左边去空格函数:ltrim(string A)
    去除字符串左边的空格

    hive> select ltrim(‘ abc ‘) from dual;  
    abc
    
  19. 右边去空格函数:rtrim(string A)
    去除字符串右边的空格

    hive> select rtrim(‘ abc ‘) from dual;  
    abc
    
  20. 正则表达式替换函数:regexp_replace(string A, string B, string C)
    将字符串A中的符合java正则表达式B的部分替换为C。注意,在有些情况下要使用转义字符,类似oracle中的regexp_replace函数

    hive> select regexp_replace('foobar', 'oo|ar', '') from lxw_dual;
    fb
    
  21. 正则表达式解析函数:regexp_extract(string subject, string pattern, int index)
    将字符串subject按照pattern正则表达式的规则拆分,返回index指定的字符,其中的index是按照正则字符串()的位置。注意,在有些情况下要使用转义字符

    hive> select regexp_extract(‘foothebar’, ‘foo(.*?)(bar)’, 1) from dual;  
    the  
    hive> select regexp_extract(‘foothebar’, ‘foo(.*?)(bar)’, 2) from dual;  
    bar  
    hive> select regexp_extract(‘foothebar’, ‘foo(.*?)(bar)’, 0) from dual;  
    foothebar?????
    
  22. URL解析函数:parse_url(url, partToExtract[, key])?????
    解析URL字符串,partToExtract的选项包含[HOST,PATH,QUERY,REF,PROTOCOL,FILE,AUTHORITY,USERINFO]。

    parse_url('http://facebook.com/path/p1.php?query=1', 'HOST')返回'facebook.com'   
    parse_url('http://facebook.com/path/p1.php?query=1', 'PATH')返回'/path/p1.php'   
    parse_url('http://facebook.com/path/p1.php?query=1', 'QUERY')返回'query=1',  
    可以指定key来返回特定参数,例如  
    parse_url('http://facebook.com/path/p1.php?query=1', 'QUERY','query')返回'1',  
      
    parse_url('http://facebook.com/path/p1.php?query=1#Ref', 'REF')返回'Ref'   
    parse_url('http://facebook.com/path/p1.php?query=1#Ref', 'PROTOCOL')返回'http' 
    
  23. json解析函数:get_json_object(string json_string, string path)
    解析json的字符串json_string,返回path指定的内容。如果输入的json字符串无效,那么返回NULL

    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’) from dual;  
    amy
    
    select get_json_object('{"store":{"fruit":\["aa","bb","cc"]},"owner":"amy"}','$.store.fruit[0]') from test_msg limit 1;
    
  24. 空格字符串函数:space(int n)
    返回长度为n的字符串

    hive> select space(10) from dual;  
    hive> select length(space(10)) from dual;  
    10
    
  25. 重复字符串函数:repeat(string str, int n)
    返回重复n次后的str字符串

    hive> select repeat(‘abc’,5) from dual;  
    abcabcabcabcabc
    
  26. 左补足函数:lpad(string str, int len, string pad)
    将str进行用pad进行左补足到len位

    hive> select lpad(‘abc’,10,’td’) from dual;  
    tdtdtdtabc
    
  27. 右补足函数:rpad(string str, int len, string pad)
    将str进行用pad进行右补足到len位

    hive> select rpad(‘abc’,10,’td’) from dual;  
    abctdtdtdt
    
  28. 分割字符串函数: split(string str, string pat)
    按照pat字符串分割str,会返回分割后的字符串数组

    hive> select split(‘abtcdtef’,'t’) from dual;  
    ["ab","cd","ef"]
    
  29. 集合查找函数: find_in_set(string str, string strList)
    返回str在strlist第一次出现的位置,strlist是用逗号分割的字符串。如果没有找该str字符,则返回0

    hive> select find_in_set(‘ab’,'ef,ab,de’) from dual;  
    2  
    hive> select find_in_set(‘at’,'ef,ab,de’) from dual;  
    0
    
  30. 分词函数:sentences(string str, string lang, string locale)
    返回值: array
    返回输入 str 分词后的单词数组
    分词函数先分句子,句号.会看成是一个单词,逗号,会被拆开,叹号!会被拆成两个句子

    hive> select sentences('hello word!hello hive,hi hive,hello hive')
    [["hello","word"],["hello","hive","hi","hive","hello","hive"]]  
    
    select sentences('hello word,hello hive,hi hive,hello hive');
    [["hello","word","hello","hive","hi","hive","hello","hive"]]  
    
    hive>select sentences('hello word.hello hive,hi hive,hello hive');
    [["hello","word.hello","hive","hi","hive","hello","hive"]]
    
  31. 分词后统计一起出现频次最高的TOP-K
    ngrams(array, int N, int K, int pf)
    返回值: array<struct<string,double>>
    与 sentences()函数一起使用,分词后,统计分词结果中一起出现频次最高的 TOP-K 结果

    hive> select ngrams(sentences('hello word!hello hive,hi hive,hello hive'),2,2);  
    [{"ngram":["hello","hive"],"estfrequency":2.0},{"ngram":["hive","hi"],"estfrequency":1.0}]
    //该查询中,统计的是两个词在一起出现频次最高的 TOP\-2  
    //结果中,hello 与 hive 同时出现 2 次
    
  32. 分词后统计与指定单词一起出现频次最高的TOP-K
    context_ngrams(array, array, int K, int pf)
    返回值:array<struct<string,double>>
    与 sentences()函数一起使用,分词后,统计分词结果中与数组中指定的单词一起出现(包括顺序)频次最高的 TOP-K 结果
    是紧跟着指定单词出现,可以跨越句子

    hive> select context_ngrams(sentences('hello word!hello hive,hi hive,hello hive'),array('hello',null),3);
    [{"ngram":["hive"],"estfrequency":2.0},{"ngram":["word"],"estfrequency":1.0}]
    //该查询中,统计的是与'hello'一起出现,并且在 hello 后面的频次最高的 TOP-3
    //结果中,hello 与 hive 同时出现 2 次,hello 与 word 同时出现 1 次
    
    hive> select context_ngrams(sentences('hello word!hello hive,hi hive,hello hive'),array(null,'hive'),3);
    [{"ngram":["hello"],"estfrequency":2.0},{"ngram":["hi"],"estfrequency":1.0}]
    //该查询中,统计的是与'hive'一起出现,并且在 hive 之前的频次最高的 TOP-3
    
    hive>select context\_ngrams(sentences('hello word hello hive,hi hive,hello hive'),array(null,'hive'),3);  
    [{"ngram":["hello"],"estfrequency":2.0},{"ngram":["hi"],"estfrequency":1.0}]
    
    hive>select context\_ngrams(sentences('hello hive,hello hive,hi hive,hello hive'),array(null,'hive'),3);  
    [{"ngram":["hello"],"estfrequency":3.0},{"ngram":["hi"],"estfrequency":1.0}]
    
    hive>select context\_ngrams(sentences('hello hive,hello hive,hello hive,hi hive,hello hive'),array(null,'hive'),3);
    [{"ngram":["hello"],"estfrequency":4.0},{"ngram":["hi"],"estfrequency":1.0}]
    
  33. 字符串反转函数: reverse(string A)
    返回字符串A的反转结果

    hive> select reverse(abcedfg’) from dual;
    gfdecba  
    
  34. 重复字符串函数:repeat(string str, int n)
    返回重复n次后的str字符串

    hive> select repeat('abc',5);
    abcabcabcabcabc
    

十二、混合函数

  1. 调用Java函数: java_method(class, method[, arg1[, arg2..]])
    返回值: varies
    调用 Java 中的方法处理数据

     hive> select reflect("java.net.URLEncoder", "encode", 'http://lxw1234.com',"UTF-8");
     http%3A%2F%2Flxw1234.com
     //该查询中调用 java.net.URLEncoder 中的encode方法,给该方法传的参数为'http://lxw1234.com',"UTF-8"
    
  2. 调用Java函数:reflect(class, method[, arg1[, arg2..]])
    返回值: varies
    调用 Java 中的方法处理数据

     hive> select reflect("java.net.URLDecoder", "decode",
     'http%3A%2F%2Flxw1234.com',"UTF-8");
     http://lxw1234.com
    
  3. 字符串的hash值:hash(a1[, a2…])
    返回值: int
    返回字符串的 hash 值

     hive> select hash('lxw1234.com');
     -809268416
    

十三、XPath解析XML函数

  1. xpath
    (string xmlstr,string xpath_expression)
    返回值: array
    从 xml 字符串中返回匹配到表达式的结果数组

     //获取 xml 字符串中 a/b/节点的值
     hive> select xpath('b1b2c1','a/b/text()') from lxw1234;
     ["b1","b2"]
     //获取 xml 字符串中所有名为 id 的属性值
     hive> select xpath('b1b2','//@id') from lxw1234;
     ["foo","bar"]
    
  2. xpath_string
    xpath_string(string xmlstr,string xpath_expression)
    返回值: string
    默认情况下,从 xml 字符串中返回第一个匹配到表达式的节点的值

     hive> select xpath_string ('b1b2', '//b') from lxw1234;
     b1
     3.
     //指定返回匹配到哪一个节点
     hive> select xpath_string ('b1b2', '//b[2]') from lxw1234;
     b2
    
  3. xpath_boolean
    xpath_boolean (string xmlstr,string xpath_expression)
    返回值: boolean
    返回 xml 字符串中是否匹配 xml 表达式

     hive> select xpath_boolean ('b', 'a/b') from lxw1234;  
     true
     hive> select xpath_boolean ('10', 'a/b < 10') from lxw1234;  
     false 
    
  4. xpath_short, xpath_int, xpath_long
    xpath_short (string xmlstr,string xpath_expression)
    xpath_int (string xmlstr,string xpath_expression)
    xpath_long (string xmlstr,string xpath_expression)
    返回值: int
    返回 xml 字符串中经过 xml 表达式计算后的值,如果不匹配,则返回0

     hive> SELECT xpath_int ('this is not a number', 'a') FROM lxw1234;  
     0
     hive> SELECT xpath_int ('1248', 'sum(a/*)') FROM lxw1234;  
     15
     hive> select xpath_long('10.511.2','sum(a/*)') from lxw1234;  
     21
    
  5. xpath_float, xpath_double, xpath_number
    xpath_float (string xmlstr,string xpath_expression)
    xpath_double (string xmlstr,string xpath_expression)
    path_number (string xmlstr,string xpath_expression)
    返回值: number
    返回 xml 字符串中经过 xml 表达式计算后的值,如果不匹配,则返回0

     hive> select xpath_double('10.511.2','sum(a/*)') from lxw1234;  
     21.7
    

十四、汇总统计函数(UDAF)

  1. 个数统计函数: count(*) || count(expr) || count(DISTINCT expr[, expr_.])

    count(*)统计检索出的行的个数,包括NULL值的行
    count(expr)返回指定字段的非空值的个数
    count(DISTINCTexpr[, expr_.])返回指定字段的不同的非空值的个数

     hive> select count(*) from lxw_dual;
     20
     hive> select count(distinct t) from lxw_dual;
     10
    
  2. 总和统计函数: sum(col) || sum(DISTINCT col)
    sum(col)统计结果集中col的相加的结果
    sum(DISTINCT col)统计结果中col不同值相加的结果

     hive> select sum(t) from lxw_dual;
     100
     hive> select sum(distinct t) from lxw_dual;
     70
    
  3. 平均值统计函数: avg(col) || avg(DISTINCT col)
    avg(col)统计结果集中col的平均值
    avg(DISTINCT col)统计结果中col不同值相加的平均值

     hive> select avg(t) from lxw_dual;
     50
     hive> select avg (distinct t) from lxw_dual;
     30
    
  4. 最小值统计函数: min(col)
    统计结果集中col字段的最小值

     hive> select min(t) from lxw_dual;
     20
    
  5. 最大值统计函数: max(col)
    统计结果集中col字段的最大值

     hive> select max(t) from lxw_dual;
     120
    
  6. 非空集合总体变量函数: var_pop(col)
    返回值: double
    统计结果集中col非空集合的总体变量(忽略null)

  7. 非空集合样本变量函数: var_samp (col)
    返回值: double
    统计结果集中col非空集合的样本变量(忽略null)

  8. 总体标准偏离函数: stddev_pop(col)
    返回值: double
    该函数计算总体标准偏离,并返回总体变量的平方根,其返回值与VAR_POP函数的平方根相同

  9. 样本标准偏离函数: stddev_samp (col)
    返回值: double
    该函数计算样本标准偏离

  10. 中位数函数: percentile

    • percentile(BIGINT col, p)
      求准确的第pth个百分位数,p必须介于0和1之间,但是col字段目前只支持整数,不支持浮点数类型

        hive>select percentile(id,0.2) from student;
        2.0
      
    • percentile(BIGINT col, array(p1 [, p2]…))
      功能和上述类似,之后后面可以输入多个百分位数,返回类型也为array,其中为对应的百分位数

        hive>select percentile(id,array(0.2,0.4)) from student;  
        [2.0,2.4000000000000004]
      
  11. 近似中位数函数: percentile_approx(DOUBLE col, p [, B])
    求近似的第pth个百分位数,p必须介于0和1之间,返回类型为double,但是col字段支持浮点类型。参数B控制内存消耗的近似精度,B越大,结果的准确度越高。默认为10,000。当col字段中的distinct值的个数小于B时,结果为准确的百分位数

  12. 直方图: histogram_numeric(col, b)
    返回值:array<struct {'x','y'}>
    以b为基准计算col的直方图信息

    hive> select histogram_numeric(100,5) from lxw_dual;
    [{"x":100.0,"y":1.0}]
    
  13. 集合去重数:collect_set(col)
    只接受基本数据类型,它的主要作用是将某字段的值进行去重汇总,产生array类型字段

    如下数据记录,要统计每种no下的score,这里就可以配合group by 产生奇效
    no  score
    1   2
    1   3
    1   3
    2   2
    2   4
    2   4
    hive>select no,collect_set(score) from tablss group by no;
    1	[2,3]
    2	[2,4]
    
    hive> select * from student;
    1	zhangsan	22
    2	lisi	21
    3	wangwu	17
    4	zhaoliu	25
    2	lisi	21
    3	wangwu	17
    4	zhaoliu	25
    hive>select name,collect_set(id) from student group by name;
    lisi [2]
    wangwu [3]
    zhangsan [1]
    zhaoliu [4]
    
  14. 集合不去重函数:collect_list (col)
    返回值: array
    将 col 字段合并成一个数组,不去重

    hive> select no,collect_list(score) from tablss group by no;
    1	[2,3,3]
    2	[2,4,4]
    
    hive> select name,collect_list(id) from student group by name;
    lisi	[2,2]
    wangwu	[3,3]
    zhangsan	[1]
    zhaoliu	[4,4]
    

十五、表格生成函数Table-Generating Functions (UDTF)

  1. 数组拆分成多行:explode

    • explode(array a)
      返回值:Array Type
      对于a中的每个元素,将生成一行且包含该元素

        hive> select explode(split(concat_ws(',','1','2','3','4','5','6','7','8','9'),',')) from test.dual;  
        1  
        2  
        3  
        4  
        5  
        6  
        7  
        8  
        9
      
  2. Map拆分成多行:explode

    • explode(MAP)
      map中每个key-value对,生成一行,key为一列,value为一列

        hive> select explode(map('k1','v1','k2','v2'));
        k1	v1
        k2	v2
      
posted @ 2020-10-20 16:38  猫熊小才天  阅读(579)  评论(0编辑  收藏  举报