Over a million developers have joined DZone.

Streaming SQL Ingest

The first important step in building Big Data store (or lake) is ingesting data from your existing OLTP systems which are generally SQL-based.

· Big Data Zone

Learn how you can maximize big data in the cloud with Apache Hadoop. Download this eBook now. Brought to you in partnership with Hortonworks.

Data Engineering requires you ingest data from existing sources, often in a one-time batch and then you have to determine some way to keep your data lake in sync.   Some people will write SQOOP jobs triggered by Chron or Oozie.  Some will write custom C#, Java, Python or Scala programs that ingest data via a schedule or predetermine batch schedule.  There is another way and it's open source from Apache. NiFi's QueryDatabaseTable processor for zero coding reading of data from a SQL RDBMS and produce standard AVRO files with a built-in schema.   These AVRO files can be stored directly in HDFS or S3, easily sent over KAFKA or for my use case I convert them into SQL inserts and into ORC files for fast Hive access.

Using readily available JDBC drivers, Apache NiFi can easily read your existing SQL tables and ingest records as they arrive.  The one caveat being that you have to have a value that will always increase.   If you don't have an autoincrementing key, I recommend adding one just for these purposes.   It also makes a very nice choice for a surrogate primary unique key.

For MySQL and MariaDB, you can easily add one via:

ALTER TABLE `useraccount` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST;  

Oracle you can use a sequence and an identify column in SQL Server.

Once NiFi converts your files to ORC, lands it in HDFS, it also creates a Hive Table definition on those of those ORC files and lets you have fast datawarehouse SQL access to them.

For a step by step example, please see my detailed walkthrough here.

ORC files are a really fast format that is readily querable by Hive on Tez for fast datawarehouse SQL queries.   For some benchmarks to see if ORC meets your needs, try this benchmark tool.

For a nice presentation on ORC, JSON, AVRO and Parquet files, check this talk out. In my examples, I used all these formats except Parquet. Parquet is very simliar to ORC and is often used in Spark. To write to a Parquet file from Spark, you simply write a DataFrame to a Parquet file:

myDataFrame.write.parquet("myDataFrame.parquet")

In most production Spark 1.6+ environments running on YARN, this will write the file to HDFS.  For consistency, I recommend connecting your Spark jobs to the Hive Context (instead of the regular SQL context) to ensure you gain access to the Hive Metastore and your files get saved to HDFS and not random standard disk which is not distributed and may not have adequate storage or production level monitoring.

Below is an example Spark Scala program to do this:

def main(args: Array[String]) {

  Logger.getLogger("org.apache.spark").setLevel(Level.ERROR)
  Logger.getLogger("org.apache.spark.storage.BlockManager").setLevel(Level.ERROR)

  val logger: Logger = Logger.getLogger("com.dataflowdeveloper.sentiment.TwitterSentimentAnalysis")
  val sparkConf = new SparkConf().setAppName("TwitterSentimentAnalysis")

  sparkConf.set("spark.streaming.backpressure.enabled", "true")
  sparkConf.set("spark.cores.max", "4")
  sparkConf.set("spark.serializer", classOf[KryoSerializer].getName)
  sparkConf.set("spark.sql.tungsten.enabled", "true")
  sparkConf.set("spark.eventLog.enabled", "true")
  sparkConf.set("spark.app.id", "Sentiment")
  sparkConf.set("spark.io.compression.codec", "snappy")
  sparkConf.set("spark.rdd.compress", "true")

  val sc = new SparkContext(sparkConf)
  val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
  import sqlContext.implicits._
  val tweets = sqlContext.read.json("hdfs://sandbox.hortonworks.com:8020/social/twitter")
  sqlContext.setConf("spark.sql.orc.filterPushdown", "true")

  tweets.printSchema()
  tweets.take(5).foreach(println)

  try { 
       val outputTweets = tweets.map( row => Tweet(convert(row.getString(row.fieldIndex("coordinates"))),convert(row.getString(row.fieldIndex("geo"))),
    convert(row.getString(row.fieldIndex("handle"))),
    convert(row.getString(row.fieldIndex("hashtags"))),
    convert(row.getString(row.fieldIndex("language"))),
    convert(row.getString(row.fieldIndex("location"))),
    convert(row.getString(row.fieldIndex("msg"))),
    convert(row.getString(row.fieldIndex("time"))),
    convert(row.getString(row.fieldIndex("tweet_id"))),
    convert(row.getString(row.fieldIndex("unixtime"))),
    convert(row.getString(row.fieldIndex("user_name"))),
    convert(row.getString(row.fieldIndex("tag"))),
    convert(row.getString(row.fieldIndex("profile_image_url"))),
    convert(row.getString(row.fieldIndex("source"))),
    convert(row.getString(row.fieldIndex("place"))),
    convert(row.getString(row.fieldIndex("friends_count"))),
    convert(row.getString(row.fieldIndex("followers_count"))),
    convert(row.getString(row.fieldIndex("retweet_count"))),
    convert(row.getString(row.fieldIndex("time_zone"))),
    convert(row.getString(row.fieldIndex("sentiment"))), 
    detectSentiment(row.getString(row.fieldIndex("msg"))).toString ) )

 outputTweets.toDF().write.format("orc").mode(SaveMode.Overwrite).saveAsTable("default.sparktwitterorc")

In the above example, I save the dataframe to ORC through the Hive SQL Context and put it under the default database with the Hive table name of sparktwitterorc.

Hortonworks DataFlow is an integrated platform that makes data ingestion fast, easy, and secure. Download the white paper now.  Brought to you in partnership with Hortonworks

Topics:
hadoop ,big data ,sql ,java ,nifi ,database ,data engineering ,spark ,scala ,jvm

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}