數據集成平台:datax將MySQL數據同步到hive(全部列和指定列)

1.數據集成平台:將MySQL數據同步到hive(全部和指定列)

  1. python環境:2.7版本
  2. py腳本
    傳參:

source_database:數據庫

source_table:表

source_columns:列

source_splitPk:split key,要求必須是int類型

bash 复制代码
# coding=utf-8
import json
import getopt
import os
import sys
import MySQLdb

#MySQL相关配置,需根据实际情况作出修改
mysql_host = "47.57.227.5"
mysql_port = "3306"
mysql_user = "vinson_readonly"
mysql_passwd = "8AGY5Eqq8Ac8VR7b"

#HDFS NameNode相关配置,需根据实际情况作出修改
hdfs_nn_host = "mycluster"
hdfs_nn_port = "8020"

#生成配置文件的目标路径,可根据实际情况作出修改
def get_connection():
    return MySQLdb.connect(host=mysql_host, port=int(mysql_port), user=mysql_user, passwd=mysql_passwd)


def get_mysql_meta(database, table, columns):
    connection = get_connection()
    cursor = connection.cursor()
    if columns == 'all':
        # 如果传入 '*' 表示要所有列
        sql = "SELECT COLUMN_NAME, DATA_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' ORDER BY ORDINAL_POSITION" % (database, table)
    else:
        # 传入指定列
        # 将每个列名加上单引号
        columns = ', '.join("'%s'" % col.strip() for col in columns.split(','))
        sql = "SELECT COLUMN_NAME, DATA_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' AND COLUMN_NAME IN (%s) ORDER BY ORDINAL_POSITION" % (
        database, table, columns)
    cursor.execute(sql)
    fetchall = cursor.fetchall()
    # print(fetchall)
    cursor.close()
    connection.close()
    return fetchall


def get_mysql_columns(database, table,source_columns):
    return map(lambda x: x[0], get_mysql_meta(database,table,source_columns))


def get_hive_columns(database, table,source_columns):
    def type_mapping(mysql_type):
        mappings = {
            "bigint": "bigint",
            "int": "bigint",
            "smallint": "bigint",
            "tinyint": "bigint",
            "mediumint": "bigint",
            "decimal": "string",
            "double": "double",
            "float": "float",
            "binary": "string",
            "char": "string",
            "varchar": "string",
            "datetime": "string",
            "time": "string",
            "timestamp": "string",
            "date": "string",
            "text": "string",
            "bit": "string",
        }
        return mappings[mysql_type]

    meta = get_mysql_meta(database, table,source_columns)
    return map(lambda x: {"name": x[0], "type": type_mapping(x[1].lower())}, meta)


def generate_json(source_database, source_table,source_columns,source_splitPk):
    job = {
        "job": {
            "setting": {
                "speed": {
                      "channel": 15
                    },
                "errorLimit": {
                    "record": 0,
                    "percentage": 0.02
                }
            },
            "content": [{
                "reader": {
                    "name": "mysqlreader",
                    "batchSize":"8192",
                    "batchByteSize":"33554432",
                    "parameter": {
                        "username": mysql_user,
                        "password": mysql_passwd,
                        "column": get_mysql_columns(source_database, source_table,source_columns),
                        "splitPk": source_splitPk,
                        "connection": [{
                           "table": [source_table],
                            "jdbcUrl": ["jdbc:mysql://" + mysql_host + ":" + mysql_port + "/" + source_database + "?userCompress=true&useCursorFetch=true&useUnicode=true&characterEncoding=utf-8&useSSL=false"]
                        }]
                    }
                },
                "writer": {
                    "name": "hdfswriter",
                     "batchSize":"8192",
                     "batchByteSize":"33554432",
                    "parameter": {
                        "defaultFS": "hdfs://" + hdfs_nn_host + ":" + hdfs_nn_port,
                        "fileType": "text",
                        "path": "${targetdir}",
                        "fileName": source_table,
                        "column": get_hive_columns(source_database, source_table,source_columns),
                        "writeMode": "append",
                        "fieldDelimiter": u"\u0001",
                        "compress": "gzip"
                    }
                },
                "transformer": [

                        {
                          "name": "dx_groovy",
                          "parameter": {
                            "code": "for(int i=0;i<record.getColumnNumber();i++){if(record.getColumn(i).getByteSize()!=0){Column column = record.getColumn(i); def str = column.asString(); def newStr=null; newStr=str.replaceAll(\"[\\r\\n]\",\"\"); record.setColumn(i, new StringColumn(newStr)); };};return record;",
                            "extraPackage":[]
                          }
                        }
                      ]
            }]
        }
    }
    output_path = "/opt/module/datax/job/import/" + source_database

    if not os.path.exists(output_path):
        os.makedirs(output_path)
    with open(os.path.join(output_path, ".".join([source_database, source_table, "json"])), "w") as f:
        json.dump(job, f)


def main(args):
    source_database = ""
    source_table = ""
    source_columns = ""
    source_splitPk = ""

    options, arguments = getopt.getopt(args, 'd:t:c:k:', ['sourcedb=', 'sourcetbl=', 'columns=', 'splitPk='])
    for opt_name, opt_value in options:
        if opt_name in ('-d', '--sourcedb'):
            source_database = opt_value
        if opt_name in ('-t', '--sourcetbl'):
            source_table = opt_value
        if opt_name in ('-c', '--columns'):
            source_columns = opt_value
        if opt_name in ('-k', '--splitPk'):
            source_splitPk = opt_value
    generate_json(source_database, source_table,source_columns,source_splitPk)

if __name__ == '__main__':
    main(sys.argv[1:])
  1. sh腳本
bash 复制代码
#!/bin/bash
python ~/bin/sap_gateway_gen_import_config.py -d db -t table -c Id,created_date -k selfincrementid
python ~/bin/sap_gateway_gen_import_config.py  -d db -t table  -c all -k selfincrementid
相关推荐
YJlio3 分钟前
ZoomIt 学习笔记(11.11):休息计时器与演讲节奏控制——倒计时、番茄钟与现场掌控力
数据库·笔记·学习
sc.溯琛17 分钟前
MySQL 性能优化核心:索引创建与管理实战指南
数据库·mysql·性能优化
锋君30 分钟前
Orcale数据库在Asp.Net Core环境下使用EF Core 生成实体
数据库·后端·oracle·asp.net
啊吧怪不啊吧31 分钟前
SQL之用户管理——权限与用户
大数据·数据库·sql
VX:Fegn089533 分钟前
计算机毕业设计|基于springboot + vue电影院购票管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
ZePingPingZe34 分钟前
MySQL与Spring,事务与自动提交有什么关系?
mysql·spring
q_191328469535 分钟前
基于SpringBoot2+Vue2的企业合作与活动管理平台
java·vue.js·经验分享·spring boot·笔记·mysql·计算机毕业设计
凌冰_36 分钟前
JAVA与MySQL实现银行管理系统
java·开发语言·mysql
NineData38 分钟前
NineData 数据库 DevOps 正式支持谷歌云,全面接入 GCP 数据源
运维·数据库·devops·ninedata·gcp·玖章算术·数据智能管理平台
韩立学长44 分钟前
Springboot考研自习室预约管理系统1wdeuxh6(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端