基本知識:
Sqoop導出的基本用法:https://sqoop.apache.org/docs/1.4.6/SqoopUserGuide.html#_syntax_4 的10. sqoop-export
内容摘要:
本文主要是對--update-mode參數的用法進行了驗證。結論如下:
--update-mode模式有兩種updateonly(預設)和allowinsert
updateonly:該模式用于更新Hive表與目标表中資料的不一緻,即在不一緻時,将Hive中的資料同步給目标表(如MySQL、Oracle等的目标表中),這種不一緻是指,一條記錄中的不一緻,比如Hive表和MySQL中都有一個id=1的記錄,但是其中一個字段的取值不同,則該模式會将這種差異抹除。對于“你有我無”的記錄則“置之不理”。
allowinsert:該模式用于将Hive中有但目标表中無的記錄同步到目标表中,但同時也會同步不一緻的記錄。可以這種模式可以包含updateony模式的操作,這也是為什麼沒有命名為insertonly的原因吧。
測試場景一:全量導出
1. 準備原始資料:
為簡化處理,先在MySQL中建立原始資料表wht_test1,并添加測試資料,如下所示:
2. 将原始表中的資料導入到Hive中。
sqoop import --connectjdbc:mysql://localhost:3306/wht --username root --password cloudera --tablewht_test1 --fields-terminated-by ',' --hive-import --hive-table default.wht_test1 --hive-overwrite -m 1
執行完該操作後,導入的資料在HDFS的/user/hive/warehouse/wht_test1目錄下。
3. 建立導出表。
在MySQL中建立結構相同的表,用于導出資料:
CREATE TABLEwht_test2 LIKE wht_test1;
4. 從Hive(HDFS)導出資料。
sqoop export --connectjdbc:mysql://localhost:3306/wht --username root --password cloudera --tablewht_test2 --fields-terminated-by ',' --export-dir /user/hive/warehouse/wht_test1
執行完該操作後,MySQL的wht_test2表中插入了Hive中的資料,如下所示:
測試場景二:增量導出,在源資料中增加2條記錄,檢視不同模式導出結果
1. 編輯HDFS中的資料檔案,添加兩行新的記錄,編輯後的檔案内容如下所示:
Ø updateonly模式:
sqoop export --connectjdbc:mysql://localhost:3306/wht --username root --password cloudera --tablewht_test2 --fields-terminated-by ',' --update-key c_id --export-dir /user/hive/warehouse/wht_test1
檢視結果,可以看出Updateonly模式不能導出新增資料:
Ø allowinsert模式:
sqoop export --connectjdbc:mysql://localhost:3306/wht --username root --password cloudera --tablewht_test2 --fields-terminated-by ',' --update-key c_id --update-mode allowinsert --export-dir /user/hive/warehouse/wht_test1
檢視結果,新增資料被導出:
測試場景三:修改Hive表資料,修改age的值,并新增一行記錄,然後重新導出,看目标表中的資料是否會被修改
1. 編輯HDFS中的資料檔案,編輯後的檔案内容如下所示:
sqoop export --connectjdbc:mysql://localhost:3306/wht --username root --password cloudera --tablewht_test2 --fields-terminated-by ',' --update-key c_id --update-mode updateonly --export-dir/user/hive/warehouse/wht_test1
檢視結果,Hive表中修改的資料被更新,但updateonly模式不會導出新插入的記錄:
測試場景三:allowinsert模式(導出不同HDFS源檔案中的新增資料)
Hive表可能有多個分區,在此新增一個目錄,并儲存結構相同的資料,使用allowinsert模式檢視導出結果。
新增資料目錄wht_test1_part,該目錄下的資料檔案如下所示:
執行導出指令:sqoop export --connect jdbc:mysql://localhost:3306/wht --usernameroot --password cloudera --table wht_test2 --fields-terminated-by ',' --update-key c_id --update-mode allowinsert --export-dir/user/hive/warehouse/wht_test1_part
檢視導出結果,可以看出新增資料被導出:
————————————————
版權聲明:本文為部落客「汀桦塢」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。