HBase QualifierFilter Java Example

最近在学习如何使用客户端查询HBase,而很多网上的代码都比较旧,例如HTable已经被弃用,新版是Table. 所以我在整合了fatkun和官方文档以后,写下了一个自己的例子。我在代码中添加了一个读取行数的上限,一个兼容多过滤器的FilterList类。这个Java代码等同于HBase shell中的语句:
scan 'personal-cloud-test', {FILTER => "QualifierFilter(=, 'binary:temperature')", LIMIT => 10}

package com.mincong-h.hbase;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.PageFilter;
import org.apache.hadoop.hbase.filter.QualifierFilter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.util.Bytes;

public class GetExample {

    /**
     * 部分代码来自hbase项目官方说明和fatkun的博客
     * http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/package-summary.html
     * http://ju.outofmemory.cn/entry/17434
     * 
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        Configuration config = HBaseConfiguration.create();
        config.set("hbbase.zookeeper.quorum", "localhost");
        Connection connection = ConnectionFactory.createConnection(config);
        try {
            Table table = connection.getTable(TableName.valueOf("personal-cloud-test"));
            Scan scan = new Scan();
            FilterList filters = new FilterList();
            Filter qualifierFilter = new QualifierFilter(
                        CompareFilter.CompareOp.EQUAL, 
                        new BinaryComparator(Bytes.toBytes("temperature")));
            Filter pageFilter = new PageFilter(10);
            filters.addFilter(qualifierFilter);
            filters.addFilter(pageFilter);
            scan.setFilter(filters);
            ResultScanner resultScanner = table.getScanner(scan);
            try {
                for (Result r : resultScanner) System.out.println(r);
            } finally {
                if (resultScanner != null) resultScanner.close();
                if (table != null) table.close();
            }
        } finally {
            connection.close();
        }
    }
}

与系统有关的一些相关信息:

OS: Mac OS X Yosemite 10.10.4
Hadoop: 2.7.1
HBase: 1.0.1.1
ZooKeeper: 3.4.6

你可能感兴趣的:(hbase,hadoop)