使用scala调用Hbase API
1:查看表是否存在
def isTableExist(table: String): Boolean = {
val conf: Configuration = HBaseConfiguration.create
conf.set("hbase.zookeeper.quorum", "192.168.56.101,192.168.56.102,192.168.56.103")
conf.set("hbase.zookeeper.property.clientPort", "2181")
val admin: HBaseAdmin = new HBaseAdmin(conf)
val bool = admin.tableExists(table)
admin.close()
bool
}
2:根据表名,获取所有数据
val conf: Configuration = HBaseConfiguration.create
conf.set("hbase.zookeeper.quorum", "192.168.56.101,192.168.56.102,192.168.56.103")
conf.set("hbase.zookeeper.property.clientPort", "2181")
val table: HTable = new HTable(conf, tableName)
val scan: Scan = new Scan()
val scanner = table.getScanner(scan)
var flag = true
while (flag) {
val result = scanner.next()
try {
val cells: Array[Cell] = result.rawCells()
cells.foreach(cell => {
println("行键:" + Bytes.toString(CellUtil.cloneRow(cell)))
println("列族:" + Bytes.toString(CellUtil.cloneFamily(cell)))
println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)))
println("值:" + Bytes.toString(CellUtil.cloneValue(cell)))
})
} catch {
case e: NullPointerException => flag = false
}
}
}
3:根据表名,rowkey获取 1:此rowkey下的所有数据 2:获取指定列族下的所有数据 3:某一指定列族下的某一个列的数据
def getRowQualifier(tableName: String, rowKey: String, family: String, qualifier1: String): Unit = {
val conf: Configuration = HBaseConfiguration.create
conf.set("hbase.zookeeper.quorum", "192.168.56.101,192.168.56.102,192.168.56.103")
conf.set("hbase.zookeeper.property.clientPort", "2181")
val table: HTable = new HTable(conf, tableName)
// 如果不使用addColumn或者addFamily,那就是获取此rowkey下的所有列的数据
val get = new Get(Bytes.toBytes(rowKey))
// 如果使用addColumn,添加列族和列,则此列的数据
//get.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier1))
// 如果使用addFamily,添加列族,则此列族下的所有数据
//get.addFamily(Bytes.toBytes(family))
val result = table.get(get)
result.rawCells().foreach(cell=>{
println("行键:" + Bytes.toString(result.getRow()))
println("列族" + Bytes.toString(CellUtil.cloneFamily(cell)))
println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)))
println("值:" + Bytes.toString(CellUtil.cloneValue(cell)))
})
table.close()
}