HBase java get scan 例子

maven依赖

<dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-client</artifactId>
    <version>0.98.24-hadoop2</version>
</dependency>

代码

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HConnectionManager;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;

public class App {
	
	private static Configuration hbaseconfig = null;
	static {
		Configuration conf = new Configuration();
		conf.set("hbase.zookeeper.quorum", "127.0.0.1");
		conf.set("hbase.zookeeper.property.clientPort", "2181");

		hbaseconfig = HBaseConfiguration.create(conf);
	}

	/***
	 * 根据主键rowKey查询一行数据 get 'student','010'
	 * 
	 * @throws IOException
	 */
	public static Map<String,String> getOneRecordByRowKey(String tableName, String rowkey) throws IOException {
		Map<String,String> dataMap = new HashMap<>();
		HConnection hconn = null;
		hconn = HConnectionManager.createConnection(hbaseconfig);
		HTableInterface hTable = null;
		hTable = hconn.getTable(tableName);
		Get get = new Get(rowkey.getBytes()); // 根据主键查询
		Result r = hTable.get(get);
		for (Cell cell : r.rawCells()) {
			dataMap.put(Bytes.toString(CellUtil.cloneQualifier(cell)), Bytes.toString(CellUtil.cloneValue(cell)));
		}
		return dataMap;
	}
	
	/**
	 *  scan 一个表
	 * @param tableName
	 * @param startRow 
	 * @param stopRow
	 * @return
	 * @throws IOException
	 */
	public static 	List<Map<String,String>>   scanRecords(String tableName, String startRow,String stopRow) throws IOException {
		List<Map<String,String>> datas = new ArrayList<>();
		HConnection hconn = null;
		hconn = HConnectionManager.createConnection(hbaseconfig);
		HTableInterface hTable = null;
		hTable = hconn.getTable(tableName);
		Scan scan = new Scan(startRow.getBytes(), stopRow.getBytes());
		ResultScanner rs = hTable.getScanner(scan);
		for(Result r:rs) {
			//String rowKey =Bytes.toString( r.getRow());
			Map<String,String> dataMap = new HashMap<>();
			for (Cell cell : r.rawCells()) {
				dataMap.put(Bytes.toString(CellUtil.cloneQualifier(cell)), Bytes.toString(CellUtil.cloneValue(cell)));
			}
			datas.add(dataMap);
		}
		return datas;
	}
	


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值