mongodb数据迁移到hbase

  • 导入包
# encoding: utf-8
'''
@author: zcc
@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
@software: pycharm
@file: ggsn_to_hbase.py
@time: 9/1/17 2:43 PM
@desc:
'''
from thrift.transport import TSocket, TTransport
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from hbase.ttypes import ColumnDescriptor, Mutation, BatchMutation, TRegionInfo
from hbase.ttypes import IOError, AlreadyExists
from hbase import Hbase
from hbase.ttypes import *
  • 操作hbase的类
import struct
def encode(n):
return struct.pack("i", n) class HbaseControl(object):
def __init__(self, table, col_name, host='192.168.1.10', port=9090):
self.table = table
self.host = host
self.port = port # Connect to HBase Thrift server
self.transport = TTransport.TBufferedTransport(TSocket.TSocket(host, port))
self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport) # Create and open the client connection
self.client = Hbase.Client(self.protocol)
self.transport.open() # set type and field of column families
self.set_column_families(col_name)
self._build_column_families() def set_column_families(self, col_list=['name', 'sex', 'age']):
'''
设置每列名称和属性
:param self:
:param type_list:
:param col_list:
:return:
'''
self.columnFamilies = col_list def _build_column_families(self):
'''
如果hbase中没有当前表,则建立
:param self:
:return:
'''
tables = self.client.getTableNames()
if self.table not in tables:
self.__create_table(self.table) def __create_table(self, table):
'''
在hbase中建表
:param self:
:param table:
:return:
'''
columnFamilies = []
for columnFamily in self.columnFamilies:
name = Hbase.ColumnDescriptor(name=columnFamily)
columnFamilies.append(name)
self.client.createTable(table, columnFamilies) def del_row(self, row_key):
'''
删除行
:param row_key:
:return:
'''
self.client.deleteAllRow(self.table, row_key, {}) def __del__(self):
'''
销毁对象前关闭hbase链接
:return:
'''
self.transport.close() def _del_table(self, table):
'''
删除hbase中的表
:param table:
:return:
'''
self.client.disableTable(table)
self.client.deleteTable(table) def getColumnDescriptors(self):
'''
获取hbase表的列簇描述
:return:
'''
return self.client.getColumnDescriptors(self.table) def put(self, record, day):
'''
向hbase中插入一条记录
:param record:
:return:
'''
assert isinstance(record, dict)
mutations = []
# tel和日期构成hbase内的行名
row_key = '{0}_{1}'.format(record['tel'], day)
# 插入tel
mutations.append(Hbase.Mutation(column='baseinfo:tel', value=str(record['tel'])))
# 插入day
mutations.append(Hbase.Mutation(column='baseinfo:day', value=str(day)))
# 插入suminfo
mutations.append(Hbase.Mutation(column='suminfo:context', value=str(record['suminfo'])))
self.client.mutateRow(self.table, row_key, mutations, {}) def puts(self, records, day):
'''
hbase批量插入
:param records:
:param day:
:return:
'''
assert isinstance(records, list) mutationsBatch = []
for record in records:
mutations = []
# tel和日期构成hbase内的行名
row_key = '{0}_{1}'.format(record['tel'], day)
# 插入tel
mutations.append(Hbase.Mutation(column='baseinfo:tel', value=str(record['tel'])))
# 插入day
mutations.append(Hbase.Mutation(column='baseinfo:day', value=str(day)))
# 插入suminfo
mutations.append(Hbase.Mutation(column='suminfo:context', value=str(record['suminfo']))) mutationsBatch.append(Hbase.BatchMutation(row=row_key, mutations=mutations))
self.client.mutateRows(self.table, mutationsBatch, {})
  • 操作mongodb且到将数据导入到hbase的类
from pymongo import MongoClient
class MongDBControl(object):
def __init__(self, table_name, host='192.168.1.20', port=27017):
self.client = MongoClient(host, port)
db = self.client.table
self.collect = db[table_name]
self.table = table_name def __del__(self):
self.client.close() def record_to_hbase(self, hc):
assert isinstance(hc, HbaseControl) num = 0 while True:
records = self.collect.find().skip(1000*num).limit(1000)
if not records: break
hc.puts(list(records), self.table)
num += 1
print '已经从mongodb向hbase导入{0}条数据!!'.format(num*1000)
print '数据迁移完毕!!!'
  • 主函数
if __name__ == '__main__':
if 1:
hc = HbaseControl(table='table', col_name=['baseinfo', 'count', 'suminfo', 'nodebll', 'nodebzl'])
mc = MongDBControl('20170806')
# mc.record_to_hbase(hc)
hc._del_table('table')

mongodb数据迁移到hbase的更多相关文章

  1. MongoDB 数据迁移和同步

    MongoDB 数据迁移和同步 MongoDB的数据同步 复制 mongodb的复制至少需要两个实例.其中一个是主节点master,负责处理客户端请求,其余的都是slave,负责从master上复制数 ...

  2. Oracle数据迁移至HBase操作记录

    Oracle数据迁移至HBase操作记录 @(HBase) 近期需要把Oracle数据库中的十几张表T级别的数据迁移至HBase中,过程中遇到了许多苦难和疑惑,在此记录一下希望能帮到一些有同样需求的兄 ...

  3. mongodb系列~mongodb数据迁移

    一 简介:今天来聊聊mongo的数据迁移二 迁移   1 具体迁移命令   nohup mongodump --port --db dbname --collection tablename --qu ...

  4. mongodb数据迁移的两种方式

    环境说明:bbs数据采集的数据越来越多,目前是50G,每天大概以200W的数据量增长.而当前服务器1.2上面的空间不足,需要把数据迁移到空间足够大的1.3上面去 尝试了2种方式对数据进行迁移,一种是r ...

  5. 亿级mongodb数据迁移

    1. 预先准备有效数据单号池,通过单号拉取数据处理 单号表默认为1 01 使用findAndModify 更新单号表状态为 2 读取单号 循环读取100 条 02 通过运单号批量查询 Aladin_W ...

  6. MongoDB 数据迁移 备份 导入(自用)

    MongoDB bin文件夹下 备份:mongodump -h IP:PORT -d 库名 -c 集合名 -o 存储路径 恢复:mongorestore -h IP:PORT -d 库名 -c 集合名 ...

  7. MongoDB数据迁移

    将集合user从192.168.1.12:27017导入到192.168.1.120:27017 数据的导出:mongoexport 数据的导入:mongoimport 导出集合user的过程: [r ...

  8. Hbase 整合 Hadoop 的数据迁移

    上篇文章说了 Hbase 的基础架构,都是比较理论的知识,最近我也一直在搞 Hbase 的数据迁移, 今天就来一篇实战型的,把最近一段时间的 Hbase 整合 Hadoop 的基础知识在梳理一遍,毕竟 ...

  9. 如何将MongoDB数据库的数据迁移到MySQL数据库中

    FAQ v2.0终于上线了,断断续续忙了有2个多月.这个项目是我实践的第一个全栈的项目,从需求(后期有产品经理介入)到架构,再到设计(有征询设计师的意见).构建(前端.后台.数据库.服务器部署),也是 ...

随机推荐

  1. 关于SQL优化的一点建议

    前段时间一直在做关于性能优化相关的工作,结合自己的实际工作经验,只针对SQL层面提一些优化的规范和建议. 针对SQL编写 1.单条SQL长度不宜超过100行: 2.SQL子查询不宜嵌套3层: 子查询嵌 ...

  2. Bytom Kit开发辅助工具介绍

    Bytom Kit是一款为了帮助开发者更简单地理解Bytom的开发辅助工具,集合了校验.标注.解码.测试水龙头等功能. 该工具用python语言封装了一套比原的API和7个工具方法,如果有开发需求可以 ...

  3. MySql中not in的优化

    最近项目上用select查询时使用到了not in来排除用不到的主键id一开始使用的sql如下: select s.SORT_ID, s.SORT_NAME, s.SORT_STATUS, s.SOR ...

  4. 3、Docker镜像管理基础

    Docker image     # docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE redis -alpine 23d561d12e92 d ...

  5. 2、Docker基础用法

    容器镜像:https://hub.docker.com/ Docker架构图:  https://ruby-china.org/topics/22004 Docker使用客户端-服务器(client- ...

  6. Java并发编程的挑战

    并发编程的目的是为了让程序运行得更快,但是,并不是线程启动的越多,就能让程序最大限度地并发执行.并发编程时,会面临非常多的挑战,比如上下文切换的问题,死锁的问题,以及受限于各种硬件和软件的资源限制问题 ...

  7. WebForm服务器验证控件与前端js自定义验证共同使用

        问题: 前端aspx页面中需要在button中添加OnClientClick事件后,这个OnClientClick所执行的自定义的客户端js验证:这个时候,所有的服务器验证控件都会失效!   ...

  8. 给web请求加遮罩动画

    效果预览: css: /*#fountainG{ position:relative; margin:10% auto; width:240px; height:29px }*/ #fountainG ...

  9. LeetCode--036--有效的数独(java)

    判断一个 9x9 的数独是否有效.只需要根据以下规则,验证已经填入的数字是否有效即可. 数字 1-9 在每一行只能出现一次. 数字 1-9 在每一列只能出现一次. 数字 1-9 在每一个以粗实线分隔的 ...

  10. 自己封装的一个类似axios的请求

    下载:https://pan.baidu.com/s/1k0-CpGGtfDTsCm85NMfuHA 使用: axios({ method:'post', baseURL:baseAddress, u ...