168大数据

标题: 用sqoop将mysql的数据导入到hive表中的方法 [打印本页]

作者: 168主编    时间: 2018-8-24 15:33
标题: 用sqoop将mysql的数据导入到hive表中的方法
本帖最后由 168主编 于 2018-8-24 15:40 编辑

1、mysql的表结构如下:

[AppleScript] 纯文本查看 复制代码
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `stu_no` varchar(16) DEFAULT NULL,
  `name` varchar(64) DEFAULT NULL,
  `age` int(11) DEFAULT '0',
  `birthday` date DEFAULT NULL,
  `create_time` date DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `index_stu_no` (`stu_no`),
  KEY `index_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


2、需求1:把student表100条记录的id,stu_no,name,create_time字段导入hive(备注,如果是导入表的几个字段,不能使用需求2的方式直接导入导表中,使用第三种方式有可能会成功,但是仅限于表字段排序对应上了,如果没有对应上,会出现null或错误的列)

(1)在HDFS创建导出数据的目录

[AppleScript] 纯文本查看 复制代码
su hdfs
hadoop fs -mkdir /mysql
hadoop fs -chmod -R 777 /mysql


(2)使用query导出数据到HDFS目录下

[AppleScript] 纯文本查看 复制代码
sqoop import \
--connect jdbc:mysql://master60:3306/test \
--username root \
--password 123456 \
--query 'select id,stu_no,name,create_time from student where $CONDITIONS LIMIT 100' \
--target-dir /mysql/test/student \
--delete-target-dir \
--num-mappers 1 \
--compress \
--compression-codec org.apache.hadoop.io.compress.SnappyCodec \
--fields-terminated-by '\t'

(3)在Hive中创建表结构

[AppleScript] 纯文本查看 复制代码
drop table if exists default.student ;
create table default.student (
id int,
stu_no int,
name string,
create_time date
)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' ;


(4)把导出的数据导入Hive中

load data inpath '/mysql/test/student' into table default.student;

3、需求2,把student表所有字段导入hive

(1)创建表结构,按mysql的表字段排序

[AppleScript] 纯文本查看 复制代码
drop table if exists default.student ;
create table default.student (
id int,
stu_no int,
name string,
age int,
birthday date,
create_time date
)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' ;


(2)导入表数据到Hive

[AppleScript] 纯文本查看 复制代码
sqoop import \
--connect jdbc:mysql://master60:3306/test \
--username root \
--password 123456 \
--table student \
--fields-terminated-by '\t' \
--delete-target-dir \
--num-mappers 1 \
--hive-import \
--hive-database default \
--hive-table student







欢迎光临 168大数据 (http://www.bi168.cn/) Powered by Discuz! X3.2