背景
現有的數據迴流方案中,爲避免數據重複,有一些前置操作(delete/truncate)。在迴流之前執行這些操作會對查詢造成一些瞬時影響。
針對這種場景我們需要做一些優化(update or insert)。
適用場景
- 準實時項目迴流(數據迴流頻繁)
- 數據累加型計算
- 無需刪除之前計算結果
要求
數據加工表中包含唯一業務字段。
實現方式
原迴流方式
#刪除目標表當天數據,避免重複迴流
delete_sql="truncate table $target_table;"
echo "delete_sql=$delete_sql"
sqoop eval --connect jdbc:mysql://$HOSTNAME:$PORT/$DBNAME --username $username --password $password -e "$delete_sql" &&
#導出到MYSQL
sqoop export --connect jdbc:mysql://$HOSTNAME:$PORT/$DBNAME?tinyInt1isBit=false --username $username --password $password --table $target_table --fields-terminated-by '\001' --input-null-string '\\N' --input-null-non-string '\\N' --export-dir $hdfs_temp_dir &&
改造後
#導出到MYSQL
sqoop export -Dsqoop.export.records.per.statement=1 -Dsqoop.export.statements.per.transaction=1 \
--connect jdbc:mysql://$HOSTNAME:$PORT/$DBNAME?tinyInt1isBit=false \
--username $username --password $password --table $target_table -m 1 --fields-terminated-by '\001' --input-null-string '\\N' \
--input-null-non-string '\\N' --export-dir $hdfs_temp_dir --update-key server_id --update-mode allowinsert &&
參數說明:
--update-key:設置更新唯一字段,可以設置多個,用逗號隔開
--update-mode:allowinsert允許插入
注:key需要添加唯一索引 ,如果是多個字段,添加組合唯一索引。
ps: 解決批量更新死鎖問題,每個事務操作一條記錄。
sqoop.export.records.per.statement=1
sqoop.export.statements.per.transaction=1
Caused by: java.sql.BatchUpdateException: Deadlock found when trying to get lock; try restarting transaction