您的位置:首页 > 编程语言 > Java开发

HBase 使用 Java Api 实现对数据的增删改查

2016-06-20 16:47 736 查看

1、初始化

public class HbaseDemo {

private Configuration conf = null;

// 初始化
@Before
public void init() {
conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum",
"hadoop-master:2181,hadoop-slave1:2181,hadoop-slave2:2181");
}
}

2、创建名为person的表

// 创建表
    @Test
    public void testCreate() throws Exception {
        HBaseAdmin admin = new HBaseAdmin(conf);
        // 判断表是否存在,若存在则先删除,再重新创建
        boolean b = admin.tableExists(Bytes.toBytes("person"));
        if (b) {
            admin.disableTable(Bytes.toBytes("person"));
            admin.deleteTable("person");
        }

        TableName name = TableName.valueOf("person");
        HTableDescriptor table = new HTableDescriptor(name);

        // 添加2个列族
        HColumnDescriptor base_info = new HColumnDescriptor("base_info");
        HColumnDescriptor extar_info = new HColumnDescriptor("extra_info");

        base_info.setMaxVersions(5);

        table.addFamily(base_info);
        table.addFamily(extar_info);
        admin.createTable(table);
    }
结果:
hbase(main):009:0> list
TABLE
person
yu
2 row(s) in 0.0190 seconds

=> ["person", "yu"]
hbase(main):010:0>

3、删除person表

// 删除表
@Test
public void testDrop() throws Exception {
HBaseAdmin admin = new HBaseAdmin(conf);
admin.disableTable("person");
admin.deleteTable("person");
admin.close();

}
结果
hbase(main):006:0> list
TABLE
yu
1 row(s) in 0.0090 seconds

=> ["yu"]

再此创建person表

4、向person表中添加数据

// 向表中添加数据
@Test
public void testPut() throws Exception {
HTable table = new HTable(conf, "person");
Put p = new Put(Bytes.toBytes("rk_0002"));
p.add("base_info".getBytes(), "name".getBytes(), "zhangsan".getBytes());
table.put(p);
table.close();
}
结果:
hbase(main):008:0> scan 'person'
ROW                   COLUMN+CELL
rk_0002              column=base_info:name, timestamp=1466412335931, value=zhangsan
1 row(s) in 0.0520 seconds
再向表中添加rowkey为rk_0001 name=zhaoyi,age=23,score=98的数据

运行后:

hbase(main):014:0> scan 'person'
ROW                   COLUMN+CELL
rk_0001              column=base_info:age, timestamp=1466414657818, value=23
rk_0001              column=base_info:name, timestamp=1466414632795, value=zhaoyi
rk_0001              column=base_info:score, timestamp=1466414670768, value=89
rk_0002              column=base_info:name, timestamp=1466414617620, value=zhangsan
2 row(s) in 0.0330 seconds


5、取出表中数据:

// 根据rowkey取表中数据
    @Test
    public void testGet() throws Exception {
        HTable table = new HTable(conf, "person");
        Get get = new Get(Bytes.toBytes("rk_0001"));
        get.setMaxVersions(5);
        Result result = table.get(get);

        // 1) result.getValue(family, qualifier); 可以从result中直接取出一个特定的value

        /*
         * //2) 遍历出result中所有的键值对 for (KeyValue kv : result.list()) {
         * String family = new String(kv.getFamily());
         * System.out.println("列族: " + family);
         * String qualifier = new String(kv.getQualifier());
         * System.out.println("列: " + qualifier);
         * System.out.println("值:" + new String(kv.getValue()));
         * System.out.println("---------------------------------"); }
         */
        /*
         * // 3)用cell遍历result中所有的键值对
*for (Cell cell : result.rawCells()) {
         * System.out.println("Family is :" + new String(cell.getFamily()) +
         * " \t " + "Qualifier is :" + new String(cell.getQualifier()) + "\t" +
         * "Value is :" + new String(cell.getValue())); }
         */
        // 4)新版本的Cell遍历
        //可以使用new String()转换为String,也可以使用Bytes.toString来转换
        for (Cell cell : result.rawCells()) {
            System.out.println("RowKey is :"
                    + new String(CellUtil.cloneRow(cell)) + "\t Family is :"
                    + new String(CellUtil.cloneFamily(cell))
                    + "\t Qualifier is :"
                    + new String(CellUtil.cloneQualifier(cell))
                    + "\t Value is :"
                    + Bytes.toString(CellUtil.cloneValue(cell)));
        }
    }
控制台输出为:
log4j:WARN No appenders could be found for logger (org.apache.hadoop.security.Groups).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
RowKey is :rk_0001     Family is :base_info     Qualifier is :age     Value is :23
RowKey is :rk_0001     Family is :base_info     Qualifier is :name     Value is :zhaoyi
RowKey is :rk_0001     Family is :base_info     Qualifier is :score     Value is :89


(方法4的输出结果)

6、删除表中的指定数据

// 删除rk_0001、列族为base_info中的score数据
@Test
public void testDel() throws Exception {
HTable table = new HTable(conf, "person");
Delete delete = new Delete(Bytes.toBytes("rk_0001"));
delete.deleteColumn(Bytes.toBytes("base_info"), Bytes.toBytes("score"));
table.delete(delete);
table.close();
}
结果:
hbase(main):027:0> scan 'person'
ROW                    COLUMN+CELL
rk_0001               column=base_info:age, timestamp=1466418788607, value=23
rk_0001               column=base_info:name, timestamp=1466418767594, value=zhaoyi
rk_0002               column=base_info:name, timestamp=1466418435955, value=zhangsan
2 row(s) in 0.0210 seconds
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息