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 entry point for SparkSQL functionality. 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.
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) |
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. |
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 can be used only on the key-value pair, and then it generates SequenceFile and writes the file to 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.
Common methods of Spark Streaming are the same as those of Spark Core. The following table describes some special Spark Streaming methods.
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 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.
Method |
Description |
---|---|
collect() |
Returns an array containing all the columns of a DataFrame. |
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. |
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. |
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot