1. 程式人生 > 實用技巧 >Hive(四)【DML 資料匯入匯出】

Hive(四)【DML 資料匯入匯出】

目錄

一.資料匯入

1.1 【load】--向資料中裝載資料

load data [local] inpath '資料的路徑' [overwrite] into table 表名 [partition('屬性'='值',...)];
--load data:表示載入資料
--local:從本地載入資料到hive表;否則從hdfs上載入資料到hive表
--inpath:待載入資料的路徑
--overwrite:覆蓋表已有資料;否則追加
--into 表名:載入到那張表
--partition:載入進指定分割槽
案例

1.載入本地檔案到hive表

load data local inpath '/opt/moudle/hive/datas/student.txt' into table student;

2.載入hdfs檔案到hive表

load data inpath '/user/student.txt' into table student;

3.載入hdfs資料且覆蓋student表中資料

load data inpath '/user/student2.txt' overwrite into table student;

1.2 【insert】--查詢語句向表中插入資料

insert into/overwrite table 表名 
select id,name from student where id<1006;
--into:追加
--overwrite:覆寫

注意:insert不支援插入部分欄位,並且後邊跟select語句時,select之前不能加as,加了as會報錯,一定要跟建立表的as select區分開

案例

1.基本模式插入幾條資料

insert into table student values(1004,'張三'),(1005,'王五');

2.根據查詢結果插入資料,覆蓋原資料

insert overwrite table student2 select id,name from student where id < 1006;

1.3 【as select】--查詢語句中建立表且載入資料

案例
create table if not exists 表2 as select id,name from 表1; 

1.4 【location】--建立表指定location載入資料

案例
create table if not exists 表名(
欄位1 型別,
欄位2 型別,
...
)
row format delimited fields terminated by '\t'
location '/student';

1.5 【import】--import資料到Hive中

案例
import table 表名 from '/user/hive/warehouse/export/student';

注意:必須是通過export匯出的資料,才能通過import匯入。因為export匯出的資料包含元資料,要求import匯入的表不能存在;

1.6 【sqoop】--工具匯入

二.資料匯出

1.1【insert】--insert匯出

案例

1.將查詢結果格式化匯出到本地

insert overwrite local directory '/opt/module/hive/datas/export/student'
row format delimited fields terminated by '\t'
select * from student;

2.將查詢結果匯出到hdfs(沒有local)

insert overwrite directory'/user/student2'
row format delimited fields terminated by '\t'
select * from student2;

注意注意注意!:insert匯出的目錄hive會自動建立,所以匯出目錄要寫不存在的目錄,否則overwrite很容易誤刪資料

1.2【hadoop fs -get】--hadoop命令匯出

案例

1.先查看錶資訊

desc formatted 表名;

2.根據表資訊找到表在hdfs資料的儲存位置,再下載到本地

hadoop fs -get 'hdfs資料儲存路徑'  '本地路徑';
hadoop fs -get '/user/hive/warehouse/student/student.txt' '/opt/export/student.txt';

1.3【hive的shell命令】

在指令碼可以通過此方式匯出資料到檔案

案例

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

bin/hive -e 'select*from student;' > /opt/module/hive/data/export/student4.txt

1.4【export】--export匯出到hdfs

案例
export table default.student to '/user/hive/warehouse/export/student';

1.5【sqoop】--工具匯出