spark 对hbase 操作
本文将分两部分介绍,第一部分讲解使用 HBase 新版 API 进行 CRUD 基本操作;第二部分讲解如何将 Spark 内的 RDDs 写入 HBase 的表中,反之,HBase 中的表又是如何以 RDDs 形式加载进 Spark 内的。
环境配置
为了避免版本不一致带来不必要的麻烦,API 和 HBase环境都是 1.0.0 版本。HBase 为单机模式,分布式模式的使用方法类似,只需要修改HBaseConfiguration
的配置即可。
开发环境中使用 SBT 加载依赖项
name := "SparkLearn" version := "1.0" scalaVersion := "2.10.4" libraryDependencies += "org.apache.spark" %% "spark-core" % "1.3.0" libraryDependencies += "org.apache.hbase" % "hbase-client" % "1.0.0" libraryDependencies += "org.apache.hbase" % "hbase-common" % "1.0.0" libraryDependencies += "org.apache.hbase" % "hbase-server" % "1.0.0" |
HBase 的 CRUD 操作
新版 API 中加入了 Connection
,HAdmin
成了Admin
,HTable
成了Table
,而Admin
和Table
只能通过Connection
获得。Connection
的创建是个重量级的操作,由于Connection
是线程安全的,所以推荐使用单例,其工厂方法需要一个HBaseConfiguration
。
val conf = HBaseConfiguration.create() |
创建表
使用Admin
创建和删除表
val userTable = TableName.valueOf("user") //创建 user 表 |
插入、查询、扫描、删除操作
HBase 上的操作都需要先创建一个操作对象Put
,Get
,Delete
等,然后调用Table
上的相对应的方法
try{ |
Spark 操作 HBase
写入 HBase
首先要向 HBase 写入数据,我们需要用到PairRDDFunctions.saveAsHadoopDataset
。因为 HBase 不是一个文件系统,所以saveAsHadoopFile
方法没用。
def saveAsHadoopDataset(conf: JobConf): Unit
Output the RDD to any Hadoop-supported storage system, using a Hadoop JobConf object for that storage system
这个方法需要一个 JobConf 作为参数,类似于一个配置项,主要需要指定输出的格式和输出的表名。
Step 1:我们需要先创建一个 JobConf。
//定义 HBase 的配置 |
Step 2: RDD 到表模式的映射
在 HBase 中的表 schema 一般是这样的:
row cf:col_1 cf:col_2
而在Spark中,我们操作的是RDD元组,比如(1,"lilei",14)
, (2,"hanmei",18)
。我们需要将 RDD[(uid:Int, name:String, age:Int)]
转换成 RDD[(ImmutableBytesWritable, Put)]
。所以,我们定义一个 convert 函数做这个转换工作
def convert(triple: (Int, String, Int)) = { |
Step 3: 读取RDD并转换
//read RDD data from somewhere and convert |
Step 4: 使用saveAsHadoopDataset
方法写入HBase
localData.saveAsHadoopDataset(jobConf) |
读取 HBase
Spark读取HBase,我们主要使用SparkContext
提供的newAPIHadoopRDD
API将表的内容以 RDDs 的形式加载到 Spark 中。
val conf = HBaseConfiguration.create() |
最新文章
- php读取大文件
- 【转】MSM搭建(Memcached_Session_Manager)--解决集群session共享
- 【Leetcode】 - Divide Two Integers 位运算实现整数除法
- javascript google map circle radius_changed ,angularjs google map circle radius_changed
- android ioctl fuzz,android 本地提权漏洞 android root
- 获取sqlserver数据库中所有库、表、字段名的方法
- Serializable接口的背后
- c语言,链表
- Redis在win7上的安装与可视化应用
- Windows Phone获取WiFi BSSID
- Claris and XOR
- 设计模式成长记(一) 抽象工厂模式(Abstract Factory)
- Pycharm配置支持vue语法
- 003.MMM双主-双从读写分离部署
- socket.timeout: The read operation timed out 更改pip源至国内镜像,显著提升下载速度
- eclipse 对 hadoop1.2.1 hdfs 文件操作
- 【摘】SVN提交与版本冲突
- linux 驱动之LCD驱动(有framebuffer)
- python --help查询python相关命令
- EasyUI 让dialog中的treegrid的列头固定