批量查询Hbase 传入一个rowkey List 返回一个嵌套 HashMap<String, HashMap<String, String>>
public static HashMap<String, HashMap<String, String>> queryTableBatch(String tableName,List<String> rowkeyList) throws IOException {
Connection connection = ConnectionFactory.createConnection(conf);
List<Get> getList = new ArrayList();
HashMap<String, HashMap<String, String>> resultMap = new HashMap();
Table table = connection.getTable(TableName.valueOf(tableName));// 获取表
for (String rowkey : rowkeyList) {//把rowkey加到get里,再把get装到list中
Get get = new Get(Bytes.toBytes(rowkey));
getList.add(get);
}
Result[] results = table.get(getList);
// System.out.println("results.length"+results.length);
for (Result result : results) {
System.out.println(result.rawCells().length);
if(result.rawCells().length>0){
String rowkey=Bytes.toString(result.getRow());
HashMap<String, String> map = new HashMap();
for (Cell kv : result.rawCells()) {
String value = Bytes.toString(CellUtil.cloneValue(kv));
map.put(Bytes.toString(CellUtil.cloneQualifier(kv)),value);
}
resultMap.put(rowkey,map);
}
}
table.close();
return resultMap;
}
根据嵌套HashMap 批量写入Hbase
public static void writeTable(String tableName, HashMap<String, HashMap<String, String>> inputMap) {
try {
Connection connection = ConnectionFactory.createConnection(conf);
Table table = connection.getTable(TableName.valueOf(tableName));
List<Put> list = new ArrayList();
for (String rowkey : inputMap.keySet()) {
Put put = new Put(Bytes.toBytes(rowkey));
for (Map.Entry<String, String> entry : inputMap.get(rowkey).entrySet()) {
put.addColumn(Bytes.toBytes("cf1"), Bytes.toBytes(entry.getKey()), Bytes.toBytes(entry.getValue()));
}
if (!put.isEmpty()) {
list.add(put);
}
}
table.put(list);
table.close();
} catch (IOException e) {
e.printStackTrace();
}
}
测试
public static void main(String[] args) throws IOException {
List<String> list2 = new ArrayList<String>();
list2.add("1001");
list2.add("1002");
HashMap<String, HashMap<String, String>> a = queryTableTestBatch(list2);
System.out.println(a);
for (String i : a.keySet()){
System.out.println(i);
Set<Map.Entry<String, String>> entries = a.get(i).entrySet();
System.out.println(entries);
}
//结果:{1002={sex=female, name=Janna, age=20}, 1001={sex=male, age=18}}
}