使用更新密钥导出Sqoop

Y.P*_*hvi 1 hadoop hdfs sqoop2

我必须将HDFS文件导出到MySql中.
假设我的HDFS文件是:

1,abcd,23
2,efgh,24
3,ijkl,25
4,mnop,26
5,qrst,27
Run Code Online (Sandbox Code Playgroud)

并说我的Mysql数据库架构是:

+-----+-----+-------------+
| ID  | AGE |    NAME     |
+-----+-----+-------------+
|     |     |             |
+-----+-----+-------------+
Run Code Online (Sandbox Code Playgroud)

当我使用以下Sqoop命令插入时:

sqoop export \
--connect jdbc:mysql://localhost/DBNAME \
--username root \
--password root \
--export-dir /input/abc \
--table test \
--fields-terminated-by "," \
--columns "id,name,age"
Run Code Online (Sandbox Code Playgroud)

它工作正常并插入数据库.

但是,当我需要更新已经存在的记录时,我必须使用--update-key--columns.

现在,当我尝试使用以下命令更新表时:

sqoop export \
--connect jdbc:mysql://localhost/DBNAME \
--username root \
--password root \
--export-dir /input/abc \
--table test \
--fields-terminated-by "," \
--columns "id,name,age" \
--update-key id
Run Code Online (Sandbox Code Playgroud)

我面临的问题是数据没有更新到列中的指定 --columns

我做错了吗?

我们不能这样更新数据库吗?HDFS文件应该只在Mysql架构中更新?

有没有其他方法来实现这一目标?

小智 9

4b.将HDFS中的数据更新到关系数据库中的表中

在mysql test db中创建emp表tbl

create table emp
(
id int not null primary key,
name varchar(50)
);
Run Code Online (Sandbox Code Playgroud)

vi emp - >创建包含以下内容的文件

1,Thiru
2,Vikram
3,Brij
4,Sugesh
Run Code Online (Sandbox Code Playgroud)

将文件移动到hdfs

hadoop fs -put emp <dir>
Run Code Online (Sandbox Code Playgroud)

执行以下sqoop作业将数据导出到mysql

sqoop export --connect <jdbc connection> \
--username sqoop \
--password sqoop \
--table emp \
--export-dir <dir> \
--input-fields-terminated-by ',';
Run Code Online (Sandbox Code Playgroud)

验证mysql表中的数据

mysql> select * from emp;

+----+--------+
| id | name   |
+----+--------+
|  1 | Thiru  |
|  2 | Vikram |
|  3 | Brij   |
|  4 | Sugesh |
+----+--------+
Run Code Online (Sandbox Code Playgroud)

更新emp文件并将更新的文件移动到hdfs.更新文件的内容

1,Thiru
2,Vikram
3,Sugesh
4,Brij
5,Sagar
Run Code Online (Sandbox Code Playgroud)

用于upsert的Sqoop导出 - 如果密钥与其他插入匹配则更新.

sqoop export --connect <jdbc connection> \
--username sqoop \
--password sqoop \
--table emp \
--update-mode allowinsert \
--update-key id \
--export-dir <dir> \
--input-fields-terminated-by ',';

Note: --update-mode <mode> - we can pass two arguments "updateonly" - to update the records. this will update the records if the update key matches.
if you want to do upsert (If exists UPDATE else INSERT) then use "allowinsert" mode.
example: 
--update-mode updateonly \ --> for updates
--update-mode allowinsert \ --> for upsert
Run Code Online (Sandbox Code Playgroud)

验证结果:

mysql> select * from emp;
+----+--------+
| id | name   |
+----+--------+
|  1 | Thiru  |
|  2 | Vikram |
|  3 | Sugesh |--> Previous value "Brij"
|  4 | Brij   |--> Previous value "Sugesh"
|  5 | Sagar  |--> new value inserted
+----+--------+
Run Code Online (Sandbox Code Playgroud)