Hive DML 數據庫定義,表定義等操作

數據導入

向表中裝載數據

1.語法

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:表示上傳到指定分區

2.實操案例

(1)創建一張表

create table student(id string, name string) row format delimited fields terminated by '\t';

(2)加載本地文件到 hive

load data local inpath 'student.txt' into table student;

(3)加載 HDFS 文件到 hive 中  上傳文件到 HDFS

hive(test)> dfs -put 'student.txt' '/hive/student';
加載 HDFS 上數據
load data inpath '/hive/student.txt' into table student;

(4)加載數據覆蓋表中已有的數據上傳文件到 HDFS

hive(test)> dfs -put 'student.txt' '/hive/student';
加載數據覆蓋表中已有的數據
load data inpath 'student.txt' overwrite into table student;

通過查詢語句向表中插入數據(Insert)

1.創建一張分區表

create table student_partition(id int, name string) partitioned by (month string) row format delimited fields terminated by '\t';

2.基本插入數據

insert into table student_partition partition(month='202005')values(1, 'zhangsan');
insert into table student_partition partition(month='202004')values(2, 'lisi');

3.基本模式插入(根據單張表查詢結果)

insert overwrite table student_partition partition(month='202005') select id, name from student_partition where month='202004';

4.多插入模式(根據多張表查詢結果)

多表插入的關鍵點在於將所要執行查詢的表語句 "from 表名",放在最開頭位置。

from student_partition
insert overwrite table student_partition partition(month='202005') select id,name where month = '202005'
insert overwrite table student_partition partition(month='202004') select id,name where month = '202005';

查詢語句中創建表並加載數據(As Select)

根據查詢結果創建表(查詢的結果會添加到新創建的表中)

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

創建表時通過 Location 指定加載數據路徑

1.創建表,並指定在 hdfs 上的位置

create table if not exists student5(id int, name string) 
row format delimited fields terminated by ' '  
location '/hive/student5';

2.上傳數據到 hdfs 上

hive> dfs -put student.txt /hive/student5;

3.查詢數據

hive> select * from student5;

Import 數據到指定 Hive 表中

注意:先用 export 導出後,再將數據導入。

hive> import table student5 partition(month='202005') from '/hive/student5';

數據導出

Insert 導出

1.將查詢的結果導出到本地

insert overwrite local directory '/root/data' select * from student;

2.將查詢的結果格式化導出到本地

insert overwrite local directory 'root/data' row format delimited fields terminated by '\t'
select * from student;

3.將查詢的結果導出到 HDFS 上(沒有 local)

insert overwrite directory '/root/data' row format delimited fields terminated by '\t'
select * from student;

Hive Shell 命令導出

基本語法:(hive -f/-e 執行語句或者腳本 > file)

[hive]$ bin/hive -e 'select * from default.student;' > /root/data/student4.txt;

Export 導出到 HDFS 上

export table student to '/hive/student';

清除表中數據(Truncate)

注意:Truncate 只能刪除管理表,不能刪除外部表中數據

truncate table student;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章