Using a Secondary Index to Read Data
Prerequisites
This function is available only in MRS 1.7 or later version.
Function Description
In a user table with HIndexes, HBase uses a filter to query data.
Sample Code
The following code snippets are in the scanDataByHIndex method in the HIndexExample class of the com.huawei.bigdata.hbase.examples packet.
public void scanDataByHIndex() {
LOG.info("Entering HIndex-based Query.");
Table table = null;
ResultScanner rScanner = null;
try {
table = conn.getTable(tableName);
// Create a filter for indexed column.
// For MRS 2.0.0 or later, replace CompareOp with CompareOperator.
SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes("info"), Bytes.toBytes("age"),
CompareOp.GREATER_OR_EQUAL, Bytes.toBytes("26"));
filter.setFilterIfMissing(true);
Scan scan = new Scan();
scan.setFilter(filter);
rScanner = table.getScanner(scan);
// Scan the data
LOG.info("Scan data using indices..");
for (Result result : rScanner) {
LOG.info("Scanned row is:");
for (Cell cell : result.rawCells()) {
LOG.info(Bytes.toString(CellUtil.cloneRow(cell)) + ":" + Bytes.toString(CellUtil.cloneFamily(cell)) + ","
+ Bytes.toString(CellUtil.cloneQualifier(cell)) + "," + Bytes.toString(CellUtil.cloneValue(cell)));
}
}
LOG.info("Successfully scanned data using indices for table " + tableName + ".");
} catch (IOException e) {
LOG.error("Failed to scan data using indices for table " + tableName + "." + e);
} finally {
if (rScanner != null) {
rScanner.close();
}
if (table != null) {
try {
table.close();
} catch (IOException e) {
LOG.error("failed to close table, ", e);
}
}
}
LOG.info("Entering HIndex-based Query.");
} Last Article: Querying a List of Secondary Indexes
Next Article: Deleting a Secondary Index
Did this article solve your problem?
Thank you for your score!Your feedback would help us improve the website.