Hive(二)DML数据操作语言

DML数据操作

一、数据导入

1、向表中装载数据

hive> load data [local] inpath '路径' [overwrite] into table 表名 [partition (partcol1=val1,…)];

(1)load data:表示加载数据
(2)local:表示从本地加载数据到hive表;否则从HDFS加载数据到hive表
(3)inpath:表示加载数据的路径
(4)overwrite:表示覆盖表中已有数据,否则表示追加
(5)into table:表示加载到哪张表
(6)表名:表示具体的表
(7)partition:表示上传到指定分区
2、通过查询语句向表中插入数据
(1)基本插入

insert into table  student partition(month='201709') values(1,'wangwu');
insert overwrite table student partition(month='201708') select id, name from student where month='201709';
  • 从student表中选择所有month分区为2017年9月的记录的id和name字段,然后将这些数据插入到(或覆盖)month分区为2017年8月的student表分区中。

(2)多插入

from dept_partition
              insert overwrite table dept_partition partition(month='201707')
              select deptno,dname,loc where month='201709'
              insert overwrite table dept_partition partition(month='201706')
              select deptno,dname,loc  where month='201709';

(3)查询语句中创建表并加载数据
根据查询结果创建表,查询的结果会添加到新创建的表中

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

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

  • 指定在HDFS上的位置
create table if not exists student5(
id int, name string)
row format delimited fields terminated by '\t'
location '/user/hive/warehouse/student5';
  • 上传数据到HDFS
dfs -put /opt/datas/student.txt /opt/hive/warehouse/student5;

(5)将数据导入到指定Hive表中
先用export导出后,再讲数据导入

import table student2 partition(month='201709') from '/opt/hive/warehouse/export/student';

从HDFS上的/opt/hive/warehouse/export/student目录中,导入数据到Hive表student2的month='201709'分区。

2、数据导出
(1)insert导出

  • 将查询的结果导出到本地
insert overwrite local directory '/opt/datas' select * from dept_partition;
  • 将查询的结果格式化导出到本地
insert overwrite local directory '/opt/datas/dept1'
row format delimited
fields terminated by '|'
select * from dept_partition;
  • 将查询的结果导出到HDFS上
insert overwrite directory '/opt/datas/dept'
row format delimited
fields terminated by '|'
select * from dept_partition;

(2)Hadoop命令导出到本地

dfs -get /opt/hive/warehouse/employee/employee.txt /opt/datas/dept2/dept.txt;
  • 源文件路径:/opt/hive/warehouse/employee/employee.txt
  • 目标路径:/opt/datas/dept2/dept.txt

(3)Hive Shell命令导出

  • 基本语法:hive -f/-e 执行语句或者脚本 > file
hive -e 'select * from hivetest.dept_partition;' > /opt/datas/dept3/dept.txt;

在shell窗口执行,需要库名.表名,需要本地文件夹存在

(4)export导出到HDFS上

export table hivetest.dept_partition to '/opt/datas/dept2';

3、清除表中数据

truncate table student;

只能删除管理表,不能删除外部表中的数据

posted @ 2024-09-02 14:36  一年都在冬眠  阅读(33)  评论(0)    收藏  举报