sparksql读取hbase

test("hbase") {
  val sqlContext = SparkSession.builder().getOrCreate().sqlContext
  //拉取hbase数据
  val hBaseConfiguration = HBaseConfiguration.create()
  hBaseConfiguration.set(TableInputFormat.INPUT_TABLE, "apptmslogs:waybillInfo") //hbase 中的表
  hBaseConfiguration.set(TableInputFormat.SCAN_COLUMNS, "cf1:airwaybillno cf1:arrivecity") //hbase 字段 ,多个字段空格隔开
  hBaseConfiguration.set(TableInputFormat.SCAN_ROW_START, "20180517132443-Y01591805170032") //rowkey开始行
  hBaseConfiguration.set(TableInputFormat.SCAN_ROW_STOP, "20180615170225-Y01591806150061")  //rowkey结束行
  val hbaseRDD: RDD[(ImmutableBytesWritable, Result)] = sc.newAPIHadoopRDD(hBaseConfiguration,
    classOf[TableInputFormat],
    classOf[ImmutableBytesWritable],
    classOf[Result])

  val rowRDD = hbaseRDD.map({ case (ib, result) =>
    val cells = result.rawCells()
    val it = cells.iterator
    val airwaybillno = it.next() //第一个字段
    val arrivecity = it.next()   //第二个字段
//转换成RDD[Row]
    Row(new String(airwaybillno.getValueArray, airwaybillno.getValueOffset, airwaybillno.getValueLength),
      new String(arrivecity.getValueArray, arrivecity.getValueOffset, arrivecity.getValueLength))

  })

  val structType = StructType(StructField("airwaybillno", StringType, true) :: StructField("arrivecity", StringType, true) :: Nil)//构造schema
  val df = sqlContext.createDataFrame(rowRDD, structType)//转成DataFrame
  df.createOrReplaceTempView("waybillInfo")//注册表
  val sqldf = sqlContext.sql("select * from waybillInfo")
  sqldf.show()

}

查询结果展示

+-----------------+----------+
|     airwaybillno|arrivecity|
+-----------------+----------+
|"Y01591805170032"|      "咸阳"|
|"Y01591806010063"|      "安阳"|
|"Y00481806020005"|      "兰州"|
|"Y00491806120014"|      "厦门"|
|"Y00491806120033"|      "厦门"|
|"Y00491806120052"|      "厦门"|
|"Y00491806130141"|      "厦门"|
|"Y00491806140033"|      "厦门"|
|"Y00491806140052"|      "厦门"|
+-----------------+----------+

 

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值