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

Spark Python APIs

To avoid API compatibility or reliability problems, you are advised to use open source APIs of the corresponding version.

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 SparkSQL 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)

Uses the Func method to generate a new RDD for each element in the RDD that invokes map.

filter(f)

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

flatMap(f, preservesPartitioning=False)

Invokes the Func method for all RDD elements and then flattens the results to generate a new RDD.

sample(withReplacement, fraction, seed=None)

Samples and returns a subset of RDD.

union(rdds)

Returns a new RDD that contains a set of elements of the source RDD and the specified RDD.

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

Deletes duplicate elements to generate a new 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

Method

Description

reduce(f)

Invokes Func on elements of the RDD.

collect()

Returns an array that contains all elements of the 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 can be used only on the key-value pair, and then generates SequenceFile and writes is to the local or Hadoop file system.

countByKey()

Counts the times that each key occurs.

foreach(func)

Runs the function on each element of the dataset.

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 the key-value pair. Common operations include groupByKey and reduceByKey.

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

The common methods of Spark Streaming are similar to those of Spark Core. The following table provides some methods of Spark Streaming.

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 Streaming calculation.

awaitTermination(timeout)

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

stop(stopSparkContext, stopGraceFully)

Stops the Streaming calculation. 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 in Python:

  • 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 the columns of DataFrame.

count()

Returns the number of rows in DataFrame.

describe()

Calculates the statistics, including the count, 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 statement.

printSchema()

Prints schema information to the console.

registerTempTable(name)

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

toDF()

Returns a DataFrame whose columns are renamed.