一、先创建表,初始化数据
create 's1','c1','c2'
put 's1','a','c1:name','zs'
put 's1','a','c1:age','18'
put 's1','a','c2:score','99'
put 's1','b','c1:name','jack'
put 's1','b','c1:age','21'
put 's1','b','c2:score','85'
put 's1','c','c1:name','tom'
put 's1','c','c1:age','31'
put 's1','c','c2:score','79'
put 's1','d','c1:name','lili'
put 's1','d','c1:age','27'
put 's1','d','c2:score','65'
put 's1','e','c1:name','ww'
put 's1','e','c1:age','35'
put 's1','e','c2:score','100'
put 's1','f','c1:name','jessic'
put 's1','f','c1:age','12'
put 's1','f','c2:score','77'
二、代码如下:
package com.imooc.hbase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.*;
import org.apache.hadoop.hbase.util.Bytes;
import java.util.List;
/**
* 全表扫描Scan+Filter
*
* 注意:首先需要创建表s1,然后初始化一批数据
*
*/
public class HBaseScanFilter {
public static void main(String[] args) throws Exception{
//获取配置
Configuration conf = HBaseConfiguration.create();
//指定HBase使用的zk的地址,多个都逗号隔开
conf.set("hbase.zookeeper.quorum", "bigdata01:2181,bigdata02:2181,bigdata03:2181");
//指定HBase在hdfs上的根目录
conf.set("hbase.rootdir","hdfs://bigdata01:9000/hbase");
//创建HBase连接,负责对HBase中数据的增删改查(DML操作)
Connection conn = ConnectionFactory.createConnection(conf);
//获取Table对象,指定要操作的表名,表需要提前创建好
Table table = conn.getTable(TableName.valueOf("s1"));
Scan scan = new Scan();
//范围查询:指定查询区间,提高查询性能
//这是一个左闭右开的区间,也就是查询的结果中包含左边的,不包含右边的
scan.withStartRow(Bytes.toBytes("a"));
scan.withStopRow(Bytes.toBytes("f"));
//添加Filter对数据进行过滤:使用RowFilter进行过滤,获取Rowkey小于等于d的数据
Filter filter = new RowFilter(CompareOperator.LESS_OR_EQUAL,new BinaryComparator(Bytes.toBytes("d")));
scan.setFilter(filter);
//获取查询结果
ResultScanner scanner = table.getScanner(scan);
//迭代查询结果
for (Result result: scanner) {
List<Cell> cells = result.listCells();
//RowKey
byte[] row_key = result.getRow();
for (Cell cell: cells) {
//注意:下面获取的信息都是字节类型的,可以通过new String(bytes)转为字符串
//列族
byte[] famaily_bytes = CellUtil.cloneFamily(cell);
//列
byte[] column_bytes = CellUtil.cloneQualifier(cell);
//值
byte[] value_bytes = CellUtil.cloneValue(cell);
System.out.println("Rowkey:"+new String(row_key)+",列族:"+new String(famaily_bytes)+",列:"+new String(column_bytes)+",值:"+new String(value_bytes));
}
System.out.println("================================================================");
}
//关闭连接
table.close();
conn.close();
}
}