This article: using Springboot to integrate HBase, based on the Hbasejavaapi two-time package, you can directly refer to the jar package use, currently testing has supported the HBase1.1.2 and HBase1.4.6 two versions. The following is how the project is used, and also describes the basic use of HBASEJAVAAPI.
Project Address: Code Cloud: Gitee.com/yao_qi/hbasecomponent
HBase component Interface Documentation Basic concepts
Table: Tables
Columnfamily: Column family, there can be more than one column family under a table, but it is not recommended to set multiple column families, HBase recommends designing a long narrow table instead of a short width type.
Qualifier: Columns, a column family can have more than one column, a column in a table can be misaligned, but this is not efficient, the columns in the same table are best the same.
Cell: A column of data under a cell, a column can have more than one cell, according to the version number, by default each time the latest version of the data read, the storage under the cell is the data itself.
Row: Rows, multi-column data consists of one row, and multiple qualifier in a row.
RowKey: Line Jian, used to uniquely identify a row of data, a row of more than one column, the design of the line is directly related to the efficiency of the query.
HBase Configuration
The following configuration is the most basic configuration, indispensable.
HBase: conf: quorum: 192.168.80.234:2181,192.168.80.235:2181,192.168.80.241:2181 znodeParent: /hbase-unsecure #如果有更多配置,写在config下,例如: #config: # key: value # key: value
If more configuration is needed, it needs to be configured in config and written in key-value form.
Parameter description
Quorum is the zookeeper configuration in HBase, Znodeparent is the path to hbase configuration in zookeeper.
Simple example
Introduce the component Jar package:
<dependency> <groupId>com.semptian.hbase.component</groupId> <artifactId>hbase-component</artifactId> <version>1.0.1-SNAPSHOT</version> </dependency>
Inject the Hbaseoperations interface where needed, the implementation class of the interface is Hbasetemplate, which operates hbase through this class.
@Autowired private HBaseOperations hBaseDao;
Query a piece of data through Rowkey query:
public void testQueryTable() { Result result = hBaseDao.queryByTableNameAndRowKey( "LBS", 9223372036854775803L); System.out.println(result.isEmpty()); result.listCells().forEach(cell -> { System.out.println( "row:" + Bytes.toLong(CellUtil.cloneRow(cell)) + ",family:"+ Bytes.toString(CellUtil.cloneFamily(cell)) + ", qualifier: " + Bytes.toString(CellUtil.cloneQualifier(cell)) + ", value:" + Bytes.toString(CellUtil.cloneValue(cell))); }); }
Basic operation of Table new table
Creating a table can be done with hbasetemplate, with this method in the Hbasetemplate class.
Examples of operations:
hBaseDao.createTable("HBASE-COMPONENT_1", "CF1", "CF2");
The above code creates a table, Hbase-component_1 is the table name, and CF1,CF2 represents the table with two column families.
If more than one column family can be added later, the column families are not recommended to set a number of.
Delete a table
hBaseDao.dropTable("HBASE-COMPONENT_1");
The parameter is the table name, which deletes the table from the table name.
Determine if a table exists
hBaseDao.tableExists("lbs");
The table names here are case-sensitive. Return value: Boolean.
New data adds a new piece of data
It is important to note that the stored data in HBase is unformatted and is stored as a byte array, so you need to convert the data into a byte array when storing a single piece of data.
Data in string format can be converted directly to byte array GetBytes (), but data in other formats needs to be converted using tools.
There is a need to pay extra attention to the format of the Rowkey, in what format to decide what format to take.
hBaseDao.put("HBase-component", "1534154424340", "CF1", "test_1", Bytes.toBytes("testData"));
Parameter description:
(1) tableName 目标数据表(2) rowName rowKey(3) familyName 列族名(4) qualifier 列名(5) data 字节数组类型的数据
A new piece of data here is to populate the data into a cell.
Batch new data
String rowKey = String.valueOf(System.currentTimeMillis());Put put = new Put(rowKey.getBytes());String defaultColumn = "CF1";String column1 = "col1";String column2 = "col2";String column3 = "col3";String value = "test";put.addColumn(defaultColumn.getBytes(), column1.getBytes(), value.getBytes());put.addColumn(defaultColumn.getBytes(), column2.getBytes(), value.getBytes());put.addColumn(defaultColumn.getBytes(), column3.getBytes(), value.getBytes());List<Put> putList = new ArrayList<>();putList.add(put);putList.add(put);putList.add(put);putList.add(put);putList.add(put);hBaseDao.putBatch("HBase-component", putList);
Bulk inserting data is using multiple put objects, Putbatch (...) Parameter of the method: Table name, Putlist (set of multiple put).
Note Bulk INSERT data is also data that is inserted in byte array format.
Delete data Delete one piece of data
hBaseDao.delete("HBase-component", "1534210201115", "CF1", "col2");
Parameter description:
(1) Table name
(2) RowKey
(3) Column family name
(4) Column name
Delete Here is to delete the data under a cell
Bulk Delete Data
String tableName = "HBase-component";String rowKey1 = "1534164113922";String rowKey2 = "1534168248328";List<Delete> deleteList = new ArrayList<>();Delete delete = new Delete(rowKey1.getBytes());Delete delete1 = new Delete(rowKey2.getBytes());deleteList.add(delete);deleteList.add(delete1);hBaseDao.deleteBatch(tableName, deleteList);
Delete objects are required for bulk deletion.
Query a single result query
Result result = hBaseDao.queryByTableNameAndRowKey("LBS", 9223372036854775803L); System.out.println(result.isEmpty()); result.listCells().forEach(cell -> { System.out.println( " row:" + Bytes.toLong(CellUtil.cloneRow(cell)) + " family:"+ Bytes.toString(CellUtil.cloneFamily(cell)) + " qualifier: " + Bytes.toString(CellUtil.cloneQualifier(cell)) + " value:" + Bytes.toString(CellUtil.cloneValue(cell))); });
Querybytablenameandrowkey () The method is querying data through the table name and Rowkey, where Rowkey supports multiple types, long,double,integer several types.
As for what type of parameter is passed here, it depends on the type of Rowkey when the data is inserted, although HBase stores a byte array, but is sensitive to the type, and if the type pair is not possible an error occurs.
Batch Scan
Build Scanscan scan = new scan ()//set timestamp, calculate time difference Long timedifference = 2L * 30L * 24L * 60L * 60L * 1000L; Long endTime = System.currenttimemillis (); Long FromTime = endtime-timedifference;//Set time filter filterlist filterlist = new filterlist (); Filter starttimefilter = new Singlecolumnvaluefilter (Default_column_family.getbytes (), Data_create_time.getbytes (), CompareFilter.CompareOp.GREATER, Bytes.tobytes (FromTime)); Filter endtimefilter = new Singlecolumnvaluefilter (Default_column_family.getbytes (), Data_create_time.getbytes (), CompareFilter.CompareOp.LESS, Bytes.tobytes (EndTime)); Filterlist.addfilter (Starttimefilter); Filterlist.addfilter (Endtimefilter); Scan.setfilter (filterlist);//Get result set Resultscanner Resultscanner = Hbasetemplate.querybyscan (table_name, scan);//traverse result set try{if (Resultscanner! = null) {Resultscanner.foreach (resu LT, {list<cell> celllist = Result.listcells (); ... } }}finally{if (ResultscannEr! = null) {resultscanner.close (); }}
The bulk query can be implemented by the Querybyscan () method, the first parameter is the table name, the second parameter is scan, the query is constructed by a different scan, and the filter is added to the build scan object, and multiple filters can be added.
It is important to note that the Resultscanner class here, when traversing the result set, needs to use the try-finally structure to close the object after the Resultscanner object is used. This is highlighted in HBase's official documentation. Therefore, you need to pay extra attention when using Resultscanner objects.
Common filters:
Line Health Filter: RowFilter
Column Family filter: Familyfilter
Value Filter: Valuefilter
Column filter: Qualifierfilter
Single-column Value filter: Singlecolumnvaluefilter (returns rows that meet the criteria)
Single-Column value exclusion filter: Singlecolumnexcludefilter (returns the result of excluding the column, as opposed to a single-row value filter)
Prefix filter: Prefixfilter (this filter is for the row health, in the construction method passed in the form of a byte array, the filter will go to match the line health)
Page filter: Pagefilter (when using the Pagefilter filter, it is important to note that it is not possible to return the corresponding number of results by setting the page size)
String tableName = "RECOMMEND_ENGINE_DATA_MODEL";Scan scan = new Scan();PageFilter pageFilter = new PageFilter(1);scan.setFilter(pageFilter);ResultScanner resultScanner = hBaseDao.queryByScan(tableName, scan);try{ resultScanner.forEach(result -> { result.listCells().forEach(cell -> { // process });}finally{ if (resultScanner != null) { resultScanner.close(); }}
The above code sets the page size to 1, expected to return a piece of data, but the result will return two data, the number of results returned will depend on the number of regionserver.
If the order of filterlist,filterlist affects the pagefilter effect.
General comparison filter, you need to use the comparison operator in Comparefilter.compareop. All filters are set with the scan object.
Multi-Filter Query
String tableName = "Hbase-component"; Scan scan = new scan (); Pagefilter pagefilter = new Pagefilter (1); Singlecolumnvaluefilter singlecolumnvaluefilter = new Singlecolumnvaluefilter ("CF1". GetBytes (), "col1 ". GetBytes (), CompareFilter.CompareOp.EQUAL, New Substringcomparator (" group ")); Singlecolumnvaluefilter . Setfilterifmissing (True); filterlist filterlist = new filterlist (); Filterlist.addfilter (Singlecolumnvaluefilter); Filterlist.addfilter ( Pagefilter); Scan.setfilter (filterlist); Resultscanner Resultscanner = Hbasedao.querybyscan (tableName, scan); try {Resultscanner.foreach (result, { Result.listcells (). ForEach (cell, {System.out.println) ("row:" + bytes.tostring (cellut Il.clonerow (cell) + "family:" + bytes.tostring (cellutil.clonefamily (cell)) + "Qualif IER: "+ bytes.tostring (Cellutil.clonequalifier (cell)) +" value: "+ bytes.tostring (cellutil.cloneValue (cell)); }); }); } finally {if (Resultscanner! = null) {resultscanner.close (); } }
Multiple filters need to be filterlist and set directly to the scan object. Multiple filters need to pay attention to the order of the filter, such as the above code if the two filters in the order of exchange, the results of the query is not the same.
Mapping of result Sets
In HBase, all the default order is alphabetical, for example, CF1 column families have more than one column: col1, col2, col3, then the order of cells in listcells () is always arranged alphabetically by column name when traversing the result set.
So Celllist.get (0) is the corresponding col1 in the data, Celllist.get (1) is the corresponding col2 data, Celllist.get (2) is the corresponding col3 data.
If the column is named A, B, C, the corresponding subscript is celllist.get (0), Celllist.get (1), Celllist.get (2)