一、导入数据
create_namespace 'exam' create 'exam:mytest','info' hdfs dfs -put /opt/data/quizz/UserBehaviorTestHbase.csv /quizz/data hbase org.apache.hadoop.hbase.mapreduce.ImportTsv -Dimporttsv.separator="," -Dimporttsv.columns="HBASE_ROW_KEY,info:stuid,info:proid,info:level,info:score" exam:mytest /quizz/data/UserBehaviorTestHbase.csv
二、pom依赖导入
<dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>1.2.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-common --> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-common</artifactId> <version>1.2.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-server --> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-server</artifactId> <version>1.2.0</version> </dependency>
三、代码操作
使用到工厂模式创建Connection连接,见 https://www.cnblogs.com/sabertobih/p/14001250.html
1)配置
//构建配置文件对象 Configuration conf = HBaseConfiguration.create(); //设置zookeeper端口 conf.set("hbase.zookeeper.property.clientPort","2181"); //设置zookeeper host conf.set("hbase.zookeeper.quorum","192.168.56.111"); //设置hbase hmaster入口 conf.set("hbase.master","192.168.56.111:60000");
2)创建表对象
//创建数据库连接对象 ConnectionBuilder<Connection> build = ConnectionFactory.getConnectionBuilder(DatabaseType.HBASE); Connection conn = build.getConnection(); //根据表名查找表 Table tab = conn.getTable(TableName.valueOf("exam2:mt1"));
3)put命令添加一行ROWKEY
//构建put命令对象并设置rowkey Put put = new Put("3".getBytes()); //按照列族 修饰符 顺序填充一个列族的数据put.addColumn("info".getBytes(),"username".getBytes(),"ww".getBytes()); //put命令执行 tab.put(put);
4)get命令获得行数据
//设置一个get Get get = new Get("1".getBytes()); //通过table直接获得该行数据 Result result = tab.get(get); //通过列族和修饰符找到对应的值 String name = Bytes.toString(result.getValue("info".getBytes(), "username".getBytes())); System.out.println(name);
5)设置scan,此处使用Filter过滤数据
//设置一个scan SingleColumnValueFilter scvf = new SingleColumnValueFilter( "info".getBytes(),"username".getBytes(), CompareFilter.CompareOp.EQUAL, "ww".getBytes()); Scan scan = new Scan(); scan.setFilter(scvf); ResultScanner rs = tab.getScanner(scan); for (Result r : rs) { System.out.println(Bytes.toString(r.getRow())+":"+ Bytes.toString(r.getValue("info".getBytes(),"username".getBytes()))); }