spark常用模板

1. 批任务整体流程:

import org.apache.spark.sql.SparkSession
import org.slf4j.LoggerFactory//高性能日志
object test{

  private val LOGGER = LoggerFactory.getLogger(this.getClass)
  def main(args: Array[String]): Unit = {

    args.foreach(x => Util.infoLog(LOGGER, s"****args: ${x} ****")
    )
    val inputSql=args(0)
    val inputSchema=args(1).split(",")
    val defaultPartitions=args(2).toInt


    val sc = SparkSession.builder().enableHiveSupport().getOrCreate()
    import sc.implicits._

    try{
    val inputDocsDF = sc.sql(inputSql).repartition(defaultPartitions)
    .rdd.map {
            row =>
            val docSql = row.toSeq.asInstanceOf[Seq[String]].toArray
            //.toBuffer.asInstanceOf[ArrayBuffer[String]]  //可变长度,适用于schema要增加的情况
            docSql

        //做正式处理
        }    


  } finally {
    if (null != sc) {
      //清空persist的rdd
      sc.sparkContext.getPersistentRDDs.foreach(x => x._2.unpersist())//rdd,dataframe都适用,因为底层都是rdd
      //sc.catalog.uncacheTable(tableName) //用于清空指定表,不存在会报错
      //sc.catalog.clearCache() //清空所有cache(),不包括disk,如果cache了tempView,则需要用该方法清除
      sc.stop
    }
  }
  }

}

 2.加载hdfs文件:

import org.apache.hadoop.fs.{FileSystem, Path}


val hdfsHead = filePath.split("\\/").take(3).mkString("/")

val hdfs=org.apache.hadoop.fs.FileSystem.get(new java.net.URI(hdfsHead), new org.apache.hadoop.conf.Configuration())
  
if (hdfs.exists(new Path(filePath))) {
      val filelines = sparkContext.textFile(filePath).collect().filter(x => !x.startsWith("#") && x.trim.nonEmpty)
      Util.infoLog(LOGGER, "*****文件加载完毕: " + filelines.take(10).mkString("#"))
      filelines.foreach {
        line =>
          
         //做处理
      }
    }
else {
        sys.error("*****文件不存在:" + filePath)
      }

3.rdd写hive

写入前rdd转dataframe

import org.apache.spark.sql.Row
import org.apache.spark.sql.types.{StringType, StructField, StructType}

 val outDF =  sc.createDataFrame(inputDocsRDD.map(x => Row.apply(x:_*)),
        StructType(INPUT_SCHEMA.map{x=> StructField(x, StringType)})).repartition(20)
//INPUT_SCHEMA为字段名array

若用方法1 ,则会需保持hive表字段与INPUT_SCHEMA一致

若用方法2,则只要列数对即可,最终根据hive表字段为准

见:scala中HDFS文件操作,hive表操作_Code_LT的博客-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值