How to use “put” to add data in hbase?

In HBase, data can be added using the Put class. The Put class is a class in the org.apache.hadoop.hbase.client package that is used to represent the data to be inserted or updated.

Here are the steps for adding data using the Put class:

  1. Instantiate a Put object and pass the row key as a parameter to the constructor. The row key serves as a unique identifier for the data and is used to determine the data’s location in the HBase table.
  2. Instantiate a new Put object with the key “row1”.
  3. Use the addColumn method to add the column family, column qualifier, and corresponding value to be inserted or updated.
  4. Add a column to the table with the specified column family, column name, and value.
  5. To add multiple columns, you can repeatedly call the addColumn method.
  6. Add column “col2” with value “value2” in column family “cf1” in the put operation. Also, add column “col3” with value “value3” in column family “cf2”.
  7. Use the put method of the Table to add the Put object to the HBase table.
  8. insert the put value into the table.

The complete code example is shown below:

import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.*;

public class HBaseExample {
    public static void main(String[] args) {
        try {
            // 创建 HBase 配置对象
            Configuration config = HBaseConfiguration.create();

            // 创建 HBase 连接对象
            Connection connection = ConnectionFactory.createConnection(config);

            // 获取 HBase 表对象
            TableName tableName = TableName.valueOf("mytable");
            Table table = connection.getTable(tableName);

            // 创建 Put 对象,并指定行键
            Put put = new Put(Bytes.toBytes("row1"));

            // 添加列族、列限定符和值
            put.addColumn(Bytes.toBytes("cf1"), Bytes.toBytes("col1"), Bytes.toBytes("value1"));
            put.addColumn(Bytes.toBytes("cf1"), Bytes.toBytes("col2"), Bytes.toBytes("value2"));

            // 将 Put 对象添加到表中
            table.put(put);

            // 关闭连接
            table.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Please note that the above code is provided for reference only, and you may need to make corresponding modifications based on your own environment and needs when actually using it.

bannerAds