DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • 6 Best Practices to Build Data Pipelines
  • Building Robust Real-Time Data Pipelines With Python, Apache Kafka, and the Cloud
  • Request Tracing in Spring Cloud Stream Data Pipelines With Kafka Binder
  • The Technology Stack Needed To Build a Web3 Application

Trending

  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • How AI Agents Are Transforming Enterprise Automation Architecture
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  1. DZone
  2. Data Engineering
  3. Big Data
  4. How to Build a Data Pipeline Using Kafka, Spark, and Hive

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.

By 
Avi Garg user avatar
Avi Garg
·
May. 07, 19 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
30.5K Views

Join the DZone community and get the full member experience.

Join For Free

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. 

kafka Data (computing) File system Pipeline (software) Build (game engine) hadoop

Opinions expressed by DZone contributors are their own.

Related

  • 6 Best Practices to Build Data Pipelines
  • Building Robust Real-Time Data Pipelines With Python, Apache Kafka, and the Cloud
  • Request Tracing in Spring Cloud Stream Data Pipelines With Kafka Binder
  • The Technology Stack Needed To Build a Web3 Application

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!