Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Build a Data Pipeline Using Kafka, Spark, and Hive

DZone 's Guide to

How to Build a Data Pipeline Using Kafka, Spark, and Hive

In this post, we learn how to make a basic data pipeline using these popular Apache frameworks and the Scala language.

· Big Data Zone ·
Free Resource

In this post, we will look at how to build data pipeline to load input files (XML) from a local file system into HDFS, process it using Spark, and load the data into Hive.

Use Case

We have some XML data files getting generated on a server location at regular intervals daily. Our task is to create a data pipeline which will regularly upload the files to HDFS, then process the file data and load it into Hive using Spark.

Solution

Initial Steps

  • Create Hive tables depending on the input file schema and business requirements.

  • Create a Kafka Topic to put the uploaded HDFS path into.

Step 1

At first we will write Scala code to copy files from he local file system to HDFS. We use the copyFromLocal method as mentioned in the below code (FileUploaderHDFS). The below code copies the file from the path assigned to the  localPathStr variable to the HDFS path assigned to the destPath variable.

Once the file gets loaded into HDFS, then the full HDFS path will gets written into a Kafka Topic using the Kafka Producer API. So our Spark code will load the file and process it.

FileUploaderHDFS:

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.Path
import org.apache.hadoop.fs.FileSystem
import java.io.IOException
import java.io.File
import java.nio.file.{Files, Paths, StandardCopyOption}

import java.util.Properties

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}

object FileUploaderHDFS {

  def main(args: Array[String]): Unit = {

    try {

      println("Inside FileUploaderHDFS")
      val hadoopConf = new Configuration()
      val hdfs = FileSystem.get(hadoopConf)

      val localPathStr = "<local-input-file-path>"

      val fileList = getListOfFiles(localPathStr)
      val destPath = new Path("<hdfs-destination-path>")
      if (!hdfs.exists(destPath))
        hdfs.mkdirs(destPath)
      for (file <- fileList) {


        val localFilePath = new Path("file:" + "//" + file)
        hdfs.copyFromLocalFile(localFilePath, destPath)


        /*Move file to processed folder*/
         Files.move(
          Paths.get(file.toString),
          Paths.get("<Processed-File-Path>"),
          StandardCopyOption.REPLACE_EXISTING)

        produceKafkaMsg(destPath + "/" + file.getName)

        println("File has been uploaded into HDFS " + destPath  )

      }


    }

    catch {
      case ex: IOException => {

        println("Input /Output Exception")

      }
    }
  }


  def getListOfFiles(dir: String): List[File] = {
    val d = new File(dir)
    if (d.exists && d.isDirectory) {
      d.listFiles.filter(_.isFile).toList
    } else {
      List[File]()
    }
  }

// This method writes the uploaded file path into Kafka topic
  def produceKafkaMsg(hdfsFile:String):Unit={

    val kafkaProducerProperty = new Properties();
    kafkaProducerProperty.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
    kafkaProducerProperty.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    kafkaProducerProperty.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")

    val kafkaProducer = new KafkaProducer[Nothing, String](kafkaProducerProperty)

    val kafkaProducerRecord = new ProducerRecord("inputFileLists",hdfsFile)
    println(kafkaProducer.send(kafkaProducerRecord))

    println("File has been uploaded into HDFS " + hdfsFile  )


  }

}

Step 2

Write the code for a Kafka Consumer (GetFileFromKafka) which is running in an infinite loop and regularly pools the Kafka Topic for the input message. Once the HDFS file path is available in the topic, it (ApplicationLauncher) launches the Spark application  (ParseInputFile) which process the file and loads the data into a Hive table. Please see below code for details. 

ApplicationLauncher:

import org.apache.spark.launcher.SparkLauncher
import org.apache.spark.launcher.SparkAppHandle

object ApplicationLauncher {

  def launch(hdfsFilePath:String):Unit={

    val command = new SparkLauncher()
      .setAppResource("<file-path-of -your-application-jar>")
      .setMainClass("ParseInputFile")
      .setVerbose(false)
      .addAppArgs(hdfsFilePath)
      .setMaster("local")
      .addSparkArg("--jars","<file-path>/spark-xml_2.11-0.5.0.jar") //It is required to parse xml file
    val appHandle = command.startApplication()
    appHandle.addListener(new SparkAppHandle.Listener{
      def infoChanged(sparkAppHandle : SparkAppHandle) : Unit = {
        println(sparkAppHandle.getState + "  Custom Print")
      }

      def stateChanged(sparkAppHandle : SparkAppHandle) : Unit = {
        println(sparkAppHandle.getState)
        if ("FINISHED".equals(sparkAppHandle.getState.toString)){
          sparkAppHandle.stop
        }
      }
    })



  }

}

GetFileFromKafka

import java.util.{Collections, Properties}

import org.apache.kafka.clients.consumer.{ConsumerConfig, KafkaConsumer}

import scala.collection.JavaConversions._


object GetFileFromKafka {

  def main(args: Array[String]): Unit = {
    println("Inside GetFileFromKafka")
    val kafkaConsumerProperty = new Properties()
    kafkaConsumerProperty.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
    kafkaConsumerProperty.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer")
    kafkaConsumerProperty.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer")
    kafkaConsumerProperty.put(ConsumerConfig.GROUP_ID_CONFIG, "cg01")
    kafkaConsumerProperty.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")

    val topic = "inputFileLists"
    val kafkaConsumer = new KafkaConsumer[String,String](kafkaConsumerProperty)
    kafkaConsumer.subscribe(Collections.singletonList(topic))
    while(true){
      val fileLists = kafkaConsumer.poll(10000)
      //Read the file paths from kafka topic
      for(filePath <- fileLists)
      {
       //Launch Spark-Application to process File
        try{
          ApplicationLauncher.launch(filePath.value())
        }
        catch{
          case e :Throwable => e.printStackTrace
        }


      }
    }


  }

}

Step 3:

Now, in this final step, we will write a Spark application to parse an XML file and load the data into Hive tables ( ParseInputFile) depending on business requirements.

ParseInputFile:

import com.databricks.spark.xml
import org.apache.spark.SparkConf
import org.apache.spark._
import org.apache.spark.sql.SparkSession


object ParseInputFile {

  def main(args: Array[String]): Unit = {

    val filePath = args(0)
    val sparkSession = SparkSession.builder().appName("Read Raw XML").enableHiveSupport().getOrCreate()
    val webRawData = sparkSession.read.format("com.databricks.spark.xml").option("rootTag","records").option("rowTag","record").load(filePath)
    webRawData.registerTempTable("tempRawData")

    sparkSession.sql("<Your-HiveQL-To process data from tempRawData table>").registerTempTable("webDataEnrich")


  sparkSession.sql("<Insert-HiveQL-to load data into respective hive table>")


  }


}

Final Step:

 1. Make sure the FileUploaderHDFS application is synced with the frequency of input files generation.

 2.  Launch the GetFileFromKafka application and it should be running continuously. 

Topics:
data pipeline ,big data ,apache kafka tutorial ,apache spark tutorial scala ,hive tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}