温馨提示×

hbase如何写入数据

小亿
84
2024-05-06 20:07:54
栏目: 大数据

要在HBase中写入数据,可以通过HBase的Java API使用Put类。以下是一个简单的示例:

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

public class Example {
    public static void main(String[] args) {
        try {
            org.apache.hadoop.conf.Configuration config = HBaseConfiguration.create();
            config.set("hbase.zookeeper.quorum", "localhost");
            Connection connection = ConnectionFactory.createConnection(config);
            Table table = connection.getTable(TableName.valueOf("example_table"));

            Put put = new Put(Bytes.toBytes("row1"));
            put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("col1"), Bytes.toBytes("value1"));
            put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("col2"), Bytes.toBytes("value2"));

            table.put(put);

            table.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,我们创建了一个Put对象,指定了行键为"row1",列族为"cf",列名为"col1"和"col2",值为"value1"和"value2"。然后将该Put对象插入到名为"example_table"的表中。最后,记得关闭Table和Connection对象。

0