Hbase API 笔记



目前在学习hbase ,此博客主要用来记录hbase 学习笔记

hbase 提供了丰富的API,非常方便。


  • 连接hbase 
    HBaseAdmin admin;
	HTable htable;
	String TN = "person";

	public void init() throws Exception {
		Configuration conf = new Configuration();
		conf.set("hbase.zookeeper.quorum", "localhost");
		admin = new HBaseAdmin(conf);
		htable = new HTable(conf, TN.getBytes());
	}

  • 创建表

        // 表描述
		HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(TN));
		HColumnDescriptor cf = new HColumnDescriptor("cf".getBytes());
		desc.addFamily(cf);
		admin.createTable(desc);

  • 插入数据
        String rowKey = "rowkey3";
		Put put = new Put(rowKey.getBytes());
		put.add("cf".getBytes(), "name".getBytes(), "xiaohua3".getBytes());
		put.add("cf".getBytes(), "age".getBytes(), "35".getBytes());
		put.add("cf".getBytes(), "sex".getBytes(), "women".getBytes());
		htable.put(put);

  • 批量插入
String rowKey = "rowkey3";
List<Put> puts= new ArrayList<Put>();
		for(int i=10;i<100;i++) {
			rowKey ="rowkey"+i;
			Put put = new Put(rowKey.getBytes());
			String name ="name "+i;
			put.add("cf".getBytes(), "name".getBytes(), name.getBytes());
			put.add("cf".getBytes(), "age".getBytes(), "35".getBytes());
			put.add("cf".getBytes(), "sex".getBytes(), "women".getBytes());
			puts.add(put);
		}
		
htable.put(puts);

  • 查询单个数据
        String rowKey = "rowkey1";
		Get get = new Get(rowKey.getBytes());
		get.addColumn("cf".getBytes(), "name".getBytes());
		get.addColumn("cf".getBytes(), "age".getBytes());
		get.addColumn("cf".getBytes(), "sex".getBytes());
		Result rs = htable.get(get);
		Cell cell = rs.getColumnLatestCell("cf".getBytes(), "name".getBytes());
		Cell cell2 = rs.getColumnLatestCell("cf".getBytes(), "age".getBytes());
		Cell cell3 = rs.getColumnLatestCell("cf".getBytes(), "sex".getBytes());
		System.out.println(new String(CellUtil.cloneValue(cell)));
		System.out.println(new String(CellUtil.cloneValue(cell2)));
		System.out.println(new String(CellUtil.cloneValue(cell3)));

  • 删除
Delete delete = new Delete("rowkey2".getBytes());
htable.delete(delete);

猜你喜欢

转载自blog.csdn.net/qq_28059559/article/details/86131375