Hive 之 數據的導入與導出及刪除
一、數據導入
1.1 向表中加載數據(load): 用的很多
load data [local] inpath '/home/data/aaa.txt' [overwrite] into table student
[partition(partcol1=val1, partcol2=val2, ...)];
參數說明:
load data: 表示加載數據;
local: 表示從本地加載數據到 Hive 表, 否則表示從 HDFS 加載數據到 Hive 表;
inpath: 表示加載數據的路徑;
overwrite: 表示覆蓋表中的已有數據, 沒有表示追加;
into table: 表示加載到哪張表;
student: 具體的表名;
partition: 表示上傳到指定分區;
1.2 通過查詢語句向表中插入數據(insert): 用的很多
1.2.1 基本模式插入: (根據單張表查詢結果)
insert overwrite | into haha [partition(month='2019-03')] select id from aa;
可以將 select id from aa
的結果覆蓋(插入)到 haha 表中;
1.2.2 多插入模式: (根據多張表查詢結果) 用的不多
from student
insert overwrite table student partition(month='2019-07')
select id, name where month='2019-09'
insert overwrite table student partition(month='2019-06')
select id, name where month-'2019-09';
其中,from student
是由於多個語句【同時存在】, 所以給提出來了;
1.3 查詢語句中創建表並加載數據(as select):
hive (default)> create table if not exists hehe
> as select id from haha;
hive (default)> select * from hehe;
OK
hehe.id
1
2
3
4
5
6
Time taken: 0.062 seconds, Fetched: 6 row(s)
1.4 創建表時通過 location 指定加載數據路徑
在 HDFS 上創建路徑並 put 進一個數據文件:
[root@hadoop102 data]# hadoop fs -mkdir -p /atguigu/hive/aa
[root@hadoop102 data]# hadoop fs -put aa.txt /atguigu/hive/aa
創建表, 使用 location
指向剛剛創建的目錄:
hive (default)> create table if not exists heihei(id int)
> location '/atguigu/hive/aa';
OK
Time taken: 0.22 seconds
查詢數據:
hive (default)> select * from heihei;
OK
heihei.id
1
2
3
4
5
6
Time taken: 0.116 seconds, Fetched: 6 row(s)
1.5 import 數據到指定 Hive 表中: (瞭解即可)
import table student partition(month='2019-08') from '/user/hive/warehouse/export/student';
【注意】得先用 export 導出數據後, 才能使用 import 導入;(因爲需要 export 出來的元數據信息)
如果想隨意指定路徑文件就能導入 Hive 表中, 就得使用 load 命令;
二、 數據導出
2.1 insert 導出:
2.1.1 將查詢的結果導出到本地:
hive (default)> insert overwrite local directory '/opt/module/data/dept' select * from dept;
【注意】這樣導出來的數據, 字段間沒有分隔符, 都是緊挨着在一起的, 後續無法使用;
2.1.2 將查詢的結果格式化後導出到本地:
hive (default)> insert overwrite local directory '/opt/module/data/dept'
> row format delimited fields terminated by '\t' select * from dept;
這樣導出來的數據, 使用 “\t” 分割每個字段;
2.1.3 將查詢的結果導出到 HDFS 上:
hive (default)> insert overwrite directory '/opt/module/data/dept'
> row format delimited fields terminated by '\t' select * from dept;
【即】不使用local
就可以將數據導出到 HDFS 上;
2.2 Hadoop 命令導出到本地:
dfs -get /user/hive/warehouse/student/month=2019-08/000000_0 /opt/module/datas/export/student3.txt
2.3 Hive Shell 導出:
使用hive -e/-f "命令" > file_name
:
bin/hive -e 'select * from default.student' > /opt/module/datas/export/student4.txt
2.4 export 導出到 HDFS 上:
hive (default)> export table haha to '/opt/module/data/haha/txt';
【注意】導出來的數據在 HDFS 上;
2.5 sqoop 導出:
後續會有專題;
三、 數據刪除:
數據的刪除使用 truncate
:
hive (default)> truncate table haha;
【注】truncate 只能刪除管理表的數據, 不能刪除外部表的數據; 因爲 Hive 不具備刪除外部表數據的能力;