Book Image

Apache Spark 2.x Cookbook

By : Rishi Yadav
Book Image

Apache Spark 2.x Cookbook

By: Rishi Yadav

Overview of this book

While Apache Spark 1.x gained a lot of traction and adoption in the early years, Spark 2.x delivers notable improvements in the areas of API, schema awareness, Performance, Structured Streaming, and simplifying building blocks to build better, faster, smarter, and more accessible big data applications. This book uncovers all these features in the form of structured recipes to analyze and mature large and complex sets of data. Starting with installing and configuring Apache Spark with various cluster managers, you will learn to set up development environments. Further on, you will be introduced to working with RDDs, DataFrames and Datasets to operate on schema aware data, and real-time streaming with various sources such as Twitter Stream and Apache Kafka. You will also work through recipes on machine learning, including supervised learning, unsupervised learning & recommendation engines in Spark. Last but not least, the final few chapters delve deeper into the concepts of graph processing using GraphX, securing your implementations, cluster optimization, and troubleshooting.
Table of Contents (19 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

WordCount using Structured Streaming


Let's start with a simple example of streaming in which in one terminal, we will type some text and the streaming application will capture it in another window.

How to do it...

  1. Start the Spark shell:
$ spark-shell  
  1. Create a DataFrame to read what's coming on port 8585:
scala> val lines = spark.readStream.format("socket").option("host","localhost").option("port",8585).load
  1. Cast the lines from DataFrame to Dataset with the String datatype and then flatten it:
scala> val words = lines.as[String].flatMap(_.split(" "))
  1.  Do the word count:
scala> val wordCounts = words.groupBy("value").count()
  1. Start the netcat server in a separate window:
$ nc -lk 8585
  1. Come back to the previous terminal and print the complete set of counts to the console every time it is updated:
scala> val query = wordCounts.writeStream.outputMode("complete").format("console").start()
  1. Now go back to the terminal where you started netcat and enter different lines, such as to be or not to be...