-
-
Save selvanponraj/cf62dbdd70e4319f57f7 to your computer and use it in GitHub Desktop.
Accessing Hbase from Apache Spark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.apache.spark.rdd.NewHadoopRDD | |
| import org.apache.hadoop.hbase.mapreduce.TableInputFormat | |
| import org.apache.hadoop.hbase.HBaseConfiguration | |
| import org.apache.hadoop.hbase.client.Result | |
| import org.apache.hadoop.hbase.io.ImmutableBytesWritable | |
| val sparkContext = new SparkContext("local", "Simple App") | |
| val hbaseConfiguration = (hbaseConfigFileName: String, tableName: String) => { | |
| val hbaseConfiguration = HBaseConfiguration.create() | |
| hbaseConfiguration.addResource(hbaseConfigFileName) | |
| hbaseConfiguration.set(TableInputFormat.INPUT_TABLE, tableName) | |
| hbaseConfiguration | |
| } | |
| val rdd = new NewHadoopRDD( | |
| sparkContext, | |
| classOf[TableInputFormat], | |
| classOf[ImmutableBytesWritable], | |
| classOf[Result], | |
| hbaseConfiguration("/path/to/hbase-site.xml", "table-with-data") | |
| ) | |
| /** Convert columns to strings **/ | |
| import scala.collection.JavaConverters._ | |
| val columns = rdd.map(tuple => tuple._2).map(result => result.getColumn("Column Family".getBytes(), | |
| "ColumnQualifier".getBytes())).map(keyValues => { | |
| new String(keyValues.asScala.reduceLeft{ | |
| (a,b) => if (a.getTimestamp > b.getTimestamp) a else b | |
| }.getValue.map(_.toChar))}) | |
| /** another way to get multiple columns */ | |
| val cols = rdd.map(tuple => tuple._2).map(result => result.getColumn("CF".getBytes, "CQ1".getBytes) :: result.getColumn("CF".getBytes, "CQ2".getBytes) :: result.getColumn("CF".getBytes, "CQ2".getBytes):: Nil) | |
| /** convert all values to strings **/ | |
| val row_vals = cols.map(row => row.map(ele => new String(ele.head.getValue.map(_.toChar)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment