title: Python 读写 hbase 数据的正确姿势(一)
tags:
hbase
happybase
python
categories:
�Hbase
comments: true
date: 2017-09-09 19:00:00
之前操作 hbase 大都是用 java 写,或者偶尔用 python 写几个一些简单的 put、get 操作。最近在使用 happybase 库批量向 hbase 导入数据,并通过 java 实现查询的一些复杂的搜索时(scan+filter),遇到了一些有趣的问题。
实验版本
Hbase 版本:1.0.0
Happybase 版本:1.1.0
Python 版本:2.7.13
问题1:filter 过滤失败
问题重现
hbase 的使用场景大概是这样的:
有一个 hbase table,存储一些文章的基本信息,包括创建时间、文章ID、文章类别ID等,同属于一个column family,"article"。
查询的场景则是查找"指定的时间范围","文章类型ID为N" 的所有文章数据。
根据以上场景,设计如下 table:
hbase table 为 article 。
rowkey 是 "ARTICLE" + 微秒级时间戳(类似OpenTSDB 的rowkey,便于按时间序列查到某一段时间创建的 articles),即 "ARTICLE1504939752000000"。
family 为 "basic",包含 "ArticleID", "ArticleTypeID", "Created", 三个 column。
查询时通过指定 rowkey start 和 rowkey stop,可以 scan 某一个时间段的数据(因为 rowkey 中包含数值型的时间戳),通过 hbase filter 实现"ArticleTypeID" == N 的过滤条件。
开始导入数据、准备查询,以下是导入数据部分代码 demo:
def save_batch_events(datas, table=None):
with get_connetion_pool().connection() as conn:
if table is not None:
t = conn.table(table)
else:
t = conn.table(TABLE)
b = t.batch(transaction=False)
for row, data in datas.items():
b.put(row, data)
b.send()
def save_main_v1():
datas = dict()
for i in range(100):
article_type_id = i % 2
timestamp = time.time() + i<