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. Matlab 将两个图像进行分离 已知其中一个图像

    5.下图(a)是一幅两个灰度图像合成的图像,已知其中一幅图像如图(b)所示,试把另一幅图像提取出来,并显示. 运用减法做 %加载入要处理的图片 A=imread('a.png'); %将I变为[0,1 ...

  2. Bootstrap3基础 下载bootstrap3压缩包和相应的jQuery文件

      内容 参数   OS   Windows 10 x64   browser   Firefox 65.0.2   framework     Bootstrap 3.3.7   editor    ...

  3. UVA1030 Image Is Everything

    思路 如果两个面看到颜色不同,则这个正方体一定要被删掉 然后依次考虑每个面即可 注意坐标的映射 代码 #include <cstdio> #include <algorithm> ...

  4. (转)How Transformers Work --- The Neural Network used by Open AI and DeepMind

    How Transformers Work --- The Neural Network used by Open AI and DeepMind Original English Version l ...

  5. Java语言之循环基础;各个语句的区别

    FOR: WHILE DO WHILE break 与 continue的区别 break直接中断语句跳出循环,continue跳出当前循环,后面会继续执行

  6. abap 常用 function

    ABAP常用函数总结  alv .smartform. excel .text.邮件 .远程访问,FTP服务器...  **********常用功能function REUSE_ALV_GRID_DI ...

  7. 技巧 筛1~n的所有因子

    从 i : 1~n, 是i的倍数, 则计入该数 复杂度 n*(1/1+1/2+1/3+...1/n)=nlogn ll d[N]; // 计每个数的因子数 set<ll> s[N]; // ...

  8. 显示等待 (web自动化测试)

    from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from sel ...

  9. Project D | Digital life

    I have a dream. 1999年黑客帝国就已经提出了数字化生命的雏形,近些年的黑镜和其他科幻电影更是脑洞大开,但是生命科学的进展却差强人意. 当今人类世界里有三大复杂系统:以细胞为基础的生命 ...

  10. SSM框架完成Ajax简单用户登录验证

    一.前端JSP <%@ page contentType="text/html;charset=UTF-8" language="java" %> ...