HBase 协处理器实现二级索引

HBase在0.92之后引入了coprocessors,提供了一系列的钩子,让我们能够轻易实现访问控制和二级索引的特性。下面简单介绍下两种coprocessors,第一种是Observers,它实际类似于触发器,第二种是Endpoint,它类似与存储过程。由于这里只用到了Observers,所以只介绍Observers,想要更详细的介绍请查阅(https://blogs.apache.org/hbase/entry/coprocessor_introduction)。observers分为三种:

RegionObserver:提供数据操作事件钩子;

WALObserver:提供WAL(write ahead log)相关操作事件钩子;

MasterObserver:提供DDL操作事件钩子。

相关接口请参阅hbase api。

下面给出一个例子,该例子使用RegionObserver实现在写主表之前将索引数据先写到另外一个表:

代码不换行代码换行
package com.dengchuanhua.testhbase;

import java.io.IOException;
 import java.util.Iterator;
 import java.util.List;

import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.hbase.KeyValue;
 import org.apache.hadoop.hbase.client.HTable;
 import org.apache.hadoop.hbase.client.Put;
 import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
 import org.apache.hadoop.hbase.coprocessor.ObserverContext;
 import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;

public class TestCoprocessor extends BaseRegionObserver {

@Override
 public void prePut(final ObserverContext<RegionCoprocessorEnvironment> e,
 final Put put, final WALEdit edit, final boolean writeToWAL)
 throws IOException {
 //set configuration
 Configuration conf = new Configuration();
 //need conf.set...

HTable table = new HTable(conf, "indexTableName");
 List<KeyValue> kv = put.get("familyName".getBytes(), "columnName".getBytes());
 Iterator<KeyValue> kvItor = kv.iterator();
 while (kvItor.hasNext()) {
 KeyValue tmp = kvItor.next();
 Put indexPut = new Put(tmp.getValue());
 indexPut.add("familyName".getBytes(), "columnName".getBytes(), tmp.getRow());
 table.put(indexPut);
 }
 table.close();
 }

}

写完后要加载到table里面去,先把该文件打包成test.jar并上传到hdfs的/demo路径下,然后操作如下:

1. disable ‘testTable’

2. alter ‘testTable’, METHOD=>’table_att’,’coprocessor’=>’hdfs:///demo/test.jar|com.dengchuanhua.testhbase.TestCoprocessor|1001′

3. enable ‘testTable’

然后往testTable里面插数据就会自动往indexTableName写数据了。

总结:本文主要介绍了一个用coprocessor实现二级索引的例子。

转载于:https://www.cnblogs.com/cl1024cl/p/6205167.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值