This tutorial will give you a quick overview of how to search for data using HBASE. If you have not done so yet. Follow the following two tutorials on HBASE: Connecting and HBASE: Create a Table.
Search for Data:
Basically we have to scan the table for data. So we must first setup a scan object then search for the data.
- import org.apache.hadoop.hbase.client.Result;
- import org.apache.hadoop.hbase.client.ResultScanner;
- import org.apache.hadoop.hbase.client.Scan;
- import org.apache.hadoop.hbase.Cell;
- import org.apache.hadoop.hbase.client.Table;
- import org.apache.hadoop.hbase.TableName;
- import org.apache.hadoop.hbase.util.Bytes;
- //Lets setup our scan object.
- final Scan scan = new Scan();
- //Search a particular column
- scan.addColumn(Bytes.toBytes("columnFamily"), Bytes.toBytes("columnName"));
- //Check the row key prefix
- scan.setRowPrefixFilter(Bytes.toBytes("rowkey"));
- final TableName table = TableName.valueOf(yourTableName);
- //Get the table you want to work with. using the connection from the tutorial above.
- final Table table = conn.getTable(table);
- //Create our scanner based on the scan object above.
- final ResultScanner scanner = table.getScanner(scan);
- //Now we will loop through our results
- for (Result result = scanner.next(); result != null; result = scanner.next()) {
- //Lets get our row key
- final String rowIdentifier = Bytes.toString(result.getRow());
- //Now based on each record found we will loop through the available cells for that record.
- for (final Cell cell : result.listCells()) {
- //now we can do whatever we need to with the data.
- log.info("column {} value {}", Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()), Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
- }
- }
One thought on “HBASE & Java: Search for Data”
Comments are closed.