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. 为input标签绑定事件的几种方式

    为input标签绑定事件的几种方式 1.JavaScript原生态的方式,直接复制下面的代码就会有相应的效果 <!DOCTYPE html><html><head> ...

  2. 爬虫中xpath的特殊用法

    Xpath之starts-with(@属性名称,属性字符串相同部分) 以相同的字符开头的用法 在做爬虫时解析html的源码时候可能会遇见以下这种标签, <div id="test-1& ...

  3. Java基础语法(二)之流程控制语句

    流程控制语句是用来控制程序中各语句执行顺序的语句,可以把语句组合成能完成一定功能的小逻辑模块 .控制语句分为三类:顺序,选择和循环. “顺序结构”代表”先执行a,再执行b”的逻辑.比如,先找个女朋友, ...

  4. 论文阅读:Siam-RPN

    摘要 Siam-RPN提出了一种基于RPN的孪生网络结构.由孪生子网络和RPN网络组成,它抛弃了传统的多尺度测试和在线跟踪,从而使得跟踪速度非常快.在VOT实时跟踪挑战上达到了最好的效果,速度最高16 ...

  5. 面试被问之-----sql优化中in与exists的区别

    曾经一次去面试,被问及in与exists的区别,记得当时是这么回答的:''in后面接子查询或者(xx,xx,xx,,,),exists后面需要一个true或者false的结果",当然这么说也 ...

  6. Python三大神器:装饰器,迭代器,生成器

    一.装饰器 由于一个函数能实现一种功能,现在想要在不改变其代码的情况下,让这个函数进化一下,即能保持原来的功能,还能有新的"技能",怎么办? 现已经存在一个自定义的函数func1, ...

  7. 【python 3】 文件操作

    文件操作 一: 只读.读写 # 示例: 1 f = open("E:\人员名单.txt" , encoding="utf-8" , mode="r&q ...

  8. java中==和equals的区别(转)

    java中的数据类型,可分为两类: 1.基本数据类型,也称原始数据类型.byte,short,char,int,long,float,double,boolean   他们之间的比较,应用双等号(== ...

  9. 在CentOS6.9上Shell脚本定时释放内存cache

    一.写Shell脚本 mkdir -p /var/script/ vim /var/script/freemem.sh 写入以下Shell脚本: #!/bin/bash # 当前已使用的内存大小 us ...

  10. 第 10 章 容器监控 - 081 - Weave Scope 多主机监控

    除了监控容器,Weave Scope 还可以监控 Docker Host 点击顶部 HOSTS 菜单项,地图将显示当前 host. 与容器类似,点击该 host 图标将显示详细信息 host 当前的资 ...