Hive 从 0 到 1 学习 —— 第五章 Hive DDL 语句定义

1. 创建数据库

  1. 创建一个数据库,数据库在 HDFS 上的默认存储路径是 /user/hive/warehouse/*.db

    hive (default)> create database db_hive;
    
  2. 避免要创建的数据库已经存在错误,增加 if not exists判断。(标准写法)

    hive (default)> create database if not exists db_hive;
    
  3. 创建一个数据库,指定数据库在HDFS上存放的位置

    hive (default)> create database if not exists db_hive location '/warehouse/db_hive.db';
    

在这里插入图片描述

数据库存放位置
## 2. 查询数据库

2.1 显示数据库

  1. 显示数据库

    hive> show databases;
    
  2. 过滤显示查询的数据库

    hive> show databases like 'db_hive*';
    OK
    db_hive
    db_hive_1
    

2.2 查看数据库详情

  1. 显示数据库信息

    hive (default)> desc database db_hive;
    OK
    db_name	comment	location	owner_name	owner_type	parameters
    db_hive		hdfs://hadoop102:9000/warehouse/db_hive.db	dwjf321	USER	
    Time taken: 0.051 seconds, Fetched: 1 row(s)
    
  2. 显示数据库详细信息,extended

    hive (default)> desc database extended db_hive;
    OK
    db_name	comment	location	owner_name	owner_type	parameters
    db_hive		hdfs://hadoop102:9000/warehouse/db_hive.db	dwjf321	USER	{create_time=20201217}
    Time taken: 0.044 seconds, Fetched: 1 row(s)
    

2.3 切换当前数据库

hive (default)> use db_hive;

3. 修改数据库

用户可以使用 ALTER DATABASE命令为某个数据库的 DBPROPERTIES设置键-值对属性值,来描述这个数据库的属性信息。数据库的其他元数据信息都是不可更改的,包括数据库名和数据库所在的目录位置。

hive (default)> alter database db_hive set dbproperties('create_time'='20201217');

在hive中查看修改结果

hive> desc database extended db_hive;
OK
db_name	comment	location	owner_name	owner_type	parameters
db_hive		hdfs://hadoop102:9000/warehouse/db_hive.db	dwjf321	USER	{create_time=20201217}
Time taken: 0.044 seconds, Fetched: 1 row(s)

4. 删除数据库

  1. 删除空数据库

    hive>drop database db_hive;
    
  2. 如果删除的数据库不存在,最好采用 if exists判断数据库是否存在

    hive> drop database if exists db_hive;
    
  3. 如果数据库不为空,可以采用cascade命令,强制删除

    hive> drop database db_hive cascade;
    

5. 创建表

5.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]

5.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

    DELIMITED [FIELDS TERMINATED BY char] 
    [COLLECTION ITEMS TERMINATED BY char]
    [MAP KEYS TERMINATED BY char] 
    [LINES TERMINATED BY char]
    | SERDE serde_name [WITH SERDEPROPERTIES (property_name=property_value, property_name=property_value, ...)]
    

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

    SerDe是Serialize/Deserilize的简称,目的是用于序列化和反序列化。

  8. STORED AS:指定存储文件类型

    常用的存储文件类型:

    • SEQUENCEFILE(二进制序列文件)

    • TEXTFILE(文本)

    • RCFILE(列式存储格式文件)

    如果文件数据是纯文本,可以使用STORED AS TEXTFILE

    如果数据需要压缩,使用 STORED AS SEQUENCEFILE

  9. LOCATION:指定表在HDFS上的存储位置。

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

5.3 管理表(内部表)

5.3.1 理论

默认创建的表都是所谓的管理表,有时也被称为内部表。因为这种表,Hive 会(或多或少地)控制着数据的生命周期。Hive 默认情况下会将这些表的数据存储在由配置项 hive.metastore.warehouse.dir(例如,/user/hive/warehouse)所定义的目录的子目录下。当我们删除一个管理表时,Hive 也会删除这个表中数据。管理表不适合和其他工具共享数据。

5.3.2 案例实操

  1. 普通创建表

    create table if not exists test2 (
    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';
    
  2. 根据查询结果创建表(查询的结果会添加到新创建的表中)

    create table if not exists test3 as select name,friends,children,address from test;
    
  3. 根据已经存在的表结构创建表

    create table if not exists test4 like test;
    
  4. 查询表的类型

    hive (default)> desc formatted test;
    OK
    col_name	data_type	comment
    # col_name            	data_type           	comment             
    	 	 
    name                	string              	                    
    friends             	array<string>       	                    
    children            	map<string,int>     	                    
    address             	struct<street:string,city:string>	                    
    	 	 
    # Detailed Table Information	 	 
    Database:           	default             	 
    Owner:              	dwjf321             	 
    CreateTime:         	Thu Dec 17 22:32:58 CST 2020	 
    LastAccessTime:     	UNKNOWN             	 
    Protect Mode:       	None                	 
    Retention:          	0                   	 
    Location:           	hdfs://hadoop102:9000/user/hive/warehouse/test	 
    Table Type:         	MANAGED_TABLE       	 
    Table Parameters:	 	 
    	COLUMN_STATS_ACCURATE	true                
    	numFiles            	1                   
    	totalSize           	143                 
    	transient_lastDdlTime	1608215811          
    	 	 
    # Storage Information	 	 
    SerDe Library:      	org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe	 
    InputFormat:        	org.apache.hadoop.mapred.TextInputFormat	 
    OutputFormat:       	org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat	 
    Compressed:         	No                  	 
    Num Buckets:        	-1                  	 
    Bucket Columns:     	[]                  	 
    Sort Columns:       	[]                  	 
    Storage Desc Params:	 	 
    	colelction.delim    	_                   
    	field.delim         	,                   
    	line.delim          	\n                  
    	mapkey.delim        	:                   
    	serialization.format	,                   
    Time taken: 0.118 seconds, Fetched: 36 row(s)
    

5.4 外部表

5.4.1 理论

因为表是外部表,所以 Hive 并非认为其完全拥有这份数据。删除该表并不会删除掉这份数据,不过描述表的元数据信息会被删除掉

5.4.2 管理表和外部表的使用场景

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

5.4.3 案例操作

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

  1. 数据准备

    部门数据

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

    员工数据

    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
    
  2. 建表语句

    部门表

    create external table if not exists dept(
    deptno int comment '部门ID',
    dname string comment '部门名称',
    loc int
    ) comment '部门表'
    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';
    
  3. 向外部表中导入数据

    load data local inpath '/opt/module/hive/examples/files/dept.txt' into table dept;
    load data local inpath '/opt/module/hive/examples/files/emp.txt' into table emp;
    
  4. 查看表格式化数据

    desc formatted emp;
    

5.5 管理表与外部表相互转换

  1. 查询表的类型

    hive (default)> desc formatted test3;
    Table Type:         	MANAGED_TABLE
    
  2. 修改内部表 test3为外部表

    alter table test3 set tblproperties('EXTERNAL'='TRUE');
    
  3. 查询表的类型

    hive (default)> desc formatted test3;
    Table Type:         	EXTERNAL_TABLE
    
  4. 修改外部表test3为内部表

    alter table test3 set tblproperties('EXTERNAL'='FALSE');
    
  5. 查询表的类型

    hive (default)> desc formatted test3;
    Table Type:         	MANAGED_TABLE
    

6. 分区表

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

6.1 分区表基本操作

  1. 创建分区表

    create external table if not exists dept_partition(
    deptno int comment '部门ID',
    dname string comment '部门名称',
    loc int
    ) comment '部门表'
    partitioned by (month string)
    row format delimited fields terminated by '\t'; 
    
  2. 导入数据到分区表

    hive (default)> load data local inpath '/opt/module/hive/examples/files/dept.txt' into table dept_partition partition(month='202010');
    hive (default)> load data local inpath '/opt/module/hive/examples/files/dept.txt' into table dept_partition partition(month='202011');
    hive (default)> load data local inpath '/opt/module/hive/examples/files/dept.txt' into table dept_partition partition(month='202012');
    

在这里插入图片描述

  1. 查询分区表中数据

    单分区查询

    hive (default)> select * from dept_partition where month='202010';
    OK
    dept_partition.deptno	dept_partition.dname	dept_partition.loc	dept_partition.month
    10	ACCOUNTING	1700	202010
    20	RESEARCH	1800	202010
    30	SALES	1900	202010
    40	OPERATIONS	1700	202010
    Time taken: 0.103 seconds, Fetched: 4 row(s)
    

    多分区查询

    hive (default)> select * from dept_partition where month='202010'
                  > union
                  > select * from dept_partition where month='202011'
                  > union
                  > select * from dept_partition where month='202012'
                  > ;
    OK
    _u3.deptno	_u3.dname	_u3.loc	_u3.month
    10	ACCOUNTING	1700	202010
    10	ACCOUNTING	1700	202011
    10	ACCOUNTING	1700	202012
    20	RESEARCH	1800	202010
    20	RESEARCH	1800	202011
    20	RESEARCH	1800	202012
    30	SALES	1900	202010
    30	SALES	1900	202011
    30	SALES	1900	202012
    40	OPERATIONS	1700	202010
    40	OPERATIONS	1700	202011
    40	OPERATIONS	1700	202012
    Time taken: 26.314 seconds, Fetched: 12 row(s)
    
  2. 增加分区

    创建单个分区

    hive (default)> alter table dept_partition add partition(month='202009');
    OK
    Time taken: 0.134 seconds
    

    同时创建多个分区

    hive (default)> alter table dept_partition add partition(month='202008') partition(month='202007');
    OK
    Time taken: 0.153 seconds
    
  3. 删除分区

    删除单个分区

    hive (default)> alter table dept_partition drop partition(month='202008');
    Dropped the partition month=202008
    OK
    Time taken: 0.391 seconds
    

    同时删除多个分区

    hive (default)> alter table dept_partition drop partition(month='202007'),partition(month='202009');
    Dropped the partition month=202007
    Dropped the partition month=202009
    OK
    Time taken: 0.201 seconds
    
    
  4. 查看分区表有多少分区

    hive (default)> show partitions dept_partition;
    OK
    partition
    month=202010
    month=202011
    month=202012
    Time taken: 0.074 seconds, Fetched: 3 row(s)
    
  5. 查看分区表结构

    hive (default)> desc formatted dept_partition;
    # Partition Information	 	 
    # col_name            	data_type           	comment             
    	 	 
    month               	string 
    

6.2 二级分区表

  1. 创建二级分区表

    create table if not exists detp_2_partition
    (
    deptno int,
    dname string,
    loc string
    )
    partitioned by (month string, day string)
    row format delimited fields terminated by '\t';
    
  2. 导入数据

    hive (default)> load data local inpath '/opt/module/hive/examples/files/dept.txt' into table detp_2_partition partition(month='202012',day='18');
    
  3. 查询数据

    hive (default)> select * from detp_2_partition where month='202012' and day='18';
    

7. 修改表

7.1 修改表名

  1. 语法

    alter table table_name1 rename to table_name2;
    
  2. 实例操作

    hive (default)> alter table test4 rename to test5;
    

7.2 增加、修改和删除表分区

详见 6.1 分区表基本操作

7.3 增加/修改/替换列信息

  1. 语法

    更新列

    ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]
    

    增加和替换列

    ALTER TABLE table_name ADD|REPLACE COLUMNS (col_name data_type [COMMENT col_comment], ...) 
    
  2. 案例实操

    1. 查询表结构

      hive> desc dept_partition;
      
    2. 添加列

      hive (default)> alter table dept_partition add columns(deptdesc string);
      
    3. 查询表结构

      hive> desc dept_partition;
      
    4. 更新列

      hive (default)> alter table dept_partition change column deptdesc desc int;
      
    5. 查询表结构

      hive> desc dept_partition;
      
    6. 替换列

      hive (default)> alter table dept_partition replace columns(deptno string, dname
      
       string, loc string);
      
    7. 查询表结构

      hive> desc dept_partition;
      

    8. 删除表

    hive (default)> drop table dept_partition;
    

猜你喜欢

转载自blog.csdn.net/dwjf321/article/details/112726683
今日推荐