通过将Spark与Java一起读取HBase的数据



我想使用java通过spark访问hbase。除此之外,我还没有找到任何例子。在答案中是编写的,

您也可以在Java

中写这本书

我从HBase使用Spark读取了此代码:

import org.apache.hadoop.hbase.client.{HBaseAdmin, Result}
import org.apache.hadoop.hbase.{ HBaseConfiguration, HTableDescriptor }
import org.apache.hadoop.hbase.mapreduce.TableInputFormat
import org.apache.hadoop.hbase.io.ImmutableBytesWritable
import org.apache.spark._
object HBaseRead {
  def main(args: Array[String]) {
    val sparkConf = new SparkConf().setAppName("HBaseRead").setMaster("local[2]")
    val sc = new SparkContext(sparkConf)
    val conf = HBaseConfiguration.create()
    val tableName = "table1"
    System.setProperty("user.name", "hdfs")
    System.setProperty("HADOOP_USER_NAME", "hdfs")
    conf.set("hbase.master", "localhost:60000")
    conf.setInt("timeout", 120000)
    conf.set("hbase.zookeeper.quorum", "localhost")
    conf.set("zookeeper.znode.parent", "/hbase-unsecure")
    conf.set(TableInputFormat.INPUT_TABLE, tableName)
    val admin = new HBaseAdmin(conf)
    if (!admin.isTableAvailable(tableName)) {
      val tableDesc = new HTableDescriptor(tableName)
      admin.createTable(tableDesc)
    }
    val hBaseRDD = sc.newAPIHadoopRDD(conf, classOf[TableInputFormat], classOf[ImmutableBytesWritable], classOf[Result])
    println("Number of Records found : " + hBaseRDD.count())
    sc.stop()
  }
}

谁能给我一些提示如何找到正确的依赖性,对象和东西?

看来HBaseConfigurationhbase-client中,但实际上我卡在TableInputFormat.INPUT_TABLE上。不应该处于相同的依赖性吗?

有更好的方法可以使用Spark访问HBase?

TableInputFormat类位于hbase-server.jar中,您需要在pom.xml中添加该依赖关系。请在Spark用户列表中检查HBase和不存在的TableInputFormat。

<dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-server</artifactId>
    <version>1.3.0</version>
</dependency>

及以下是使用Spark从HBase读取的示例代码。

public static void main(String[] args) throws Exception {
    SparkConf sparkConf = new SparkConf().setAppName("HBaseRead").setMaster("local[*]");
    JavaSparkContext jsc = new JavaSparkContext(sparkConf);
    Configuration hbaseConf = HBaseConfiguration.create();
    hbaseConf.set(TableInputFormat.INPUT_TABLE, "my_table");
    JavaPairRDD<ImmutableBytesWritable, Result> javaPairRdd = jsc.newAPIHadoopRDD(hbaseConf, TableInputFormat.class,ImmutableBytesWritable.class, Result.class);
    jsc.stop();
  }
}

是。有。使用Cloudera的SparkOnhbase。

<dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-spark</artifactId>
    <version>1.2.0-cdh5.7.0</version>
</dependency>

和使用HBASE扫描以读取您的hbase表(如果您知道要检索的行的钥匙)。

Configuration conf = HBaseConfiguration.create();
conf.addResource(new Path("/etc/hbase/conf/core-site.xml"));
conf.addResource(new Path("/etc/hbase/conf/hbase-site.xml"));
JavaHBaseContext hbaseContext = new JavaHBaseContext(jsc, conf);
Scan scan = new Scan();
scan.setCaching(100);
JavaRDD<Tuple2<byte[], List<Tuple3<byte[], byte[], byte[]>>>> hbaseRdd = hbaseContext.hbaseRDD(tableName, scan);
System.out.println("Number of Records found : " + hBaseRDD.count())

最新更新