Updated on 2024-08-10 GMT+08:00

Spark Python APIs

To avoid API compatibility or reliability issues after updates to the open-source Spark, it is advisable to use APIs of the version you are currently using.

Common Spark Core APIs

Spark mainly uses the following classes:

  • pyspark.SparkContext: external API of Spark. It provides the functions of Spark for Python applications that invoke this class, for example, connecting Spark clusters, creating RDDs, and broadcasting variables.
  • pyspark.SparkConf: Spark application configuration class. It is used to set an application name, execution mode, and executor memory.
  • pyspark.RDD: defines the RDD class in the Spark application. The class provides the data collection operation methods, such as map and filter.
  • pyspark.Broadcast: broadcast variable class. This class retains one read-only variable, and caches it on each machine, instead of saving a copy for each task.
  • pyspark.StorageLevel: data storage levels, including memory (MEMORY_ONLY), disk (DISK_ONLY), and memory+disk (MEMORY_AND_DISK).
  • pyspark.sql.SQLContext: main entrance of the SparkSQL functions. It can be used to create DataFrame, register DataFrame as a table, and execute SQL on a table.
  • pyspark.sql.DataFrame: distributed dataset. DataFrame is equivalent to a relationship table in Spark SQL and can be created using the method in SQLContext.
  • pyspark.sql.DataFrameNaFunctions: function in DataFrame for processing data loss.
  • pyspark.sql.DataFrameStatFunctions: function in DataFrame for statistics. It calculates the variance between columns and sample covariance.
RDD supports two types of operations: transformation and action. Table 1 and Table 2 describe their common methods.
Table 1 Transformation

Method

Description

map(f, preservesPartitioning=False)

Returns a new RDD by applying a function to all elements of this RDD.

filter(f)

Invokes the Func method for all RDD elements to generate a satisfied dataset that is returned in the form of RDD.

flatMap(f, preservesPartitioning=False)

Returns a new RDD by first applying a function to all elements of this RDD, and then flattening the results.

sample(withReplacement, fraction, seed=None)

Returns a sampled subset of this RDD.

union(rdds)

Returns a new RDD, contains source RDD and the group of RDD's elements.

distinct([numPartitions: Int]): RDD[T]

Returns a new RDD containing the distinct elements in this RDD.

groupByKey(): RDD[(K, Iterable[V])]

Returns (K,Iterable[V]) and combines the values of the same key to a set.

reduceByKey(func, numPartitions=None)

Invokes Func on the values of the same key.

sortByKey(ascending=True, numPartitions=None, keyfunc=function <lambda>)

Sorts by key in ascending or descending order. Ascending is of the boolean type.

join(other, numPartitions)

Returns the dataset of (K,(V,W)) when the (K,V) and (K,W) datasets exist. numPartitions indicates the number of concurrent tasks.

cogroup(other, numPartitions)

Returns the dataset of (K, (Iterable[V], Iterable[W])) when the (K,V) and (K,W) datasets of two key-value pairs exist. numPartitions indicates the number of concurrent tasks.

cartesian(other)

Returns the Cartesian product of the RDD and other RDDs.

Table 2 Action

API

Description

reduce(f)

Invokes Func on elements of the RDD.

collect()

Returns an array that contains all of the elements in this RDD.

count()

Returns the number of elements in the dataset.

first()

Returns the first element in the dataset.

take(num)

Returns the first num elements.

takeSample(withReplacement, num, seed)

Samples the dataset randomly and returns a dataset of num elements. withReplacement indicates whether replacement is used.

saveAsTextFile(path, compressionCodecClass)

Writes the dataset to a text file, HDFS, or file system supported by HDFS. Spark converts each record to a row of records and then writes it to the file.

saveAsSequenceFile(path, compressionCodecClass=None)

This API is limited to key-value pairs and creates a SequenceFile that can be saved to either the local or Hadoop file system.

countByKey()

Counts the appearance times of each key.

foreach(func)

Applies a function f to all elements of this RDD.

countByValue()

Counts the times that each value of the RDD occurs.

Common Spark Streaming APIs

Spark Streaming mainly uses the following classes:

  • pyspark.streaming.StreamingContext: main entrance of Spark Streaming. It provides methods for creating the DStream. A batch interval needs to be set in the input parameter.
  • pyspark.streaming.DStream: a type of data which indicates the RDDs continuous sequence. It indicates the continuous data flow.
  • dstream.PariDStreamFunctions: DStream of key-value, common operations are groupByKey and reduceByKey.

    The Java APIs of the Spark Streaming are JavaStreamingContext, JavaDStream, and JavaPairDStream.

The techniques used in Spark Streaming are comparable to those in Spark Core. Check out the table below for some examples of Spark Streaming methods.

Table 3 Common Spark Streaming APIs

Method

Description

socketTextStream(hostname, port, storageLevel)

Creates an input stream from the TCP source host:port.

start()

Starts the Spark Streaming computing.

awaitTermination(timeout)

Terminates the await of the process, which is similar to pressing Ctrl+C.

stop(stopSparkContext, stopGraceFully)

Stops Spark Streaming computing. stopSparkContext is used to determine whether SparkContext needs to be terminated. StopGracefully is used to determine whether to wait for all the received data to be processed.

UpdateStateByKey(func)

Updates the status of DStream. To use this method, you need to define the state and state update functions.

window(windowLength, slideInterval)

Generates a new DStream by batch calculating according to the window of the source DStream.

countByWindow(windowLength, slideInterval)

Returns the number of sliding window elements in the stream.

reduceByWindow(func, windowLength, slideInterval)

When the key-value pair of DStream is invoked, a new key-value pair of DStream is returned. The value of each key is obtained by aggregating the reduce function in batches in the sliding window.

join(other,numPartitions)

Performs a join operation between different Spark Streamings.

Common Spark SQL APIs

Spark SQL mainly uses the following classes:

  • pyspark.sql.SQLContext: main entrance of Spark SQL functions and DataFrame.
  • pyspark.sql.DataFrame: distributed dataset organized by naming columns.
  • pyspark.sql.HiveContext: main entrance for obtaining data stored in Hive.
  • pyspark.sql.DataFrameStatFunctions: some statistics functions.
  • pyspark.sql.functions: functions embedded in DataFrame.
  • pyspark.sql.Window: window function provided by SQL.
Table 4 Common actions of Spark SQL

Method

Description

collect()

Returns an array containing all DataFrame columns.

count()

Returns the number of DataFrame rows.

describe()

Counts the statistic information, including the counting, average value, standard deviation, minimum value and maximum value.

first()

Returns the first row.

head(n)

Returns the first n rows.

show()

Displays DataFrame in a table.

take(num)

Returns the first num rows in DataFrame.

Table 5 Basic DataFrame functions

Method

Description

explain()

Prints the logical plan and physical plan of the SQL.

printSchema()

Prints the schema information to the console.

registerTempTable(name)

Registers the DataFrame as a temporary table, whose period is bound to the SQLContext.

toDF()

Returns a DataFrame whose columns are renamed.