如何在Java中使用newAPIHadoopRDD(spark)来读取Hbase数据

时间:2017-02-03 08:32:42

标签: java apache-spark hbase

我尝试使用spark API读取Hbase数据。

代码:

    // Define SparkContext
    SparkConf sparkConf = new SparkConf().setAppName("Spark-Hbase").setMaster("master");
    sparkConf.set("XXX", "XXX");
    JavaSparkContext jsc = new JavaSparkContext(sparkConf);

    // Conf with Hbase
    Configuration conf = HBaseConfiguration.create();

    // Read data using spark
    JavaPairRDD<ImmutableBytesWritable, Result> hBaseRDD = 
            jsc.newAPIHadoopRDD(conf, TableInputFormat.class, ImmutableBytesWritable.class, Result.class);

问题出在newAPIHadoopRDD方法上。我有这个错误,我不明白。

Bound mismatch: The generic method newAPIHadoopRDD(Configuration, Class<F>, Class<K>, Class<V>) of type JavaSparkContext is not applicable for the arguments (Configuration, Class<TableInputFormat>, Class<ImmutableBytesWritable>, Class<Result>). The inferred type TableInputFormat is not a valid substitute for the bounded parameter <F extends InputFormat<K,V>>

如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

您可以按照以下示例

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableInputFormat;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;

public class HBaseReader {
    public static void main(String[] args) throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
        Configuration conf = HBaseConfiguration.create();
        conf.set(TableInputFormat.INPUT_TABLE, "table_name");
        JavaSparkContext jsc = new JavaSparkContext(new SparkConf());
        JavaPairRDD<ImmutableBytesWritable, Result> source = jsc
                .newAPIHadoopRDD(conf, TableInputFormat.class,
                        ImmutableBytesWritable.class, Result.class);
        Result result = Result.EMPTY_RESULT;

    }
}

答案 1 :(得分:0)

您必须将InputFormat用于newAPIHadoopRDD

public class MyInputFormat extends InputFormat<NullWritable, Record> { }

记录将是任何类型的可扩展可写

 interface Record extends Writable {}