Vinnie  Erdman

Vinnie Erdman

1655600460

Advanced Analytics Tutorial Using Apache Spark in Azure Databricks

In this session you will learn the fundamentals of how to apply advanced analytics using Apache spark in Azure databricks. We will focus on how to build and deploy a machine learning model, then I have a look at how you can get started with graph based processing, using graph frames in Apache spark. The combination of big data, machine learning and graph based processing, helps to fully realise the full spectrum of advanced analytics.

You will learn the fundamentals of Spark and how it is enabled on Databricks. Then we will look at how you get started with Machine Learning and Graph based processing

You will be able to begin to work with Machine Learning & Advanced Analytics in Spark.

Spark is one of the most desirable skills on the market. Integrating with big data pipelines is fundamental to the success of Machine Learning with Big Data.

#azure #analytics #apachespark 

Advanced Analytics Tutorial Using Apache Spark in Azure Databricks
Ruth  Nabimanya

Ruth Nabimanya

1650596580

Flint: A Time Series Library for Apache Spark

The ability to analyze time series data at scale is critical for the success of finance and IoT applications based on Spark. Flint is Two Sigma's implementation of highly optimized time series operations in Spark. It performs truly parallel and rich analyses on time series data by taking advantage of the natural ordering in time series data to provide locality-based optimizations.

Flint is an open source library for Spark based around the TimeSeriesRDD, a time series aware data structure, and a collection of time series utility and analysis functions that use TimeSeriesRDDs. Unlike DataFrame and Dataset, Flint's TimeSeriesRDDs can leverage the existing ordering properties of datasets at rest and the fact that almost all data manipulations and analysis over these datasets respect their temporal ordering properties. It differs from other time series efforts in Spark in its ability to efficiently compute across panel data or on large scale high frequency data.

Requirements

DependencyVersion
Spark Version2.3 and 2.4
Scala Version2.12
Python Version3.5 and above

How to install

Scala artifact is published in maven central:

https://mvnrepository.com/artifact/com.twosigma/flint

Python artifact is published in PyPi:

https://pypi.org/project/ts-flint

Note you will need both Scala and Python artifact to use Flint with PySpark.

How to build

To build from source:

Scala (in top-level dir):

sbt assemblyNoTest

Python (in python subdir):

python setup.py install

or

pip install .

Python bindings

The python bindings for Flint, including quickstart instructions, are documented at python/README.md. API documentation is available at http://ts-flint.readthedocs.io/en/latest/.

Getting Started

Starting Point: TimeSeriesRDD and TimeSeriesDataFrame

The entry point into all functionalities for time series analysis in Flint is TimeSeriesRDD (for Scala) and TimeSeriesDataFrame (for Python). In high level, a TimeSeriesRDD contains an OrderedRDD which could be used to represent a sequence of ordering key-value pairs. A TimeSeriesRDD uses Long to represent timestamps in nanoseconds since epoch as keys and InternalRows as values for OrderedRDD to represent a time series data set.

Create TimeSeriesRDD

Applications can create a TimeSeriesRDD from an existing RDD, from an OrderedRDD, from a DataFrame, or from a single csv file.

As an example, the following creates a TimeSeriesRDD from a gzipped CSV file with header and specific datetime format.

import com.twosigma.flint.timeseries.CSV
val tsRdd = CSV.from(
  sqlContext,
  "file://foo/bar/data.csv",
  header = true,
  dateFormat = "yyyyMMdd HH:mm:ss.SSS",
  codec = "gzip",
  sorted = true
)

To create a TimeSeriesRDD from a DataFrame, you have to make sure the DataFrame contains a column named "time" of type LongType.

import com.twosigma.flint.timeseries.TimeSeriesRDD
import scala.concurrent.duration._
val df = ... // A DataFrame whose rows have been sorted by their timestamps under "time" column
val tsRdd = TimeSeriesRDD.fromDF(dataFrame = df)(isSorted = true, timeUnit = MILLISECONDS)

One could also create a TimeSeriesRDD from a RDD[Row] or an OrderedRDD[Long, Row] by providing a schema, e.g.

import com.twosigma.flint.timeseries._
import scala.concurrent.duration._
val rdd = ... // An RDD whose rows have sorted by their timestamps
val tsRdd = TimeSeriesRDD.fromRDD(
  rdd,
  schema = Schema("time" -> LongType, "price" -> DoubleType)
)(isSorted = true,
  timeUnit = MILLISECONDS
)

It is also possible to create a TimeSeriesRDD from a dataset stored as parquet format file(s). The TimeSeriesRDD.fromParquet() function provides the option to specify which columns and/or the time range you are interested, e.g.

import com.twosigma.flint.timeseries._
import scala.concurrent.duration._
val tsRdd = TimeSeriesRDD.fromParquet(
  sqlContext,
  path = "hdfs://foo/bar/"
)(isSorted = true,
  timeUnit = MILLISECONDS,
  columns = Seq("time", "id", "price"),  // By default, null for all columns
  begin = "20100101",                    // By default, null for no boundary at begin
  end = "20150101"                       // By default, null for no boundary at end
)

Group functions

A group function is to group rows with nearby (or exactly the same) timestamps.

  • groupByCycle A function to group rows within a cycle, i.e. rows with exactly the same timestamps. For example,
val priceTSRdd = ...
// A TimeSeriesRDD with columns "time" and "price"
// time  price
// -----------
// 1000L 1.0
// 1000L 2.0
// 2000L 3.0
// 2000L 4.0
// 2000L 5.0

val results = priceTSRdd.groupByCycle()
// time  rows
// ------------------------------------------------
// 1000L [[1000L, 1.0], [1000L, 2.0]]
// 2000L [[2000L, 3.0], [2000L, 4.0], [2000L, 5.0]]
  • groupByInterval A function to group rows whose timestamps fall into an interval. Intervals could be defined by another TimeSeriesRDD. Its timestamps will be used to defined intervals, i.e. two sequential timestamps define an interval. For example,
val priceTSRdd = ...
// A TimeSeriesRDD with columns "time" and "price"
// time  price
// -----------
// 1000L 1.0
// 1500L 2.0
// 2000L 3.0
// 2500L 4.0

val clockTSRdd = ...
// A TimeSeriesRDD with only column "time"
// time
// -----
// 1000L
// 2000L
// 3000L

val results = priceTSRdd.groupByInterval(clockTSRdd)
// time  rows
// ----------------------------------
// 1000L [[1000L, 1.0], [1500L, 2.0]]
// 2000L [[2000L, 3.0], [2500L, 4.0]]
  • addWindows For each row, this function adds a new column whose value for a row is a list of rows within its window.
val priceTSRdd = ...
// A TimeSeriesRDD with columns "time" and "price"
// time  price
// -----------
// 1000L 1.0
// 1500L 2.0
// 2000L 3.0
// 2500L 4.0

val result = priceTSRdd.addWindows(Window.pastAbsoluteTime("1000ns"))
// time  price window_past_1000ns
// ------------------------------------------------------
// 1000L 1.0   [[1000L, 1.0]]
// 1500L 2.0   [[1000L, 1.0], [1500L, 2.0]]
// 2000L 3.0   [[1000L, 1.0], [1500L, 2.0], [2000L, 3.0]]
// 2500L 4.0   [[1500L, 2.0], [2000L, 3.0], [2500L, 4.0]]

Temporal Join Functions

A temporal join function is a join function defined by a matching criteria over time. A tolerance in temporal join matching criteria specifies how much it should look past or look futue.

  • leftJoin A function performs the temporal left-join to the right TimeSeriesRDD, i.e. left-join using inexact timestamp matches. For each row in the left, append the most recent row from the right at or before the same time. An example to join two TimeSeriesRDDs is as follows.
val leftTSRdd = ...
val rightTSRdd = ...
val result = leftTSRdd.leftJoin(rightTSRdd, tolerance = "1day")
  • futureLeftJoin A function performs the temporal future left-join to the right TimeSeriesRDD, i.e. left-join using inexact timestamp matches. For each row in the left, appends the closest future row from the right at or after the same time.
val result = leftTSRdd.futureLeftJoin(rightTSRdd, tolerance = "1day")

Summarize Functions

Summarize functions are the functions to apply summarizer(s) to rows within a certain period, like cycle, interval, windows, etc.

  • summarizeCycles A function computes aggregate statistics of rows that are within a cycle, i.e. rows share a timestamp.
val volTSRdd = ...
// A TimeSeriesRDD with columns "time", "id", and "volume"
// time  id volume
// ------------
// 1000L 1  100
// 1000L 2  200
// 2000L 1  300
// 2000L 2  400

val result = volTSRdd.summarizeCycles(Summary.sum("volume"))
// time  volume_sum
// ----------------
// 1000L 300
// 2000L 700

Similarly, we could summarize over intervals, windows, or the whole time series data set. See

  • summarizeIntervals
  • summarizeWindows
  • addSummaryColumns

One could check timeseries.summarize.summarizer for different kinds of summarizer(s), like ZScoreSummarizer, CorrelationSummarizer, NthCentralMomentSummarizer etc.

Contributing

In order to accept your code contributions, please fill out the appropriate Contributor License Agreement in the cla folder and submit it to tsos@twosigma.com.

Download Details:
Author: twosigma
Source Code: https://github.com/twosigma/flint
License: Apache-2.0 License

#database #scala #apachespark 

Flint: A Time Series Library for Apache Spark
Enoch Barcenas

Enoch Barcenas

1646808143

PySpark Tutorial for Beginners

PySpark is an interface for Apache Spark in Python. It not only allows you to write Spark applications using Python APIs, but also provides the PySpark shell for interactively analyzing your data in a distributed environment. PySpark supports most of Spark’s features such as Spark SQL, DataFrame, Streaming, MLlib (Machine Learning) and Spark Core.
 

1 - Installation & Configuration
This video will show you how to install and configure Apache Spark on a Linux machine.
Notice that in newer versions of Spark, "Slave" has been replaces by "Worker".

2 - Interacting with Apache Spark Cluster 
You will learn the general rules on how to interact with an Apache Spark cluster.

3 - Reading in Data
You will learn how to read in different types of data into Apache Spark with pySpark.

4 - Select, Filter, and Sort
You will learn about the most basic operators of pySpark. You will be able to select columns, filter rows and sort your dataframe.

5 - Aggregation 
You will learn how to aggregate your dataframe.

6 - Functions 
You will learn how to apply functions to your data. With these functions, you can create new or change existing columns in your dataframe

7 - Join, Union, and Pivot 
You will learn how to join, union, and pivot your dataframes.

8 - User Defined Functions, Pandas, and Collect 
You will learn how to wrangle your data if pySpark has no solution out of the box.

9 - Writing Data 
You will learn how to write your Spark dataframes.

#pyspark #python #apachespark

PySpark Tutorial for Beginners
Felix Kling

Felix Kling

1646807855

Getting Started with Hadoop & Apache Spark

Getting Started with Hadoop & Apache Spark

1 - Installing Debian

In this video we are installing Debian which we will use as an operating system to run a Hadoop and Apache Spark pseudo cluster.
This video covers creating a Virtual Machine in Windows, Downloading & Installing Debian, and the absolute basics of working with Linux.

2 - Downloading Hadoop
Here we will download Hadoop to our newly configured Virtual Machine. We will extract it and check whether it just works out of the box.

3 - Configuring Hadoop
After downloading and installing Hadoop we are going to configure it. After all configurations are done, we will have a working pseudo cluster for HDFS.

4 - Configuring YARN
After configuring our HDFS, we now want to configure a resource manager (YARN) to manage our pseudo cluster. For this we will adjust quite a few configurations. 
You can download my config file via the following link: https://drive.google.com/file/d/11FL12RHSAug_aQtvaG4r2KJP1RhMw3Pk/view

5 - Interacting with HDFS
After making all the configurations we can finally fire up our Hadoop cluster and start interacting with it. We will learn how to interact with HDFS such as listing the content and uploading data to it.

6 - Installing & Configuring Spark
After we are done configuring our HDFS, it is now time to get a good computation engine. For this we will download and configure Apache Spark.

7 - Loading Data into Spark
Having a running Spark pseudo cluster, we now want to load data from HDFS into a Spark data frame

8 - Running SQL Queries in Spark
Let us learn how to run typical SQL queries in Apache Spark. This includes selecting columns, filtering rows, joining tables, and creating new columns from existing ones.

9 - Save Data from Spark to HDFS
In the last video of this series we will save our Spark data frame into a Parquet file on HDFS.

#hadoop #apachespark #bigdata

Getting Started with Hadoop & Apache Spark
Karim Aya

Karim Aya

1559750657

Integrating Kafka With Spark Structured Streaming

Learn the method to integrate Kafka with Spark for consuming streaming data amd discover how to unleash your streaming analytics needs

Kafka is a messaging broker system that facilitates the passing of messages between producer and consumer. On the other hand, Spark Structure streaming consumes static and streaming data from various sources (like Kafka, Flume, Twitter, etc.) that can be processed and analyzed using a high-level algorithm for Machine Learning and pushes the result out to an external storage system. The main advantage of structured streaming is to get continuous incrementing of the result as the streaming data continue to arrive.

Kafka has its own stream library and is best for transforming Kafka topic-to-topic whereas Spark streaming can be integrated with almost any type of system. For more detail, you can refer to this blog.

In this blog, I’ll cover an end-to-end integration of Kafka with Spark structured streaming by creating Kafka as a source and Spark structured streaming as a sink.

Let’s create a Maven project and add following dependencies in pom.xml.

 <dependency>
     <groupId>org.apache.spark</groupId>
     <artifactId>spark-core_2.11</artifactId>
     <version>2.1.1</version>
 </dependency>
 <dependency>
     <groupId>org.apache.spark</groupId>
     <artifactId>spark-sql_2.11</artifactId>
     <version>2.1.1</version>
 </dependency>
 <dependency>
     <groupId>org.apache.kafka</groupId>
     <artifactId>kafka-clients</artifactId>
     <version>0.10.2.0</version>
 </dependency>
<dependency>
     <groupId>org.apache.spark</groupId>
     <artifactId>spark-streaming-kafka_2.10</artifactId>
     <version>1.6.3</version>
 </dependency>

Now, we will be creating a Kafka producer that produces messages and pushes them to the topic. The consumer will be the Spark structured streaming DataFrame.

First, setting the properties for the Kafka producer.

val props = new Properties()
props.put("bootstrap.servers", "localhost:9092")
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")

bootstrap.servers: This contains the full list of servers with hostname and port. The list should be in the form of host1: port, host2: port , and so on.

  •  

key.serializer: Serializer class for the key that implements serializer interface.

  •  

value.serializer: Serializer class for the key that implements the serializer interface.

Creating a Kafka producer and sending topic over the stream:

val producer = new KafkaProducer[String,String](props)
for(count <- 0 to 10) 
  producer.send(new ProducerRecord[String, String](topic, "title "+count.toString,"data from topic"))
println("Message sent successfully")
producer.close()

The send is asynchronous, and this method will return immediately once the record has been stored in the buffer of records waiting to be sent. This allows sending many records in parallel without blocking to wait for the response after each one. The result of the send is a RecordMetadata specifying the partition the record was sent to and the offset it was assigned. After sending the data, close the producer using the close method.

Kafka as a Source 

Now, Spark will be a consumer of streams produced by Kafka. For this, we need to create a Spark session.

val spark = SparkSession
  .builder
  .appName("sparkConsumer")
  .config("spark.master", "local")
  .getOrCreate()

This is getting the topics from Kafka and reading it in Spark stream by subscribing to a particular topic that is to be provided in option. Following is the code to subscribe Kafka topics in Spark stream and read it using readstream.

val dataFrame = spark
  .readStream
  .format("kafka")
  .option("kafka.bootstrap.servers", "localhost:9092")
  .option("subscribe", "mytopic")
  .load()

Printing the schema of the DataFrame:

 ds1.printSchema()

The output for the schema includes all the fields related to Kafka metadata.

root
 |-- key: binary (nullable = true)
 |-- value: binary (nullable = true)
 |-- topic: string (nullable = true)
 |-- partition: integer (nullable = true)
 |-- offset: long (nullable = true)
 |-- timestamp: timestamp (nullable = true)
 |-- timestampType: integer (nullable = true)

Create a dataset from DataFrame by casting the key and value from the topic as a string:

val dataSet: Dataset[(String, String)] =dataFrame.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
.as[(String, String)]

Write the data in the dataset to the console and hold the program from exit using the method awaitTermination:

val query: StreamingQuery = dataSet.writeStream
 .outputMode("append")
 .format("console")
 .start()
 query.awaitTermination()

The complete code is on my GitHub.

 

#bigdata #apachespark #kafka 

Integrating Kafka With Spark Structured Streaming