HBase 协处理器实践(一)
对数据表中的数据进行求和。
1、添加coprocessor AggregateImplementation分为添加全局和为单表添加Aggregation。
a、 添加全局AggregateImplementation,方法:修改hbase-site.xml文件,在该文件中添加
<span style="font-size:18px;"><property>
<name>hbase.coprocessor.user.region.classes</name>
<value>org.apache.hadoop.hbase.coprocessor.AggregateImplementation</value>
</property></span>
b、添加单表的AggregateImplementation,可以通过hbase shell实现也可以通过Java API
hbase shell
<span style="font-size:18px;">disable 'table'
alter 'table',METHOD => 'table_att','coprocessor' => 'hdfs://ip:9000/user/hadoop/jars/test.
jar|mycoprocessor.SampleCoprocessor|1001|'
enable 'table'</span>
java api 通过HBaseAdmin / HTableDescriptor 来实现的
<span style="font-size:18px;"> 创建HBaseConfiguration
Configuration hbaseconfig = HBaseConfiguration.create();
通过HBaseAdmin来完成为表添加配置
HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseconfig);
hbaseAdmin.disableTable(TABLE_NAME);
通过表的描述来为表添加AggregationImplementation
HTableDescriptor htd = hbaseAdmin.getTableDescriptor(TABLE_NAME);
htd.addCoprocessor(AggregateImplementation.class.getName());
hbaseAdmin.modifyTable(TABLE_NAME, htd);
hbaseAdmin.enableTable(TABLE_NAME);
hbaseAdmin.close();</span>
在完成添加之后就是对于表数据统计,LongColumnInterpreter列解释器,解析列值,调用AggregationClient的rowCount方法,t对于表数据的行统计的大小完全是取决于创建的Scan,可以是针对单个列族、单个列、范围查询。
<span style="font-size:18px;">public static void testAggregationClient()
throws Throwable {
HTable hTable = new HTable(config, TableName.valueOf("marketing"));
/**
* ColumnInterperter类型的参数ci。即列解释器,用于解析列中的值。
*/
LongColumnInterpreter columnInterpreter = new LongColumnInterpreter();
AggregationClient aggregationClient = new AggregationClient(config);
Scan scan = new Scan();
// 统计范围内的数据
// scan.setStopRow("rk007".getBytes());
// 统计单列族
scan.addFamily(Bytes.toBytes("f"));
// 统计单列族的列
// scan.addColumn(Bytes.toBytes("f"), Bytes.toBytes("q"));
Long count = aggregationClient.rowCount(hTable, columnInterpreter, scan);
System.out.println("count..." + count);
}</span>
这里的范围统计,只指定结束的rowKey,默认startRowkey从第一条开始。还有一些求平均值,最大值的方法注意数据类型。