Hive之DML操作

DML 数据操作

1. 数据导入

1.1 向表中Load数据

  1. 语法
    load data [local] inpath '数据的 path' [overwrite] 
    into table student  [partition (partcol1=val1,)];
    
    • load data: 表示加载数据
    • local: 表示从本地加载数据到 hive 表;否则从 HDFS 加载数据到 hive
    • inpath: 表示加载数据的路径
    • overwrite: 表示覆盖表中已有数据,否则表示追加
    • into table: 表示加载到哪张表
    • student: 表示具体的表
    • partition: 表示上传到指定分区
  2. 案例
    • 加载本地文件到 hive
      // 创建表
      create table if not exists student (
          id string,
          name string
      )
      row format delimited fields terminated by '\t';
      
      // 加载本地文件到hive
      load data local inpath
      '/opt/module/hive-3.1.2/datas/student.txt' into table student;
      
    • 加载 HDFS 上的数据到hive
      // 加载HDFS文件到hive (会将hdfs加载路径的文件 移动 到hive在hdfs的工作目录下 /user/hive/warehouse/table_name)
      load data inpath
      '/student/student.txt' into table student;
      

1.2 向表中Insert数据

  1. 创建一张表
    create table if not exists student2 (
        id string,
        name string
    )
    row format delimited fields terminated by '\t';
    
  2. 插入数据
    • insert into: 以追加数据的方式插入到表或分区,原有数据不会删除
    • insert overwrite: 会覆盖表中已存在的数据
    • insert 不支持插入部分字段,会进行MR
    // 插入数据 (mr)
    insert into table student2
    values ('1', 'wangwu'), ('2', 'zhaoliu');
    
    // 根据单张表查询结果插入
    insert overwrite table student2
    select id, name
    from student;
    

1.3 根据查询结果As Select到表中

// 根据查询结果创建表
create table if not exists student3
as select id, name from student2;

1.4 创建表时通过 Location 指定加载数据路径

  1. 上传数据到 hdfs
    dfs -put /opt/module/hive-3.1.2/datas/student.txt /student;
    
  2. 创建表,并指定在 hdfs 上的位置
    create table if not exists student4 (
        id int,
        name string
    )
    row format delimited fields terminated by '\t'
    location '/student';
    

1.5 Import 数据到表中

注意:先用 export 导出后,再将数据导入

// import数据到指定hive表中
import table student5
from '/user/hive/warehouse/export/student';

2. 数据导出

2.1 Insert 导出

  1. 将查询的结果导出到本地

    insert overwrite local directory
    '/opt/module/hive-3.1.2/datas/export/student'
    select * from student;
    
  2. 将查询的结果格式化导出到本地

    insert overwrite local directory
    '/opt/module/hive-3.1.2/datas/export/student1'
    row format delimited fields terminated by '\t'
    select * from student;
    
  3. 将查询的结果导出到HDFS

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

2.2 Export 导出到 HDFS

export table student
to '/user/hive/warehouse/export/student';

exportimport 主要用于两个 Hadoop 平台集群之间 Hive 表迁移

3. 清除表中数据

truncate table student;

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值