Hive的数据类型与DML和DDL

Hive 数据类型:

基本数据类型:

Hive数据类型Java数据类型长度例子
TINYINTbyte1byte有符号整数20
SMALINTshort2byte有符号整数20
INTint4byte有符号整数20
BIGINTlong8byte有符号整数20
BOOLEANboolean布尔类型,true或者falseTRUE FALSE
FLOATfloat单精度浮点数3.14159
DOUBLEdouble双精度浮点数3.14159
STRINGstring字符系列。可以指定字符集。可以使用单引号或者双引号。‘now is the time’ “for all good men”
TIMESTAMP时间类型
BINARY字节数组

​ 对于 Hive 的 String 类型相当于数据库的 varchar 类型,该类型是一个可变的字符串,不过它不能。其中最多能存储多少个字符,理论上它可以存储2GB的字符数。

集合数据类型:

数据类型描述语法示例
STRUCT和c语言中的struct类似,都可以通过“点”符号访问元素内容。例如,如果某个列的数据类型是STRUCT{first STRING, last STRING},那么第1个元素可以通过字段.first来引用。struct()
MAPMAP是一组键-值对元组集合,使用数组表示法可以访问数据。例如,如果某个列的数据类型是MAP,其中键->值对是’first’->’John’和’last’->’Doe’,那么可以通过字段名[‘last’]获取最后一个元素map()
ARRAY数组是一组具有相同类型和名称的变量的集合。这些变量称为数组的元素,每个数组元素都有一个编号,编号从零开始。例如,数组值为[‘John’, ‘Doe’],那么第2个元素可以通过数组名[1]进行引用。Array()

​ Hive 有三种复杂数据类型 ARRAY、MAP和STRUCT。ARRAY 和 MAP 与 Java 中的 Array 和 Map 类似,而 STRUCT 与 C 语言中的 Struct 类似,它封装了一个命名字段集合,复杂数据类型允许任意层次的嵌套。

案例实操:

​ 1)假设某表有如下一行,我们用JSON格式来表示其数据结构。在Hive下访问的格式为:

{
    "name": "songsong",
    "friends": ["bingbing" , "lili"] ,       //列表Array, 
    "children": {                      //键值Map,
        "xiao song": 18 ,
        "xiaoxiao song": 17  
  }
    "address": {                      //结构Struct,
        "street": "hai dian qu" ,
        "city": "beijing" 
    }
}

​ 2)基于上述数据结构,我们在Hive里创建对应的表,并导入数据。

​ 在 /opt/module 创建本地测试文件test.txt

songsong,bingbing_lili,xiao song:18_xiaoxiao song:17,hai dian qu_beijing
yangyang,caicai_susu,xiao yang:18_xiaoxiao yang:19,chao yang_beijing

​ 注意,MAP,STRUCT和ARRAY里的元素间关系都可以用同一个字符表示,这里用“_”。

​ 3)Hive上创建测试表test:

create table test(
name string,
friends array<string>,
children map<string, int>,
address struct<street:string, city:string>
)
row format delimited fields terminated by ','
collection items terminated by '_'
map keys terminated by ':'
lines terminated by '\n';

​ 字段解释:

​ row format delimited fields terminated by ‘,’ – 列分隔符

​ collection items terminated by ‘_’ --MAP STRUCT 和 ARRAY 的分隔符(数据分割符号)

​ map keys terminated by ‘:’ – MAP中的key与value的分隔符

​ lines terminated by ‘\n’; – 行分隔符

​ 4)导入文本数据到测试表:

​ hive (default)> load data local inpath ‘/opt/module/datas/test.txt’ into table test;

​ 5)访问三种集合列里的数据,以下分别是ARRAY,MAP,STRUCT的访问方式:

​ hive (default)> select friends[1]as朋友,children[‘xiao song’]as年龄,address.city from test where name=“songsong”;

OK
_c0     _c1     city
lili    18      beijing
Time taken: 0.076 seconds, Fetched: 1 row(s)

​ 如果起别名:select friends[1] as pengyou from test where name=“songsong”;

类型转换:

​ Hive 的原子类型是可以隐式转换的,类似于Java的类型转换,例如某表达式使用INT类型,TINYINT会自动转换为INT类型,但是Hive不会进行反向转化,例如,某表达式使用TINYINT类型,INT不会自动转换为TINYINT类型,它会返回错误,除非使用CAST操作。

​ 1)隐式类型转换规则如下。

​ (1)任何整数类型都可以隐式地转换为一个范围更广的类型,如TINYINT可以转换成INT,INT可以转换成BIGINT。

​ (2)所有整数类型、FLOAT和STRING类型都可以隐式地转换成DOUBLE。

​ (3)TINYINT、SMALLINT、INT都可以转换为FLOAT。

​ (4)BOOLEAN类型不可以转换为任何其它的类型。

​ 2)可以使用CAST操作显示进行数据类型转换,例如CAST(‘1’ AS INT)将把字符串’1’ 转换成整数1;如果强制类型转换失败,如执行CAST(‘X’ AS INT),表达式返回空值 NULL。

DDL 数据定义:

​ 数据库模式定义语言 DDL,是用于描述数据库中要存储的现实实体的语言。

​ 创建数据库:在创建的时候判断是否已经存在该数据库: create database if not exists db_hive

修改数据库:

​ 用户可以使用 ALTER DATABASE 命令为某个数据库的 DBPROPERTIES 设置 键-值 对属性值,来描述这个数据库的属性信息。

数据库的其他元数据信息都是不可更改的,包括数据库名和数据库所在的目录位置。

​ hive (default)> alter database db_hive set dbproperties(‘createtime’=‘20190506’);

​ 查看修改结果:

​ hive> desc database extended db_hive;

查询数据库:

​ 过滤显示查询的数据库:

​ hive>show databases like ‘db_hive*’; //只显示以 db_hive 开头的数据库

查看数据库详细:

​ 显示数据库信息:

​ hive> desc database db_hive;

​ 显示数据库详细信息,extended:

​ hive> desc database extended db_hive;

删除数据库:

​ 删除空数据库:

​ hive>drop database db_hive2;

​ 删除时判断是否存在:

​ hive> drop database if exists db_hive2;

​ 强制删除不为空的数据库:

​ hive> drop database db_hive cascade;

创建表:

​ 1)语法:

CREATE [EXTERNAL] TABLE [IF NOT EXISTS] table_name 
[(col_name data_type [COMMENT col_comment], ...)] 
[COMMENT table_comment] 
[PARTITIONED BY (col_name data_type [COMMENT col_comment], ...)] 
[CLUSTERED BY (col_name, col_name, ...) 
[SORTED BY (col_name [ASC|DESC], ...)] INTO num_buckets BUCKETS] 
[ROW FORMAT row_format] 
[STORED AS file_format] 
[LOCATION hdfs_path]

​ 2)字段解释说明:

​ (1)CREATE TABLE 创建一个指定名字的表。

​ 如果相同名字的表已经存在,则抛出异常;用户可以用 IF NOT EXISTS 选项来忽略这个异常。

​ (2)EXTERNAL 关键字可以让用户创建一个外部表,在建表的同时指定一个指向实际数据的路径(LOCATION),Hive创建内部表时,会将数据移动到数据仓库指向的路径;若创建外部表仅记录数据所在的路径,不对数据的位置做任何改变。在删除表的时候,内部表的元数据和数据会被一起删除,而外部表只删除元数据,不删除数据。

​ (3)COMMENT:为表和列添加注释。

​ (4)PARTITIONED BY 创建分区表

​ (5)CLUSTERED BY 创建分桶表

​ (6)SORTED BY 不常用

​ (7)ROW FORMAT 用户在建表的时候可以自定义 SerDe(序列化) 或者使用自带的 SerDe。如果没有指定 ROW FORMAT 或者 ROW FORMAT DELIMITED (分隔符),将会使用自带的 SerDe。在建表的时候,用户还需要为表指定列,用户在指定表的列的同时也会指定自定义的 SerDe,Hive 通过 SerDe 确定表的具体的列的数据。

​ (8)STORED AS 指定存储文件类型

​ 常用的存储文件类型:SEQUENCEFILE(二进制序列文件)、TEXTFILE(文本)、RCFILE(列式存储格式文件)

​ 如果文件数据是纯文本,可以使用STORED AS TEXTFILE。如果数据需要压缩,使用 STORED AS SEQUENCEFILE。

​ (9)LOCATION :指定表在HDFS上的存储位置。

​ (10)LIKE 允许用户复制现有的表结构,但是不复制数据。

管理表(内部表):

​ 1)理论:

​ 默认创建的表都是所谓的管理表,有时也被称为内部表。因为这种表,Hive 会(或多或少地)控制着数据的生命周期。Hive 默认情况下会将这些表的数据存储在由配置项 hive.metastore.warehouse.dir 所定义的目录的子目录下。

当我们删除一个管理表时,Hive也会删除这个表中数据。管理表不适合和其他工具共享数据。

​ 2)案例:

​ (1)普通创建表:

create table if not exists student2(
id int, name string
)
row format delimited fields terminated by '\t'
stored as textfile
location '/user/hive/warehouse/student2';

​ (2)根据查询结果创建表(查询的结果会添加到新创建的表中

create table if not exists student3
as select id, name from student;

​ (3)根据已经存在的表结构创建表

create table if not exists student4 like student;

​ (4)查询表的类型

hive (default)> desc formatted student2;

Table Type:             MANAGED_TABLE  

分区表:

​ 分区表实际上就是对应一个HDFS文件系统上的独立的文件夹,该文件夹下是该分区所有的数据文件。Hive中的分区就是分目录,把一个大的数据集根据业务需要分割成小的数据集。在查询时通过WHERE子句中的表达式选择查询所需要的指定的分区,这样的查询效率会提高很多。

外部表:

1)理论:

​ 删除该表时并不会删除掉数据,不过描述表的元数据信息会被删除掉

2)与内部表区别:

​ 每天将收集到的网站日志定期流入 HDFS 文本文件。在外部表(原始日志表)的基础上做大量的统计分析,中间表、结果表使用内部表存储,数据通过 SELECT + INSERT 进入内部表。

3)案例实操

​ 分别创建部门和员工外部表,并向表中导入数据。

原始数据:

​ 部门表:dept

10	ACCOUNTING	1700
20	RESEARCH	1800
30	SALES	1900
40	OPERATIONS	1700

​ 员工表:emp

7369	SMITH	CLERK	7902	1980-12-17	800.00		20
7499	ALLEN	SALESMAN	7698	1981-2-20	1600.00	300.00	30
7521	WARD	SALESMAN	7698	1981-2-22	1250.00	500.00	30
7566	JONES	MANAGER	7839	1981-4-2	2975.00		20
7654	MARTIN	SALESMAN	7698	1981-9-28	1250.00	1400.00	30
7698	BLAKE	MANAGER	7839	1981-5-1	2850.00		30
7782	CLARK	MANAGER	7839	1981-6-9	2450.00		10
7788	SCOTT	ANALYST	7566	1987-4-19	3000.00		20
7839	KING	PRESIDENT		1981-11-17	5000.00		10
7844	TURNER	SALESMAN	7698	1981-9-8	1500.00	0.00	30
7876	ADAMS	CLERK	7788	1987-5-23	1100.00		20
7900	JAMES	CLERK	7698	1981-12-3	950.00		30
7902	FORD	ANALYST	7566	1981-12-3	3000.00		20
7934	MILLER	CLERK	7782	1982-1-23	1300.00		10

创建表:

​ 部门表:

create external table if not exists dept(
deptno int,
dname string,
loc int
)
row format delimited fields terminated by '\t';

​ 员工表:

create external table if not exists emp(
empno int,
ename string,
job string,
mgr int,
hiredate string, 
sal double, 
comm double,
deptno int
)
row format delimited fields terminated by '\t';

向外部表中导入数据:

hive (jds)> load data local inpath ‘/opt/module/soft/dept.txt’ into table dept;

hive (jds)> load data local inpath ‘/opt/module/soft/emp.txt’ into table emp;

查看表格式化数据:

hive (jds)> desc formatted dept;

分区表基本操作:

创建分区表语法:
create table dept_partition(
               deptno int, dname string, loc string
               )
               partitioned by (month string)
               row format delimited fields terminated by '\t';
加载数据到分区表中:

​ hive (jds)> load data local inpath ‘/opt/module/soft/dept.txt’ into table dept_partition partition(month=‘201907’);

​ hive (jds)> load data local inpath ‘/opt/module/soft/dept.txt’ into table dept_partition partition(month=‘201908’);

分区查询:where

​ 单分区查询:select * from dept_partition where month=‘201908’;

​ 多分区联合查询:

select * from dept_partition where month='201907'
union
select * from dept_partition where month='201908';
创建分区:add

​ 创建单个分区:hive (jds)> alter table dept_partition add partiton(month=‘201909’);

​ 同时创建多个分区:alter table dept_partition add partition(month=‘201905’) partition(month=‘201906’);

删除分区:drop

​ 删除单个分区:hive (jds)> alter table dept_partition drop partition(month=‘201905’);

​ 删除多个分区:hive (jds)> alter table dept_partition drop partition(month=‘201906’),partition(month=‘201907’);

注:增加多个分区用 “ ”(空格)隔开,删除多个分区用 “ ,”(逗号) 隔开

**查看分区数:partitions **

​ hive (jds)> show partitions dept_partition;

**查看分区表结构:formatted **

​ hive (jds)> desc formatted dept_partition;

分区表的注意事项:

创建二级分区表:
create table dept_partition2(
               deptno int, dname string, loc string
               )
               partitioned by (month string, day string)
               row format delimited fields terminated by '\t';
正常的加载数据:

加载数据到二级分区表中:

​ hive (jds)> load data local inpath ‘/opt/module/soft/dept.txt’ into table dept_partition2 partition(month=‘201909’,day=‘13’);

查询分区数据:

​ hive (jds)> select * from dept_partition2 where month=‘201909’ and day=‘13’;

数据上传分区目录,让分区表和数据产生关联的方式:

方式一:先上传数据后同步元数据

​ **上传数据:**dfs -mkdir -p /user/hive/warehouse111/jds.db/dept_partition2/month=201910/day=10;

​ dfs -put /opt/module/soft/dept.txt /user/hive/warehouse111/jds.db/dept_partition2/month=201910/day=10;

​ **查询上传的数据:**hive (jds)> select * from dept_partition2 where month=‘201910’ and day=10; 数据为空

​ **同步元数据 msck repair :**hive (jds)> msck repair table dept_partition2;

​ **再次查询:**hive (jds)> select * from dept_partition2 where month=‘201910’ and day=10; 显示上传数据

方式二:上传数据后添加分区:

上传数据:hive (jds)> dfs -mkdir -p /user/hive/warehouse111/jds.db/dept_partition2/month=201910/day=11;

​ hive (jds)> dfs -put /opt/module/soft/dept.txt /user/hive/warehouse111/jds.db/dept_partition2/month=201910/day=11;

添加分区:hive (jds)> alter table dept_partition2 add partition(month=‘201910’,day=11);

查询数据:hive (jds)> select * from dept_partition2 where month=‘201910’ and day=11;

方式三:上传数据后 load 数据到分区

创建目录:hive (jds)> dfs -mkdir -p /user/hive/warehouse111/jds.db/dept_partition2/month=201910/day=12;

上传数据:hive (jds)> load data local inpath ‘/opt/module/soft/dept.txt’ into table dept_partition2 partition(month=‘201910’,day=12);

查询数据:hive (jds)> select * from dept_partition2 where month=‘201910’ and day=12;

修改表:

重命名表

案例:将 dept_partition2 改为 dept_partition3

​ hive (jds)> alter table dept_partition2 rename to dept_partition3;

增加/修改/替换列信息

添加列:deptdesc string

​ hive (jds)> alter table dept_partition add columns(deptdesc string);

更新列:将 deptdesc string 更新为 pid int

​ hive (jds)> alter table dept_partition change column deptdesc pid int;

替换列:全替换

​ hive (jds)> alter table dept_partition replace columns(deptno string,dname string,loc string);

DML 数据操作:

数据导入

​ 向表中转载数据:hive>load data [local] inpath ‘/opt/module/datas/student.txt’ [overwrite] into table student [partition (partcol1=val1,…)];

​ 1)load data:表示加载数据

​ 2)local:表示从本地加载数据带 hive 表;否则从 HDFS 加载数据到 hive 表

​ 3)inpath:表示加载数据的路径

​ 4)overwrite:表示覆盖表中已有数据,否则表示追加

​ 5)into table:表示加载到哪张表

​ 6)student:表示具体的表名

​ 7)partition:表示上传到指定分区

案例

​ 0、创建表:hive (jds)> create table student(id string, name string) row format delimited fields terminated by ‘\t’;

​ 1、加载本地文件到 hive:hive (default)> load data local inpath ‘/opt/module/datas/student.txt’ into table default.student;

​ 2、加载 HDFS 文件到 hive 中:

​ hive (default)> dfs -put /opt/module/datas/student.txt /user/itstar/hive;

​ hive (default)>load data inpath ‘/user/itstar/hive/student.txt’ into table default.student;

​ 3、加载数据覆盖表中已有的数据:

​ hive (default)> dfs -put /opt/module/datas/student.txt /user/itstar/hive;

​ hive (default)>load data inpath ‘/user/itstar/hive/student.txt’ overwrite into table default.student;

注:load hdfs 的数据相当于 mv(剪切) 文件到另一个目录中,源目录文件消失

通过查询语句向表中插入数据(insert)

​ 1、创建分区表:hive (jds)> create table student(id int, name string) partitioned by (month string) row format delimited fields terminated by ‘\t’;

​ 2、基本插入数据:hive (jds)> insert into table student partition(month=‘201907’) values(1,‘wangwu’);

​ 3、单表查询插入数据:hive (jds)> insert overwrite table student partition(month=‘201908’)

​ select id, name from student where month=‘201907’;

​ 4、多表查询插入数据:hive (jds)> from student

​ insert overwrite table student partition(month=‘201909’)

​ select id, name where month=‘201907’

​ insert overwrite table student partition(month=‘201910’)

​ select id, name where month=‘201908’;

创建表时通过 Location 指定加载数据路径

​ 1、创建表:hive (jds)> create table if not exists student2(

​ id int, name string)

​ row format delimited fields terminated by ‘\t’

​ location ‘/user/hive/warehouse/student2’;

​ 2、上传数据到 hdfs:hive (jds)> dfs -put /opt/module/soft/student.txt /user/hive/warehouse/student2;

​ 3、查询数据:hive (jds)> select * from student2; 注:数据显示成功

Import 数据到指定的 Hive 表中

​ 注意:先用 export 导出后(导出的数据目录里面附带有元数据),再 import 数据导入。同在 HDFS 上是 Copy 级操作

​ 命令:hive (jds)> export table student to ‘/user/hive/warehouse/export/student’;

​ 创建新表接受数据:hive (jds)> create table student3(

​ id int, name string)

​ partitioned by (month string)

​ row format delimited fields terminated by ‘\t’;

​ 向表中插入数据:hive (jds)> import table student3 from ‘/user/hive/warehouse/export/student’;

数据导出

1、将查询的数据导出到本地,数据之间无间隔

hive (jds)> insert overwrite local directory ‘/opt/module/datas/export/student’ select * from student;

2、将查询的数据导出到本地,数据之间 “\t” 间隔

hive (jds)> insert overwrite local directory ‘/opt/module/datas/export/student2’ ROW FORMAT DELIMITED FIELDS TERMINATED BY ‘\t’ select * from student;

3、将查询的结果导出到 HDFS 上

hive (jds)> insert overwrite directory ‘/user/student2’ ROW FORMAT DELIMITED FIELDS TERMINATED BY ‘\t’ select * from student;

注:虽然同是HDFS,但不是copy操作

4、Hadoop 命令导出到本地

hive (jds)> dfs -get /user/hive/warehouse/student/month=201809/000000_0 /opt/module/datas/export/student3.txt;

5、Hive Shell 命令导出

[root@bigdata111 module]# hive -e ‘select * from default.student;’ > /opt/module/datas/export/student4.txt;

6、Export导出到HDFS上

hive (jds)> export table default.student to ‘/user/hive/warehouse/export/student’;

7、清除数据

hive (jds)> truncate table student;

注:Truncate只能删除管理表,不能删除外部表中数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值