Wednesday, 27 November 2013

Read Records (that begins with some value) using RowFilter from given HBase Table

ReadRecordWithRowFilter

package filter;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.apache.hadoop.hbase.filter.SubstringComparator;
import org.apache.hadoop.hbase.util.Bytes;

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

/**
 * Created with IntelliJ IDEA.
 * User: Hadoop Share
 * Date: 27/11/13
 * Time: 6:07 PM
 * To change this template use File | Settings | File Templates.
 */
public class ReadRecordWithRowFilter {
    private static Configuration configuration = HBaseConfiguration.create();

    static{
        configuration.set("hbase.zookeeper.quorum","localhost");
        configuration.set("hbase.zookeeper.property.clientPort","2181");
    }

    List<String> getRowKeysBeginningWith(String tableName,String rowKeyBeginsWith) throws IOException {
        List<String> rowKeyList = new ArrayList<String>();
        HTableInterface table = new HTable(configuration,tableName);
        Scan scan = new Scan();
        RowFilter rowFilter = new RowFilter(CompareFilter.CompareOp.EQUAL,new SubstringComparator(rowKeyBeginsWith));
        scan.setFilter(rowFilter);
        ResultScanner resultScanner =  table.getScanner(scan);
        for(Result result:resultScanner){
            rowKeyList.add(Bytes.toString(result.getRow()));
        }
        return rowKeyList;
    }

    public static void main(String[] args) {
        ReadRecordWithRowFilter filterReader = new ReadRecordWithRowFilter();
        try {
            List<String> rowKeyList = filterReader.getRowKeysBeginningWith("TABLE_NAME","20131022:");
            System.out.println("TotalNoOfRows:" + rowKeyList.size());
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}

No comments:

Post a Comment