hive 操作

本文详细介绍了Hive的执行流程,包括逻辑计划和物理计划的转化,以及数据类型的对比。此外,还讨论了ORC文件格式的优势,内部表与外部表的区别,分区表和分桶表的概念。在函数部分,涵盖了算术、字符串、集合、日期和条件函数等,展示了Hive在数据处理中的丰富功能。
摘要由CSDN通过智能技术生成

#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
		数学函数
			# 1pmod(±n,m)
			-----------------------------------
			select pmod(-3,5);
			(-3+n*5)%5
			# n为正整数取值为从1开始带入至表达式第一次为正值时的值
			-----------------------------------
			# 2rand(seed)	伪随机
			# 3sign(num)	取表达式的符号
			# 4positive(num)	返回数值本身
			# 5negative(num)	返回数值的相反数
			# 6bin(num10)		返回10进制参数的2进制数值
			# 7conv(num,from_base,to_base)	进制转换
			# 8greatest(T...ts)	返回参数列表中的最大值
			# 9least(T...ts)		返回参数列表中的最小值
			#10bround(decimal)	银行家舍入法:
			------------------------------------
			bround(2.5)=>2
			bround(3.5)=>4
			------------------------------------
			#11shiftleft(bigint|int,int)	左移
			#12shiftright(bigint|int,int)	右移
		字符串函数
			# 1concat(int|string|...)
			# 2concat_ws(string sep,string...|array<String>)
			# 3substr(cnt string,pos int[,len int]) pos从1开始
			# 4locate(substr,str[,pos])			从pos开始找到substr首次出现首字母的位置,否则返回0
			# 5instr(str,substr)					找到substr在str中首次出现的首字母的位置,否则返回0
			# 6replace(str,substr,rep)				将str中的所有substr替换为rep
			# 7regexp_replace(str,regex,rep) 		将str中满足regex规则的内容替换为rep
			# 8sentences(str)
				# 将str以标点符号和空格分别作为第12个维度的分割符,将str拆分成一个二维数组
			# 9ngrams(array<array<string>> arr,int n,int topk)
				# 对arr中连续n个单词做词频统计并倒序排列,将topk个统计结果返回
			#10context_ngrams(array<array<string>> arr,array<string> cnt,int topk)
				# 对arr中连续size(cnt)个单词组合以cnt中非null内容匹配统计,按数量倒序排列,将topk个结果返回
			#11encode(string cnt,string encode)	将cnt转换为encode编码内容
			#12cast(exp as type)					将exp转为type类型的值
			#13get_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
				------------
			#14json_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"}  |
				+--------+----------------+--------------------------------+
			#15in_file(string cnt,string filepath)	返回内容cnt是否存在于文件filepath中
				select in_file('KY08','/root/data/clacpy.log');
			#16parse_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
			#18regexp_extract(str,group_regex,pos)	根据group_regex匹配str提取第pos个元素
				select regexp_extract('{"name":"henry","age":"18","gender":"male"}','\\{"name":"(.*?)","age":"(.*?)","gender":"(.*?)"\\}',1);
			#19split(str,regex)	根据正则regex分割字符串,支持多字符分割
			#20str_to_map(string cnt,string kvsSep,string kvSep)
				#将字符串cnt使用kvsSep作为键值对之间分隔符kvSep作为键和值的分隔符转化为map对象
			#21translate(str,from,to)	按照from同位置将str中的内容替换为to的内容
			#22md5(concat('salt_prefix',field,'salt_suffix')) 非对称加密,不可逆
			#23base64(binary(str))	将str字符串使用base64加密	简单的对称加密
			#24unbase64(str)			将str字符串使用base64解密
			#25base64(aes_encrypt(string cnt,string secretKey))	复杂的对称加密
				# secretKey的长度 16+n(0~正整数)*8
				select base64(aes_encrypt('I Love You','kb1220210616089009878909'));
				--------------------
				/OK+2+qfoemu6bdu58Cq3g==
				--------------------
			#26aes_decrypt(unbase64(strAfterEnc),string secretKey)
		集合函数
			# 1size(array/map)				返回集合元素的数量
			# 2array_contains(array,item)		返回数组中是否包含元素item
			# 3arrray(item1,...,itemn)		返回多个元素的数组
			# 4map(k1,v1,...,kn,vn)			返回多个元素的键值对
			# 5struct(v1,...,vn)				返回多个元素的结构体(自动追加列名col1,...coln)
			# 6map_keys(map)					返回键值对的键集合
			# 7map_values(map)				返回键值对的值集合
			# 8sort_array(array)				返回数组升序排序后的结果
		日期函数
			# 1current_date()						返回系统当前日期
				#current_timestamp()				返回系统当前日期的完整格式
				#unix_timestamp([string|date|datetime|timestamp[,date_format]])					
												   #默认返回系统当前时间戳(单位:秒)
												   #如果只有参数1,返回参数1的完整格式对应的时间戳
												   #如果有两个参数,返回参数1对应参数2格式的时间戳
			# 2date_add(date start_date,int days)	返回start_date之后第days天的日期
				#add_months(string|date|datetime|timestamp start_date,int months)
												   #返回start_date之后第months月的日期
			# 3datediff(big_date,small_date)		返回两个日期之间的天数差值
			# 4from_unixtime(bigint[,date_format])返回时间戳对应的date_format格式字符串信息
				#date_fromat(string|date|datetime|timestamp,date_format) 返回日期对应的date_format格式字符串信息
			# 5to_date(string|datetime|timestamp)				返回日期的年月日格式
			# 6next_day(string|datetime|timestamp,weekDay)	返回距离当前日期最近的下一个weekDay
			# 7last_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)				周最后一天
			# 8trunc(string|date|datetime|timestamp,part) 返回参数1对应参数2单位的第一天日期
				# part : 												YY=>Q=>季 MM=>月
				# date_add(next_day(date,'MO'),-7)						周第一天(星期一)日期
			# 9months_between(big_date,small_date)		返回两个日期之间的月数差
				select months_between(current_date(),'2021-3-15');
				---------
				3.06451613
				---------
		条件函数
			# 1if(condition,if_true_val,if_false_val);				双重分支,相当于三元运算符
				#nvl(field,default_val)									field==null ? default_val : field
			# 2case [ field when CONST_V1 ] then V1 ... else VN end	等值判断多分支
			# 3case [ when field>=CONST_V1] then v1 ... else VN end	区间判断多分支
			# 4coalesce(T...vs)										返回参数列表中第一个非空值
			# 5ifnull(field)											返回filed列值是否为空
			# 6ifnotnull(field)										返回field列值是否不为空
		侧视图
			# 1、select ...,item_alias from TABLE_NAME lateral view func(field) LV_alias as item_alias;
		聚合函数
			# 1sum([distinct] field)
			# 2avg([distinct] field)
			# 3count([distinct] field)
			# 4min(field)
			# 5max(field)
			# 6collect_list(field)				列举
			# 7collect_set(field)					去重
			# 8var_pop(numField)					方差
			# 9stddev_pop(numField)				标准差
			#10covar_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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值