HiveQL学习笔记2
1、操作与函数
可以在hive的shell环境中输入SHOW FUNCTIONS以获取函数列表。
例如:
Hive> DESCRIBE FUNCTION length;
2、表
托管表和外部表
在Hive创建表时,默认情况下Hive负责管理数据,这意味着Hive把数据移入他的“仓库目录”,另一种选择是创建一个外部表,这会让Hive到仓库目录以外的位置访问数据。
加载数据到托管表:
create table managed_table (dummy STRING);
load data inpath ‘/user/tom/data.txt’ into table managed_table;
丢弃一个表
drop table managed_table; 他会删除元数据和数据
外部表:
create external table external_table(dummy STRING) location ‘/user/tom/external_table’;
load data inpath ‘/user/tom/data.txt’ into table external_table;
在丢弃外部表的时候,只会删除元数据,hive不会删除数据。
3、分区和桶
Hive把表组织成分区,只是一种根据分区列的值对表进行粗略的划分(例如根据日期划分分区),表或分区可以进一步分为桶,他会为数据提供额外的结构以获得更高效的查询处理(例如根据用户ID来划分桶)
分区:
定义分区:
create table logs(ts BIGINT, line STRING) partitioned by(dt STRING, country STRING);
在我们将数据加载到分区表的时候,需要指定分区值:
Load data local inpath ‘input/hive/partitions/file1’ into table logs partition(dt=“2018-05-31”,country=“cn”);
在文件系统中,分区只是在表目录下的一个子目录,
桶:
把表或者分区组织成桶有两个理由:1、获得更高的查询处理效率。连接两个在相同列上划分了桶的表,可以使用map段连接高效的实现。2、使“取样”更高效,在处理大规模数据集时,在开发和修改查询阶段,如果能在数据集的一小部分数据上试运行查询会带来很多方便。
划分桶:
Create table bucketed_users (id INT, name STRING) clustered by (id) into 4 buckets;
将查询限制在一个桶内:
Select * from bucketed_users tablesample(bucket 1 out of 4 on id);
4、存储格式
Hive从 行格式 和 文件格式 对表的存储进行管理。
Avro是Hadoop中的一个子项目,也是Apache中一个独立的项目,Avro是一个基于二进制数据传输高性能的中间件。在Hadoop的其他项目中例如HBase(Ref)和Hive(Ref)的Client端与服务端的数据传输也采用了这个工具。Avro是一个数据序列化的系统。Avro可以将数据结构或对象转化成便于存储或传输的格式。Avro设计之初就用来支持数据密集型应用,适合于远程或本地大规模数据的存储和交换。
5、导入数据
insert语句
insert overwrite table target select col1, col2 from source;
insert overwrite table target partition(dt=“2018-5-31”) select col1, col2 from source;
insert overwrite table target partition(dt) select col1, col2, dt from source;
多表插入:
From records2
Insert overwrite table stations_by_year
Select year, count(distinct station )
Group by year
Insert overwrite table records_by_year
Select year, count(1)
Group by year
Insert overwrite table good_records_by_year
Select year, count(1)
Where temperature != 9999 and quality in (0,1,4,5,9)
Group by year;
6、表的修改
alter table source rename to target;
alter table target add columns(col3 STRING);
truncate table my_table; 删除表内的数据,但是保留表的定义
7、排序和聚集
From records2 select year, temperature distribute by year sort by year ASC, temperature DESC;
如果sort by 和 distribute by 中所有的列相同,可以缩写为cluster by以便同时制定两者所有的列。
8、MapReduce脚本
待编辑
9、连接
内连接:
Select sales., things. from sales join things on (sales.id = things.id);
左外连接:
Select sales., things. from sales left outer join things on (sales.id=things.id);
右外连接:
Select sales., things. from sales right outer join things on (sales.id = things.id);
全连接:
Select sales.* , things.* from sales full outer join things on (sales.id = things.id);
半连接:
Select * from things where things.id in (select id from sales);
Map 连接:
Select sales., things. from sales join things on (sales.id= things.id);