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

20 篇文章 0 订阅
10 篇文章 0 订阅

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

1.py腳本

傳入參數:

target_database:數據庫
target_table:表
target_columns:列
target_positions:hive列的下標(從0開始)

# coding=utf-8
import json
import getopt
import os
import sys
import MySQLdb

# MySQL相关配置,需根据实际情况作出修改
mysql_host = "hadoop102"
mysql_port = "3306"
mysql_user = "root"
mysql_passwd = "xx"

# 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, target_columns):
    return map(lambda x: x[0], get_mysql_meta(database, table, target_columns))


def get_hive_columns(database, table, target_columns, target_positions):
    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, target_columns)

    if target_columns == 'all':
        return map(lambda x: {"name": x[0], "type": type_mapping(x[1].lower())}, meta)
    else:
        positions = list(map(int, target_positions.split(',')))
        return map(lambda x, i: {"index": positions[i], "type": type_mapping(x[1].lower())}, meta, range(len(meta)))


def generate_json(target_database, target_table, target_columns, target_positions):
    print(get_hive_columns(target_database, target_table, target_columns, target_positions))
    if target_columns == 'all':
        target_columns_hive = "[*]"
    else:
        target_columns_hive = get_hive_columns(target_database, target_table, target_columns, target_positions)
    job = {
        "job": {
            "setting": {
                "speed": {
                    "channel": 15
                },
                "errorLimit": {
                    "record": 0,
                    "percentage": 0.02
                }
            },
            "content": [{
                "reader": {
                    "name": "hdfsreader",
                    "batchSize": "8192",
                    "batchByteSize": "33554432",
                    "parameter": {
                        "path": "${exportdir}",
                        "defaultFS": "hdfs://" + hdfs_nn_host + ":" + hdfs_nn_port,
                        "column": target_columns_hive,
                        "fileType": "orc",
                        "encoding": "UTF-8",
                        "fieldDelimiter": u"\u0001",
                        "nullFormat": "\\N"
                    }
                },
                "writer": {
                    "name": "mysqlwriter",
                    "batchSize": "8192",
                    "batchByteSize": "33554432",
                    "parameter": {
                        "writeMode": "replace",
                        "username": mysql_user,
                        "password": mysql_passwd,
                        "column": get_mysql_columns(target_database, target_table, target_columns),
                        "connection": [
                            {
                                "jdbcUrl":
                                    "jdbc:mysql://" + mysql_host + ":" + mysql_port + "/" + target_database + "?useUnicode=true&characterEncoding=utf-8&useSSL=false",
                                "table": [target_table]
                            }
                        ]
                    }
                }
            }]
        }
}

    output_path = "/opt/module/datax/job/export/" + target_database
    if not os.path.exists(output_path):
        os.makedirs(output_path)
    with open(os.path.join(output_path, ".".join([target_database, target_table, "json"])), "w") as f:
        json.dump(job, f)


def main(args):
    target_database = ""
    target_table = ""
    target_columns = ""  # 默认为 None,表示没有指定列信息
    target_positions = ""

    options, arguments = getopt.getopt(args, 'p:d:t:c:', ['positions=', 'targetdb=', 'targettbl=', 'columns='])
    for opt_name, opt_value in options:
        if opt_name in ('-d', '--targetdb'):
            target_database = opt_value
        if opt_name in ('-t', '--targettbl'):
            target_table = opt_value
        if opt_name in ('-c', '--columns'):
            target_columns = opt_value
        if opt_name in ('-p', '--positions'):
            target_positions = opt_value
    print(target_database, target_table, target_columns, target_positions)
    generate_json(target_database, target_table, target_columns, target_positions)


if __name__ == '__main__':
    main(sys.argv[1:])

2.sh腳本

#!/bin/bash
python ~/bin/test.py -d db-t table -c all
#kunnr,name1,sort2,addrnumber,country,state -p 0,1,2,3,4,5
#all


  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
DataX 是阿里巴巴集团开源的一款数据同步工具,它支持多种数据源之间的同步,包括 HiveMySQL、Oracle 等常见关系型数据库以及 HDFS、FTP 等非关系型数据源。下面介绍如何使用 DataXHiveMySQL 中的表互导。 首先需要在本地和远程服务器上安装好 DataX。然后创建一个名为 job.json 的配置文件,内容如下: ``` { "job": { "content": [ { "reader": { "name": "hdfswriter", "parameter": { "path": "/user/hive/warehouse/myhive.db/myhive_table", "defaultFS": "hdfs://localhost:9000", "fileType": "orc", "column": [ "col1", "col2", "col3" ] } }, "writer": { "name": "mysqlwriter", "parameter": { "url": "jdbc:mysql://localhost:3306/test", "username": "root", "password": "123456", "table": "mysql_table", "column": [ "col1", "col2", "col3" ] } } } ], "setting": { "speed": { "channel": "3" } } } } ``` 该配置文件定义了一个数据同步任务,将 Hive 中的 myhive_table 表导入到 MySQL 中的 mysql_table 表中。其中,hdfswriter 和 mysqlwriter 分别表示数据源和目标源的类型,parameter 参数中定义了数据源和目标源的详细信息。column 参数定义了需要同步的。 执行以下命令启动 DataX 任务: ``` python datax.py job.json ``` 该命令会按照配置文件中的定义开始数据同步任务。在数据量较大的情况下,可以通过修改 job.json 中的 speed 参数来调整数据同步的速度,以避免对源和目标服务器的负载过大。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_37759590

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值