#7、hive执行流程
#逻辑计划
#Antlr Antlr => AST
#another tool for language recognition
#D:\teaching\notes\kb12\system_install\hadoop\apache\apache-hive-3.1.2-src\ql\src\java\org\apache\hadoop\hive\ql\parse
#Hive.g => HiveLexer.g
SelectClauseParser.g
FromClauseParser.g
IdentifiersParser.g
HiveParser.g
selectStatement
:
selectClause
fromClause
whereClause?
groupByClause?
havingClause?
orderByClause?
clusterByClause?
distributeByClause?
sortByClause?
limitClause? -> ^(TOK_QUERY fromClause ^(TOK_INSERT ^(TOK_DESTINATION ^(TOK_DIR TOK_TMP_FILE))
selectClause whereClause? groupByClause? havingClause? orderByClause? clusterByClause?
distributeByClause? sortByClause? limitClause?))
;
#Ast AST => QueryBlock
#abstract syntax tree
#OperateTree QueryBlock => OperateTree
#LogicalOptimizer
#OperateTree => combine unnecessary ReduceSinkOperator
#物理计划
#遍历OperatorTree生成MapReduceTask
#物理层优化器进行MapReduce任务转换生成最终执行计划
#8、hive数据类型
|-------|-----------------------|-------------------------------|-------------------------------------------|
|类型 |java |mysql |hive |
|-------|-----------------------|-------------------------------|-------------------------------------------|
|字符 |char[]/String |char(n)/varchar(n) |string |
|-------|-----------------------|-------------------------------|-------------------------------------------|
|数值 |byte/short/int/long |tinyint/smallint/int/bigint |int/bigint |
| |BigInteger |decimal(38,18) |decimal(38,18) |
| |float/double | | |
| |BigDecimal | | |
|-------|-----------------------|-------------------------------|-------------------------------------------|
|布尔 |boolean |bit |boolean |
|日期 |Date |date/datetime/timestamp |date/datetime/timestamp |
| |Calender | | |
| |SimpleDateFormat | | |
|结构 |ArrayList |'aa,bb,cc' |array<TYPE> f[n] |
| |HashMap |'key1,key2,key3;v1,v2,v3' |map<KEY_TYPE,VALUE_TYPE> f['KEY'] |
| |class MyClass{} | |struct<f1:TYPE,f2:TYPE,...> f.f1 |
|-------|-----------------------|-------------------------------|-------------------------------------------|
#9、orc
列式文件存储格式
#很高的压缩比
#支持分裂(切片)
#查询优化
#为每一个字段建立一个轻量级的索引(字段索引:行偏移量)
#查询时先通过索引确认,不匹配直接跳行
#数据存储量少,传输量少,减少了Task数量
#10、内部表和外部表
create [external] table TABLE_NAME(...)...;
drop table TABLE_NAME;
#内部表:同时删除mysql中hive312内的表结构,和hdfs上存储的映射数据
#外部表:只能删除mysql中hive312内的表结构,如需删hdfs上的数据文件需要使用hdfs dfs -rm ...命令
#11、分区表 partitioned by … partition by order by 虚列 文件夹
create [external] table TABLE_NAME(
...
)
partitioned by (name type,name2 type2,...)
...;
#动态分区
-- 动态分区 : 适用于批量多分区数据挂载
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
set hive.exec.max.dynamic.partitions.pernode=1000; -- default 100
set hive.exec.max.dynamic.partitions=10000; -- default 1000
set hive.exec.max.created.files=15000; -- default 100000
#分桶表 clusted by … into N buckets 实列 文件 set hive.enforce.bucketing=true;
tablesample (bucket n outof m on rand()/column) m<N : N/m决定数量 n决定被抽取的桶编号
m>N : N/m为比例 抽取第n个桶的N/m%
tablesample(n PERCENT) hdfs粒度为块大小,所以BLOCK_SIZE*n%<=BLOCK_SIZE为BLOCK_SIZE
tablesample(n UNIT(M))
tablesample(n ROWS)
distribute by ... sort by ... 分区 分区内排序
cluster by 分区排序基于同一字段
#12、 常用函数
算术运算符:+ - * / % [& | ~ ^]
关系运算符:== [<>] > >= < <=
逻辑运算符:and or not
数学函数
# 1、pmod(±n,m)
-----------------------------------
select pmod(-3,5);
(-3+n*5)%5
# n为正整数取值为从1开始带入至表达式第一次为正值时的值
-----------------------------------
# 2、rand(seed) 伪随机
# 3、sign(num) 取表达式的符号
# 4、positive(num) 返回数值本身
# 5、negative(num) 返回数值的相反数
# 6、bin(num10) 返回10进制参数的2进制数值
# 7、conv(num,from_base,to_base) 进制转换
# 8、greatest(T...ts) 返回参数列表中的最大值
# 9、least(T...ts) 返回参数列表中的最小值
#10、bround(decimal) 银行家舍入法:
------------------------------------
bround(2.5)=>2
bround(3.5)=>4
------------------------------------
#11、shiftleft(bigint|int,int) 左移
#12、shiftright(bigint|int,int) 右移
字符串函数
# 1、concat(int|string|...)
# 2、concat_ws(string sep,string...|array<String>)
# 3、substr(cnt string,pos int[,len int]) pos从1开始
# 4、locate(substr,str[,pos]) 从pos开始找到substr首次出现首字母的位置,否则返回0
# 5、instr(str,substr) 找到substr在str中首次出现的首字母的位置,否则返回0
# 6、replace(str,substr,rep) 将str中的所有substr替换为rep
# 7、regexp_replace(str,regex,rep) 将str中满足regex规则的内容替换为rep
# 8、sentences(str)
# 将str以标点符号和空格分别作为第1、2个维度的分割符,将str拆分成一个二维数组
# 9、ngrams(array<array<string>> arr,int n,int topk)
# 对arr中连续n个单词做词频统计并倒序排列,将topk个统计结果返回
#10、context_ngrams(array<array<string>> arr,array<string> cnt,int topk)
# 对arr中连续size(cnt)个单词组合以cnt中非null内容匹配统计,按数量倒序排列,将topk个结果返回
#11、encode(string cnt,string encode) 将cnt转换为encode编码内容
#12、cast(exp as type) 将exp转为type类型的值
#13、get_json_object(string json,string path) 提取json字符串中指定key的值,一次解析一项但可多层
# path {key:value}: '$.key' '$.arraykey[index]' '$.objkey.subkey'
select get_json_object('{"name":"henry","hobbies":["s","a","c"],"address":{"province":"js","city":"nj"}}','$.name');
------------
henry
------------
select get_json_object('{"name":"henry", "hobbies":["s","a","c"], "address":{"province":"js","city":"nj"}}','$.hobbies[0]');
------------
s
------------
#14、json_tuple(string json,string...ps) 提取json字符串中指定key列表的值,一次解析多个但限一层
select json_tuple('{"name":"henry","hobbies":["s","a","c"],"address":{"province":"js","city":"nj"}}','name','hobbies','address');
+--------+----------------+--------------------------------+
| c0 | c1 | c2 |
+--------+----------------+--------------------------------+
| henry | ["s","a","c"] | {"province":"js","city":"nj"} |
+--------+----------------+--------------------------------+
#15、in_file(string cnt,string filepath) 返回内容cnt是否存在于文件filepath中
select in_file('KY08','/root/data/clacpy.log');
#16、parse_url(string url,string part[,string key]) 解析url根据part提取内容
# 当part为QUERY时添加key进行单独键的值提取
# part : PROTOCOL,HOST,QUERY,REF,PATH,USERINFO
#17、str rlike regex
select '{"name":"henry","age":"18","gender":"male"}' rlike '^.*?,"age":"\\d+",.*?$'; => true
#18、regexp_extract(str,group_regex,pos) 根据group_regex匹配str提取第pos个元素
select regexp_extract('{"name":"henry","age":"18","gender":"male"}','\\{"name":"(.*?)","age":"(.*?)","gender":"(.*?)"\\}',1);
#19、split(str,regex) 根据正则regex分割字符串,支持多字符分割
#20、str_to_map(string cnt,string kvsSep,string kvSep)
#将字符串cnt使用kvsSep作为键值对之间分隔符kvSep作为键和值的分隔符转化为map对象
#21、translate(str,from,to) 按照from同位置将str中的内容替换为to的内容
#22、md5(concat('salt_prefix',field,'salt_suffix')) 非对称加密,不可逆
#23、base64(binary(str)) 将str字符串使用base64加密 简单的对称加密
#24、unbase64(str) 将str字符串使用base64解密
#25、base64(aes_encrypt(string cnt,string secretKey)) 复杂的对称加密
# secretKey的长度 16+n(0~正整数)*8
select base64(aes_encrypt('I Love You','kb1220210616089009878909'));
--------------------
/OK+2+qfoemu6bdu58Cq3g==
--------------------
#26、aes_decrypt(unbase64(strAfterEnc),string secretKey)
集合函数
# 1、size(array/map) 返回集合元素的数量
# 2、array_contains(array,item) 返回数组中是否包含元素item
# 3、arrray(item1,...,itemn) 返回多个元素的数组
# 4、map(k1,v1,...,kn,vn) 返回多个元素的键值对
# 5、struct(v1,...,vn) 返回多个元素的结构体(自动追加列名col1,...coln)
# 6、map_keys(map) 返回键值对的键集合
# 7、map_values(map) 返回键值对的值集合
# 8、sort_array(array) 返回数组升序排序后的结果
日期函数
# 1、current_date() 返回系统当前日期
#current_timestamp() 返回系统当前日期的完整格式
#unix_timestamp([string|date|datetime|timestamp[,date_format]])
#默认返回系统当前时间戳(单位:秒)
#如果只有参数1,返回参数1的完整格式对应的时间戳
#如果有两个参数,返回参数1对应参数2格式的时间戳
# 2、date_add(date start_date,int days) 返回start_date之后第days天的日期
#add_months(string|date|datetime|timestamp start_date,int months)
#返回start_date之后第months月的日期
# 3、datediff(big_date,small_date) 返回两个日期之间的天数差值
# 4、from_unixtime(bigint[,date_format])返回时间戳对应的date_format格式字符串信息
#date_fromat(string|date|datetime|timestamp,date_format) 返回日期对应的date_format格式字符串信息
# 5、to_date(string|datetime|timestamp) 返回日期的年月日格式
# 6、next_day(string|datetime|timestamp,weekDay) 返回距离当前日期最近的下一个weekDay
# 7、last_day(string|datetime|timestamp) 返回参数日期所属月份最后一天的日期
# concat(year(current_date()),'-12-31') 年最后一天
# date_sub(add_months(trunc(current_date(),'Q'),3),1) 季度最后一天
# date_sub(next_day(current_date(),'MO'),1) 周最后一天
# 8、trunc(string|date|datetime|timestamp,part) 返回参数1对应参数2单位的第一天日期
# part : YY=>年 Q=>季 MM=>月
# date_add(next_day(date,'MO'),-7) 周第一天(星期一)日期
# 9、months_between(big_date,small_date) 返回两个日期之间的月数差
select months_between(current_date(),'2021-3-15');
---------
3.06451613
---------
条件函数
# 1、if(condition,if_true_val,if_false_val); 双重分支,相当于三元运算符
#nvl(field,default_val) field==null ? default_val : field
# 2、case [ field when CONST_V1 ] then V1 ... else VN end 等值判断多分支
# 3、case [ when field>=CONST_V1] then v1 ... else VN end 区间判断多分支
# 4、coalesce(T...vs) 返回参数列表中第一个非空值
# 5、ifnull(field) 返回filed列值是否为空
# 6、ifnotnull(field) 返回field列值是否不为空
侧视图
# 1、select ...,item_alias from TABLE_NAME lateral view func(field) LV_alias as item_alias;
聚合函数
# 1、sum([distinct] field)
# 2、avg([distinct] field)
# 3、count([distinct] field)
# 4、min(field)
# 5、max(field)
# 6、collect_list(field) 列举
# 7、collect_set(field) 去重
# 8、var_pop(numField) 方差
# 9、stddev_pop(numField) 标准差
#10、covar_pop(numBaseField,numField) 协方差
窗口函数(统计函数) 基于不同粒度扩展表的列
row_number()
rank()
dense_rank()
ntile(n)
lag(field,nth,defaultVal)
lead(field,nth,defaultVal)
first_value(field)
last_value(field)
nth_value(field,nth)
# 注意 :row_number,dense_rank, lead,lag等函数必须加order by且不支持window子句
OVER重句
over([partition by field[ order by field]] [rows between ... and ...])
# window 子句 rows between ... and ...
unbounded_preceding
n preceding
current_row
n following
unbounded_following
本文详细介绍了Hive的执行流程,包括逻辑计划和物理计划的转化,以及数据类型的对比。此外,还讨论了ORC文件格式的优势,内部表与外部表的区别,分区表和分桶表的概念。在函数部分,涵盖了算术、字符串、集合、日期和条件函数等,展示了Hive在数据处理中的丰富功能。
2万+

被折叠的 条评论
为什么被折叠?



