Tuesday, 26 November 2013

Communicate with a single HBase table

Sample Code to read record from Hbase Table

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.client.coprocessor.AggregationClient;
import org.apache.hadoop.hbase.util.Bytes;

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

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

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

    private List<String> getlistOfRowKeys(String tableName) throws IOException {
        HTableInterface table = new HTable(configuration,tableName);
        Scan scan = new Scan();
        ResultScanner resultScanner = table.getScanner(scan);
        List<String> rowKeyList = new ArrayList<String>();
        for(Result result: resultScanner) {
             rowKeyList.add(Bytes.toString(result.getRow()));
        }
        return rowKeyList;
    }

    public static void main(String[] args) {
        ReadRecordFromTable tableReader = new ReadRecordFromTable();
        try {
            List<String> rowKeyList = tableReader.getlistOfRowKeys("TABLE_NAME");
            System.out.println("No. Of records In Table: " + rowKeyList.size());
            for(String rowKey:rowKeyList){
                System.out.println(rowKey);
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
 


No comments:

Post a Comment