这次的Hbase实验,老师让做使用Java API实现Hbase的表的扫描。
咱也不清楚扫描是咋实现的,只能去网上搜搜看。
看了几篇博客,发现大家都是使用了Scan这个类。
使用方法大致就是先给Scan设置一个前闭后开区间。
然后将用需要扫描的表设置一下该Scan,获取一个迭代器。
然后一行行的迭代输出。
我一上来是这样设置的
Scan scan=new Scan("row1".getBytes(),"row9".getBytes());
这样设置后,由于该区间是前闭后开的,最后输出的结果不会含有row9的数据。可是我需要输出全部的数据。
去网上搜也没什么结果,然后我在Linux上查询的时候设置StopRow为空的时候就发现可以输出全部的结果。
然后我在Java中这样设置后,也能输出全部的结果了。
Scan scan=new Scan("row1".getBytes(),"".getBytes());
这里贴一下代码
package hbase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import java.io.IOException;
import java.util.Iterator;
public class HbaseScan {
public static void scan() throws IOException {
//连接Hbase数据库
Configuration conf=new Configuration();
conf.set("hbase.zookeeper.quorum", "centos01:2181,centos02:2181,centos03:2181");
Connection connection = ConnectionFactory.createConnection(conf);
//读取表
Table mytable = connection.getTable(TableName.valueOf("table1"));
//设置区间
Scan scan=new Scan("row1".getBytes(),"".getBytes());
//区间扫描
//scan.setStartRow("row1".getBytes());
//scan.setStopRow("".getBytes());
ResultScanner scanner = mytable.getScanner(scan);
//result 是与一行数据(有多个列族,多个列)
Iterator iterator = scanner.iterator();
System.out.println();
while(iterator.hasNext()){
Result result = iterator.next();
//获取结果 返回的是cell 用cellutils将其变为字节数组 然后再转为string
//格式化输出
String name = new String(CellUtil.clonevalue(result.getColumnLatestCell("familyName1".getBytes(), "name".getBytes())));
String address = new String(CellUtil.clonevalue(result.getColumnLatestCell("familyName1".getBytes(), "address".getBytes())));
String age = new String(CellUtil.clonevalue(result.getColumnLatestCell("familyName1".getBytes(), "age".getBytes())));
System.out.println(name+", "+age+", "+address);
}
//关闭连接
connection.close();
}
public static void main(String[] args) throws IOException{
scan();
}
}
需要做的事还有很多



