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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Data Engineering
  3. Databases
  4. Streaming SQL Ingest

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.

Tim Spann user avatar by
Tim Spann
CORE ·
Nov. 02, 16 · Tutorial
Like (2)
Save
Tweet
Share
5.24K Views

Join the DZone community and get the full member experience.

Join For Free

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.

sql MySQL Database file IO Orc (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Simulate Network Latency and Packet Drop In Linux
  • The Role of Data Governance in Data Strategy: Part II
  • Beginners’ Guide to Run a Linux Server Securely
  • Upgrade Guide To Spring Data Elasticsearch 5.0

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: