Sparksql PDF
Sparksql PDF
Sparksql PDF
pyspark.sql module
Module Context
Important classes of Spark SQL and DataFrames:
A SparkSession can be used create DataFrame, register DataFrame as tables, execute SQL over
tables, cache tables, and read parquet files. To create a SparkSession, use the following builder
pattern:
class Builder
Builder for SparkSession.
appName(name)
Sets a name for the application, which will be shown in the Spark web UI.
enableHiveSupport()
Enables Hive support, including connectivity to a persistent Hive metastore, support for
Hive serdes, and Hive user-defined functions.
getOrCreate()
Gets an existing SparkSession or, if there is no existing one, creates a new one based
on the options set in this builder.
This method first checks whether there is a valid global default SparkSession, and if yes,
return that one. If no valid global default SparkSession exists, the method creates a new
SparkSession and assigns the newly created SparkSession as the global default.
In case an existing SparkSession is returned, the config options specified in this builder
will be applied to the existing SparkSession.
master(master)
Sets the Spark master URL to connect to, such as “local” to run locally, “local[4]” to run
locally with 4 cores, or “spark://master:7077” to run on a Spark standalone cluster.
SparkSession.catalog
Interface through which the user may create, drop, alter or query underlying databases,
tables, functions etc.
SparkSession.conf
This is the interface through which the user can get and set all Spark and Hadoop
configurations that are relevant to Spark SQL. When getting the value of a config, this defaults
to the value set in the underlying SparkContext, if any.
When schema is a list of column names, the type of each column will be inferred from data.
When schema is None, it will try to infer the schema (column names and types) from data,
which should be an RDD of Row, or namedtuple, or dict.
If schema inference is needed, samplingRatio is used to determined the ratio of rows used
for schema inference. The first row will be used if samplingRatio is None.
Parameters: data – an RDD of any kind of SQL data representation(e.g. row, tuple, int,
boolean, etc.), or list, or pandas.DataFrame.
schema – a pyspark.sql.types.DataType or a datatype string or a list of
column names, default is None. The data type string format equals to
pyspark.sql.types.DataType.simpleString, except that top level struct
type can omit the struct<> and atomic types use typeName() as their
format, e.g. use byte instead of tinyint for
pyspark.sql.types.ByteType. We can also use int as a short name for
IntegerType.
samplingRatio – the sample ratio of rows used for inferring
verifySchema – verify data types of every row against schema.
Returns: DataFrame
SparkSession.newSession()
Returns a new SparkSession as new session, that has separate SQLConf, registered
temporary views and UDFs, but shared SparkContext and table cache.
SparkSession.read
Returns: DataFrameReader
SparkSession.readStream
Note: Evolving.
Returns: DataStreamReader
SparkSession.sparkContext
SparkSession.sql(sqlQuery)
Returns: DataFrame
SparkSession.stop()
SparkSession.streams
Note: Evolving.
Returns: StreamingQueryManager
SparkSession.table(tableName)
Returns: DataFrame
SparkSession.udf
Returns: UDFRegistration
SparkSession.version
As of Spark 2.0, this is replaced by SparkSession. However, we are keeping the class here for
backward compatibility.
A SQLContext can be used create DataFrame, register DataFrame as tables, execute SQL over
tables, cache tables, and read parquet files.
cacheTable(tableName)
Caches the specified table in-memory.
clearCache()
Removes all cached tables from the in-memory cache.
When schema is a list of column names, the type of each column will be inferred from data.
When schema is None, it will try to infer the schema (column names and types) from data,
which should be an RDD of Row, or namedtuple, or dict.
If schema inference is needed, samplingRatio is used to determined the ratio of rows used
for schema inference. The first row will be used if samplingRatio is None.
Parameters: data – an RDD of any kind of SQL data representation(e.g. Row, tuple,
int, boolean, etc.), or list, or pandas.DataFrame.
schema – a pyspark.sql.types.DataType or a datatype string or a list of
column names, default is None. The data type string format equals to
pyspark.sql.types.DataType.simpleString, except that top level struct
type can omit the struct<> and atomic types use typeName() as their
format, e.g. use byte instead of tinyint for
pyspark.sql.types.ByteType. We can also use int as a short name for
pyspark.sql.types.IntegerType.
samplingRatio – the sample ratio of rows used for inferring
verifySchema – verify data types of every row against schema.
Returns: DataFrame
The data source is specified by the source and a set of options. If source is not specified,
the default data source configured by spark.sql.sources.default will be used.
Optionally, a schema can be provided as the schema of the returned DataFrame and created
external table.
Returns: DataFrame
dropTempTable(tableName)
Remove the temp table from catalog.
getConf(key, defaultValue=None)
Returns the value of Spark SQL configuration property for the given key.
If the key is not set and defaultValue is not None, return defaultValue. If the key is not set and
defaultValue is None, return the system default value.
classmethod getOrCreate(sc)
Get the existing SQLContext or create a new one with given SparkContext.
Parameters: sc – SparkContext
newSession()
Returns a new SQLContext as new session, that has separate SQLConf, registered
temporary views and UDFs, but shared SparkContext and table cache.
read
Returns a DataFrameReader that can be used to read data in as a DataFrame.
Returns: DataFrameReader
readStream
Returns a DataStreamReader that can be used to read data streams as a streaming
DataFrame.
Note: Evolving.
Returns: DataStreamReader
registerDataFrameAsTable(df, tableName)
Registers the given DataFrame as a temporary table in the catalog.
Temporary tables exist only during the lifetime of this instance of SQLContext.
registerFunction(name, f, returnType=StringType)
Registers a python function (including lambda function) as a UDF so it can be used in SQL
statements.
In addition to a name and the function itself, the return type can be optionally specified. When
the return type is not given it default to a string and conversion will automatically be done. For
any other return type, the produced object must match the specified type.
())
In addition to a name and the function itself, the return type can be optionally specified. When
the return type is not specified we would infer it via reflection. :param name: name of the UDF
:param javaClassName: fully qualified name of java class :param returnType: a
pyspark.sql.types.DataType object
setConf(key, value)
Sets the given Spark SQL configuration property.
sql(sqlQuery)
Returns a DataFrame representing the result of the given query.
Returns: DataFrame
streams
Returns a StreamingQueryManager that allows managing all the StreamingQuery
StreamingQueries active on this context.
Note: Evolving.
table(tableName)
Returns the specified table or view as a DataFrame.
Returns: DataFrame
tableNames(dbName=None)
Returns a list of names of tables in the database dbName.
Parameters: dbName – string, name of the database to use. Default to the current
database.
Returns: list of table names, in string
tables(dbName=None)
Returns a DataFrame containing names of tables in the given database.
The returned DataFrame has two columns: tableName and isTemporary (a column with
BooleanType indicating if a table is a temporary one or not).
udf
Returns a UDFRegistration for UDF registration.
Returns: UDFRegistration
uncacheTable(tableName)
Removes the specified table from the in-memory cache.
Configuration for Hive is read from hive-site.xml on the classpath. It supports running both SQL
and HiveQL commands.
refreshTable(tableName)
Invalidate and refresh all the cached the metadata of the given table. For performance
reasons, Spark SQL or the external data source library it uses might cache certain metadata
about a table, such as the location of blocks. When those change outside of Spark SQL, users
should call this function to invalidate the cache.
class pyspark.sql.UDFRegistration(sqlContext)
Wrapper for user-defined function registration.
register(name, f, returnType=StringType)
Registers a python function (including lambda function) as a UDF so it can be used in SQL
statements.
In addition to a name and the function itself, the return type can be optionally specified. When
the return type is not given it default to a string and conversion will automatically be done. For
any other return type, the produced object must match the specified type.
())
A DataFrame is equivalent to a relational table in Spark SQL, and can be created using various
functions in SQLContext:
Once created, it can be manipulated using the various domain-specific-language (DSL) functions
defined in: DataFrame, Column.
To select a column from the data frame, use the apply method:
agg(*exprs)
Aggregate on the entire DataFrame without groups (shorthand for df.groupBy.agg()).
alias(alias)
Returns a new DataFrame with an alias set.
The result of this algorithm has the following deterministic bound: If the DataFrame has N
elements and if we request the quantile at probability p up to error err, then the algorithm will
return a sample x from the DataFrame so that the exact rank of x is close to (p * N). More
precisely,
This method implements a variation of the Greenwald-Khanna algorithm (with some speed
optimizations). The algorithm was first present in [[http://dx.doi.org/10.1145/375663.375670
Space-efficient Online Computation of Quantile Summaries]] by Greenwald and Khanna.
Note that null values will be ignored in numerical columns before calculation. For columns
only containing null values, an empty list is returned.
Parameters: col – str, list. Can be a single column name, or a list of names for multiple
columns.
probabilities – a list of quantile probabilities Each number must belong to
[0, 1]. For example 0 is the minimum, 0.5 is the median, 1 is the maximum.
relativeError – The relative target precision to achieve (>= 0). If set to
zero, the exact quantiles are computed, which could be very expensive.
Note that values greater than 1 are accepted but give the same result as
1.
Returns: the approximate quantiles at the given probabilities. If the input col is a
string, the output is a list of floats. If the input col is a list or tuple of strings,
the output is also a list, but each element in it is a list of floats, i.e., the output
is a list of list of floats.
cache()
Persists the DataFrame with the default storage level (MEMORY_AND_DISK).
Note: The default storage level has changed to MEMORY_AND_DISK to match Scala in 2.0.
checkpoint(eager=True)
Returns a checkpointed version of this Dataset. Checkpointing can be used to truncate the
logical plan of this DataFrame, which is especially useful in iterative algorithms where the plan
may grow exponentially. It will be saved to files inside the checkpoint directory set with
SparkContext.setCheckpointDir().
Note: Experimental
coalesce(numPartitions)
Returns a new DataFrame that has exactly numPartitions partitions.
Similar to coalesce defined on an RDD, this operation results in a narrow dependency, e.g. if
you go from 1000 partitions to 100 partitions, there will not be a shuffle, instead each of the
100 new partitions will claim 10 of the current partitions. If a larger number of partitions is
requested, it will stay at the current number of partitions.
However, if you’re doing a drastic coalesce, e.g. to numPartitions = 1, this may result in your
computation taking place on fewer nodes than you like (e.g. one node in the case of
numPartitions = 1). To avoid this, you can call repartition(). This will add a shuffle step, but
means the current upstream partitions will be executed in parallel (per whatever the current
partitioning is).
collect()
Returns all the records as a list of Row.
columns
Returns all column names as a list.
count()
Returns the number of rows in this DataFrame.
cov(col1, col2)
Calculate the sample covariance for the given columns, specified by their names, as a double
value. DataFrame.cov() and DataFrameStatFunctions.cov() are aliases.
createGlobalTempView(name)
Creates a global temporary view with this DataFrame.
The lifetime of this temporary view is tied to this Spark application. throws
TempTableAlreadyExistsException, if the view name already exists in the catalog.
createOrReplaceGlobalTempView(name)
Creates or replaces a global temporary view using the given name.
createOrReplaceTempView(name)
Creates or replaces a local temporary view with this DataFrame.
The lifetime of this temporary table is tied to the SparkSession that was used to create this
DataFrame.
createTempView(name)
Creates a local temporary view with this DataFrame.
The lifetime of this temporary table is tied to the SparkSession that was used to create this
DataFrame. throws TempTableAlreadyExistsException, if the view name already exists in
the catalog.
crossJoin(other)
Returns the cartesian product with another DataFrame.
crosstab(col1, col2)
Computes a pair-wise frequency table of the given columns. Also known as a contingency
table. The number of distinct values for each column should be less than 1e4. At most 1e6
non-zero pair frequencies will be returned. The first column of each row will be the distinct
values of col1 and the column names will be the distinct values of col2. The name of the first
column will be $col1_$col2. Pairs that have no occurrences will have zero as their counts.
DataFrame.crosstab() and DataFrameStatFunctions.crosstab() are aliases.
Parameters: col1 – The name of the first column. Distinct items will make the first item
of each row.
col2 – The name of the second column. Distinct items will make the
column names of the DataFrame.
cube(*cols)
Create a multi-dimensional cube for the current DataFrame using the specified columns, so
we can run aggregation on them.
describe(*cols)
Computes statistics for numeric and string columns.
This include count, mean, stddev, min, and max. If no columns are given, this function
computes statistics for all numerical or string columns.
Note: This function is meant for exploratory data analysis, as we make no guarantee
about the backward compatibility of the schema of the resulting DataFrame.
distinct()
Returns a new DataFrame containing the distinct rows in this DataFrame.
drop(*cols)
Returns a new DataFrame that drops the specified column. This is a no-op if schema doesn’t
contain the given column name(s).
Parameters: cols – a string name of the column to drop, or a Column to drop, or a list of
string name of the columns to drop.
dropDuplicates(subset=None)
Return a new DataFrame with duplicate rows removed, optionally only considering certain
columns.
For a static batch DataFrame, it just drops duplicate rows. For a streaming DataFrame, it will
keep all data across triggers as intermediate state to drop duplicates rows. You can use
withWatermark() to limit how late the duplicate data can be and system will accordingly limit
the state. In addition, too late data older than watermark will be dropped to avoid any
possibility of duplicates.
drop_duplicates(subset=None)
drop_duplicates() is an alias for dropDuplicates().
Parameters: how – ‘any’ or ‘all’. If ‘any’, drop a row if it contains any nulls. If ‘all’, drop a
row only if all its values are null.
thresh – int, default None If specified, drop rows that have less than
thresh non-null values. This overwrites the how parameter.
subset – optional list of column names to consider.
dtypes
Returns all column names and their data types as a list.
explain(extended=False)
Prints the (logical and physical) plans to the console for debugging purpose.
Parameters: extended – boolean, default False. If False, prints only the physical plan.
fillna(value, subset=None)
Replace null values, alias for na.fill(). DataFrame.fillna() and
DataFrameNaFunctions.fill() are aliases of each other.
Parameters: value – int, long, float, string, or dict. Value to replace null values with. If
the value is a dict, then subset is ignored and value must be a mapping
from column name (string) to replacement value. The replacement value
must be an int, long, float, boolean, or string.
subset – optional list of column names to consider. Columns specified in
subset that do not have matching data type are ignored. For example, if
value is a string, and subset contains a non-string column, then the non-
string column is simply ignored.
filter(condition)
Filters rows using the given condition.
first()
Returns the first row as a Row.
foreach(f)
Applies the f function to all Row of this DataFrame.
foreachPartition(f)
Applies the f function to each partition of this DataFrame.
freqItems(cols, support=None)
Finding frequent items for columns, possibly with false positives. Using the frequent element
count algorithm described in “http://dx.doi.org/10.1145/762471.762473, proposed by Karp,
Schenker, and Papadimitriou”. DataFrame.freqItems() and
DataFrameStatFunctions.freqItems() are aliases.
Note: This function is meant for exploratory data analysis, as we make no guarantee
Parameters: cols – Names of the columns to calculate frequent items for as a list or
tuple of strings.
support – The frequency with which to consider an item ‘frequent’. Default
is 1%. The support must be greater than 1e-4.
groupBy(*cols)
Groups the DataFrame using the specified columns, so we can run aggregation on them. See
GroupedData for all the available aggregate functions.
Parameters: cols – list of columns to group by. Each element should be a column name
(string) or an expression (Column).
groupby(*cols)
groupby() is an alias for groupBy().
head(n=None)
Returns the first n rows.
Note: This method should only be used if the resulting array is expected to be small, as
all the data is loaded into the driver’s memory.
hint(name, *parameters)
Specifies some hint on the current DataFrame.
intersect(other)
Return a new DataFrame containing rows only in both this frame and another frame.
isLocal()
Returns True if the collect() and take() methods can be run locally (without any Spark
executors).
isStreaming
Returns true if this Dataset contains one or more sources that continuously return data as it
arrives. A Dataset that reads data from a streaming source must be executed as a
StreamingQuery using the start() method in DataStreamWriter. Methods that return a
single answer, (e.g., count() or collect()) will throw an AnalysisException when there is
a streaming source present.
Note: Evolving
on – a string for the join column name, a list of column names, a join
expression (Column), or a list of Columns. If on is a string or a list of
strings indicating the name of the join column(s), the column(s) must exist
on both sides, and this performs an equi-join.
how – str, default inner. Must be one of: inner, cross, outer, full,
full_outer, left, left_outer, right, right_outer, left_semi, and
left_anti.
The following performs a full outer join between df1 and df2.
limit(num)
Limits the result count to the number specified.
na
Returns a DataFrameNaFunctions for handling missing values.
orderBy(*cols, **kwargs)
Note: The default storage level has changed to MEMORY_AND_DISK to match Scala in 2.0.
printSchema()
Prints out the schema in the tree format.
randomSplit(weights, seed=None)
Randomly splits this DataFrame with the provided weights.
Parameters: weights – list of doubles as weights with which to split the DataFrame.
Weights will be normalized if they don’t sum up to 1.0.
rdd
Returns the content as an pyspark.RDD of Row.
registerTempTable(name)
Registers this RDD as a temporary table using the given name.
The lifetime of this temporary table is tied to the SQLContext that was used to create this
DataFrame.
repartition(numPartitions, *cols)
Returns a new DataFrame partitioned by the given partitioning expressions. The resulting
DataFrame is hash partitioned.
Changed in version 1.6: Added optional arguments to specify the partitioning columns. Also
made numPartitions optional if partitioning columns are specified.
Parameters: to_replace – bool, int, long, float, string, list or dict. Value to be replaced. If
the value is a dict, then value is ignored and to_replace must be a
mapping between a value and a replacement.
value – int, long, float, string, or list. The replacement value must be an
int, long, float, or string. If value is a list, value should be of the same
length and type as to_replace. If value is a scalar and to_replace is a
sequence, then value is used as a replacement for each item in
to_replace.
subset – optional list of column names to consider. Columns specified in
subset that do not have matching data type are ignored. For example, if
value is a string, and subset contains a non-string column, then the non-
string column is simply ignored.
rollup(*cols)
Create a multi-dimensional rollup for the current DataFrame using the specified columns, so
we can run aggregation on them.
Note: This is not guaranteed to provide exactly the fraction specified of the total count of
the given DataFrame.
schema
Returns the schema of this DataFrame as a pyspark.sql.types.StructType.
select(*cols)
Projects a set of expressions and returns a new DataFrame.
Parameters: cols – list of column names (string) or expressions (Column). If one of the
column names is ‘*’, that column is expanded to include all columns in the
current DataFrame.
selectExpr(*expr)
Projects a set of SQL expressions and returns a new DataFrame.
show(n=20, truncate=True)
Prints the first n rows to the console.
sort(*cols, **kwargs)
Returns a new DataFrame sorted by the specified column(s).
sortWithinPartitions(*cols, **kwargs)
Returns a new DataFrame with each partition sorted by the specified column(s).
stat
Returns a DataFrameStatFunctions for statistic functions.
storageLevel
Get the DataFrame‘s current storage level.
subtract(other)
Return a new DataFrame containing rows in this frame but not in another frame.
take(num)
Returns the first num rows as a list of Row.
toDF(*cols)
Returns a new class:DataFrame that with new specified column names
toJSON(use_unicode=True)
Converts a DataFrame into a RDD of string.
Each row is turned into a JSON document as one element in the returned RDD.
toLocalIterator()
Returns an iterator that contains all of the rows in this DataFrame. The iterator will consume
as much memory as the largest partition in this DataFrame.
toPandas()
Returns the contents of this DataFrame as Pandas pandas.DataFrame.
Note: This method should only be used if the resulting Pandas’s DataFrame is expected
to be small, as all the data is loaded into the driver’s memory.
union(other)
Return a new DataFrame containing union of rows in this and another frame.
This is equivalent to UNION ALL in SQL. To do a SQL-style set union (that does deduplication
of elements), use this function followed by a distinct.
Also as standard in SQL, this function resolves columns by position (not by name).
unionAll(other)
Return a new DataFrame containing union of rows in this and another frame.
This is equivalent to UNION ALL in SQL. To do a SQL-style set union (that does deduplication
of elements), use this function followed by a distinct.
Also as standard in SQL, this function resolves columns by position (not by name).
unpersist(blocking=False)
Marks the DataFrame as non-persistent, and remove all blocks for it from memory and disk.
where(condition)
where() is an alias for filter().
withColumn(colName, col)
Returns a new DataFrame by adding a column or replacing the existing column that has the
same name.
withColumnRenamed(existing, new)
Returns a new DataFrame by renaming an existing column. This is a no-op if schema doesn’t
contain the given column name.
withWatermark(eventTime, delayThreshold)
Defines an event time watermark for this DataFrame. A watermark tracks a point in time
before which we assume no more late data is going to arrive.
The current watermark is computed by looking at the MAX(eventTime) seen across all of the
partitions in the query minus a user specified delayThreshold. Due to the cost of coordinating
this value across partitions, the actual watermark used is only guaranteed to be at least
delayThreshold behind the actual event time. In some cases we may still process records that
arrive more than delayThreshold late.
Parameters: eventTime – the name of the column that contains the event time of the
row.
delayThreshold – the minimum delay to wait to data to arrive late, relative
to the latest record that has been processed in the form of an interval (e.g.
“1 minute” or “5 hours”).
Note: Evolving
write
Interface for saving the content of the non-streaming DataFrame out into external storage.
Returns: DataFrameWriter
writeStream
Interface for saving the content of the streaming DataFrame out into external storage.
Note: Evolving.
Returns: DataStreamWriter
Note: Experimental
agg(*exprs)
Compute aggregates and returns the result as a DataFrame.
The available aggregate functions are avg, max, min, sum, count.
If exprs is a single dict mapping from string to string, then the key is the column to perform
aggregation on, and the value is the aggregate function.
Parameters: exprs – a dict mapping from column name (string) to aggregate functions
(string), or a list of Column.
avg(*cols)
Computes average values for each numeric columns for each group.
Parameters: cols – list of column names (string). Non-numeric columns are ignored.
count()
Counts the number of records for each group.
max(*cols)
Computes the max value for each numeric columns for each group.
mean(*cols)
Computes average values for each numeric columns for each group.
Parameters: cols – list of column names (string). Non-numeric columns are ignored.
min(*cols)
Computes the min value for each numeric column for each group.
Parameters: cols – list of column names (string). Non-numeric columns are ignored.
pivot(pivot_col, values=None)
Pivots a column of the current [[DataFrame]] and perform the specified aggregation. There are
two versions of pivot function: one that requires the caller to specify the list of distinct values
to pivot on, and one that does not. The latter is more concise but less efficient, because Spark
needs to first compute the list of distinct values internally.
# Compute the sum of earnings for each year by course with each course as a separate
column
sum(*cols)
Compute the sum for each numeric columns for each group.
Parameters: cols – list of column names (string). Non-numeric columns are ignored.
class pyspark.sql.Column(jc)
A column in a DataFrame.
alias(*alias, **kwargs)
Returns this column aliased with a new name or names (in the case of expressions that return
more than one column, such as explode).
Parameters: alias – strings of desired column names (collects all positional arguments
passed)
metadata – a dict of information to be stored in metadata attribute of the
corresponding :class: StructField (optional, keyword only argument)
asc()
Returns a sort expression based on the ascending order of the given column name.
astype(dataType)
astype() is an alias for cast().
between(lowerBound, upperBound)
A boolean expression that is evaluated to true if the value of this expression is between the
given columns.
bitwiseAND(other)
binary operator
bitwiseOR(other)
binary operator
bitwiseXOR(other)
binary operator
cast(dataType)
Convert the column into type dataType.
contains(other)
binary operator
desc()
Returns a sort expression based on the descending order of the given column name.
endswith(other)
Return a Boolean Column based on matching end of string.
getField(name)
An expression that gets a field by name in a StructField.
getItem(key)
An expression that gets an item at position ordinal out of a list, or gets an item by key out of
a dict.
isNotNull()
True if the current expression is null. Often combined with DataFrame.filter() to select
rows with non-null values.
isNull()
True if the current expression is null. Often combined with DataFrame.filter() to select
rows with null values.
isin(*cols)
A boolean expression that is evaluated to true if the value of this expression is contained by
the evaluated values of the arguments.
like(other)
Return a Boolean Column based on a SQL LIKE match.
name(*alias, **kwargs)
name() is an alias for alias().
otherwise(value)
Evaluates a list of conditions and returns one of multiple possible result expressions. If
Column.otherwise() is not invoked, None is returned for unmatched conditions.
over(window)
Define a windowing column.
rlike(other)
Return a Boolean Column based on a regex match.
startswith(other)
Return a Boolean Column based on a string match.
substr(startPos, length)
Return a Column which is a substring of the column.
when(condition, value)
Evaluates a list of conditions and returns one of multiple possible result expressions. If
Column.otherwise() is not invoked, None is returned for unmatched conditions.
class pyspark.sql.Row
A row in DataFrame. The fields in it can be accessed:
Row can be used to create a row object by using named arguments, the fields will be sorted by
names. It is not allowed to omit a named argument to represent the value is None or missing. This
should be explicitly set to None in this case.
Row also can be used to create another Row like class, then it could be used to create Row
objects, such as
asDict(recursive=False)
Return as an dict
class pyspark.sql.DataFrameNaFunctions(df)
Functionality for working with missing data in DataFrame.
Parameters: how – ‘any’ or ‘all’. If ‘any’, drop a row if it contains any nulls. If ‘all’, drop a
row only if all its values are null.
thresh – int, default None If specified, drop rows that have less than
thresh non-null values. This overwrites the how parameter.
subset – optional list of column names to consider.
fill(value, subset=None)
Replace null values, alias for na.fill(). DataFrame.fillna() and
DataFrameNaFunctions.fill() are aliases of each other.
Parameters: value – int, long, float, string, or dict. Value to replace null values with. If
the value is a dict, then subset is ignored and value must be a mapping
from column name (string) to replacement value. The replacement value
must be an int, long, float, boolean, or string.
subset – optional list of column names to consider. Columns specified in
subset that do not have matching data type are ignored. For example, if
value is a string, and subset contains a non-string column, then the non-
string column is simply ignored.
Parameters: to_replace – bool, int, long, float, string, list or dict. Value to be replaced. If
class pyspark.sql.DataFrameStatFunctions(df)
Functionality for statistic functions with DataFrame.
The result of this algorithm has the following deterministic bound: If the DataFrame has N
elements and if we request the quantile at probability p up to error err, then the algorithm will
return a sample x from the DataFrame so that the exact rank of x is close to (p * N). More
precisely,
This method implements a variation of the Greenwald-Khanna algorithm (with some speed
optimizations). The algorithm was first present in [[http://dx.doi.org/10.1145/375663.375670
Space-efficient Online Computation of Quantile Summaries]] by Greenwald and Khanna.
Note that null values will be ignored in numerical columns before calculation. For columns
only containing null values, an empty list is returned.
Parameters: col – str, list. Can be a single column name, or a list of names for multiple
columns.
probabilities – a list of quantile probabilities Each number must belong to
[0, 1]. For example 0 is the minimum, 0.5 is the median, 1 is the maximum.
relativeError – The relative target precision to achieve (>= 0). If set to
zero, the exact quantiles are computed, which could be very expensive.
Note that values greater than 1 are accepted but give the same result as
1.
Returns: the approximate quantiles at the given probabilities. If the input col is a
string, the output is a list of floats. If the input col is a list or tuple of strings,
the output is also a list, but each element in it is a list of floats, i.e., the output
is a list of list of floats.
cov(col1, col2)
Calculate the sample covariance for the given columns, specified by their names, as a double
value. DataFrame.cov() and DataFrameStatFunctions.cov() are aliases.
crosstab(col1, col2)
Computes a pair-wise frequency table of the given columns. Also known as a contingency
table. The number of distinct values for each column should be less than 1e4. At most 1e6
non-zero pair frequencies will be returned. The first column of each row will be the distinct
values of col1 and the column names will be the distinct values of col2. The name of the first
column will be $col1_$col2. Pairs that have no occurrences will have zero as their counts.
DataFrame.crosstab() and DataFrameStatFunctions.crosstab() are aliases.
Parameters: col1 – The name of the first column. Distinct items will make the first item
of each row.
col2 – The name of the second column. Distinct items will make the
column names of the DataFrame.
freqItems(cols, support=None)
Finding frequent items for columns, possibly with false positives. Using the frequent element
count algorithm described in “http://dx.doi.org/10.1145/762471.762473, proposed by Karp,
Schenker, and Papadimitriou”. DataFrame.freqItems() and
DataFrameStatFunctions.freqItems() are aliases.
Note: This function is meant for exploratory data analysis, as we make no guarantee
about the backward compatibility of the schema of the resulting DataFrame.
Parameters: cols – Names of the columns to calculate frequent items for as a list or
tuple of strings.
support – The frequency with which to consider an item ‘frequent’. Default
is 1%. The support must be greater than 1e-4.
class pyspark.sql.Window
Utility functions for defining window in DataFrames.
For example:
Note: Experimental
currentRow = 0
static orderBy(*cols)
Creates a WindowSpec with the ordering defined.
static partitionBy(*cols)
Creates a WindowSpec with the partitioning defined.
Both start and end are relative from the current row. For example, “0” means “current row”,
while “-1” means one off before the current row, and “5” means the five off after the current
row.
Both start and end are relative positions from the current row. For example, “0” means
“current row”, while “-1” means the row before the current row, and “5” means the fifth row
after the current row.
unboundedFollowing = 9223372036854775807L
unboundedPreceding = -9223372036854775808L
class pyspark.sql.WindowSpec(jspec)
A window specification that defines the partitioning, ordering, and frame boundaries.
Note: Experimental
orderBy(*cols)
Defines the ordering columns in a WindowSpec.
partitionBy(*cols)
rangeBetween(start, end)
Defines the frame boundaries, from start (inclusive) to end (inclusive).
Both start and end are relative from the current row. For example, “0” means “current row”,
while “-1” means one off before the current row, and “5” means the five off after the current
row.
rowsBetween(start, end)
Defines the frame boundaries, from start (inclusive) to end (inclusive).
Both start and end are relative positions from the current row. For example, “0” means
“current row”, while “-1” means the row before the current row, and “5” means the fifth row
after the current row.
class pyspark.sql.DataFrameReader(spark)
Interface used to load a DataFrame from external storage systems (e.g. file systems, key-value
stores, etc). Use spark.read() to access this.
This function will go through the input once to determine the input schema if inferSchema is
enabled. To avoid going through the entire data once, disable inferSchema option or specify
the schema explicitly using schema.
uses the default value, empty string. Since 2.0.1, this nullValue param
applies to all supported types including the string type.
nanValue – sets the string representation of a non-number value. If None
is set, it uses the default value, NaN.
positiveInf – sets the string representation of a positive infinity value. If
None is set, it uses the default value, Inf.
negativeInf – sets the string representation of a negative infinity value. If
None is set, it uses the default value, Inf.
dateFormat – sets the string that indicates a date format. Custom date
formats follow the formats at java.text.SimpleDateFormat. This applies
to date type. If None is set, it uses the default value, yyyy-MM-dd.
timestampFormat – sets the string that indicates a timestamp format.
Custom date formats follow the formats at java.text.SimpleDateFormat.
This applies to timestamp type. If None is set, it uses the default value,
yyyy-MM-dd'T'HH:mm:ss.SSSXXX.
maxColumns – defines a hard limit of how many columns a record can
have. If None is set, it uses the default value, 20480.
maxCharsPerColumn – defines the maximum number of characters
allowed for any given value being read. If None is set, it uses the default
value, -1 meaning unlimited length.
maxMalformedLogPerPartition – this parameter is no longer used since
Spark 2.2.0. If specified, it is ignored.
mode –
allows a mode for dealing with corrupt records during parsing. If None is
set, it uses the default value, PERMISSIVE.
format(source)
Specifies the input data source format.
Parameters: source – string, name of the data source, e.g. ‘json’, ‘parquet’.
Partitions of the table will be retrieved in parallel if either column or predicates is specified.
lowerBound`, ``upperBound and numPartitions is needed when column is specified.
Note: Don’t create too many partitions in parallel on a large cluster; otherwise Spark
might crash your external database systems.
JSON Lines (newline-delimited JSON) is supported by default. For JSON (one record per file),
set the multiLine parameter to true.
If the schema parameter is not specified, this function goes through the input once to
determine the input schema.
Parameters: path – string represents path to the JSON dataset, or a list of paths, or
RDD of Strings storing JSON objects.
schema – an optional pyspark.sql.types.StructType for the input
schema.
primitivesAsString – infers all primitive values as a string type. If None is
set, it uses the default value, false.
prefersDecimal – infers all floating-point values as a decimal type. If the
values do not fit in decimal, then it infers them as doubles. If None is set, it
uses the default value, false.
allowComments – ignores Java/C++ style comment in JSON records. If
None is set, it uses the default value, false.
allowUnquotedFieldNames – allows unquoted JSON field names. If
None is set, it uses the default value, false.
allowSingleQuotes – allows single quotes in addition to double quotes. If
None is set, it uses the default value, true.
allowNumericLeadingZero – allows leading zeros in numbers (e.g.
00012). If None is set, it uses the default value, false.
allowBackslashEscapingAnyCharacter – allows accepting quoting of all
character using backslash quoting mechanism. If None is set, it uses the
default value, false.
mode –
allows a mode for dealing with corrupt records during parsing. If None is
set, it uses the default value, PERMISSIVE.
Parameters: path – optional string or a list of string for file-system backed data
sources.
format – optional string for format of the data source. Default to ‘parquet’.
schema – optional pyspark.sql.types.StructType for the input
schema.
options – all other string options
option(key, value)
Adds an input option for the underlying data source.
options(**options)
Adds input options for the underlying data source.
orc(path)
Loads ORC files, returning the result as a DataFrame.
Note: Currently ORC support is only available together with Hive support.
parquet(*paths)
Loads Parquet files, returning the result as a DataFrame.
You can set the following Parquet-specific option(s) for reading Parquet files:
mergeSchema: sets whether we should merge schemas collected from all Parquet
part-files. This will override spark.sql.parquet.mergeSchema. The default value
is specified in spark.sql.parquet.mergeSchema.
schema(schema)
Specifies the input schema.
Some data sources (e.g. JSON) can infer the input schema automatically from data. By
specifying the schema here, the underlying data source can skip the schema inference step,
and thus speed up data loading.
table(tableName)
Returns the specified table as a DataFrame.
text(paths)
Loads text files and returns a DataFrame whose schema starts with a string column named
“value”, and followed by partitioned columns if there are any.
Each line in the text file is a new row in the resulting DataFrame.
class pyspark.sql.DataFrameWriter(df)
Interface used to write a DataFrame to external storage systems (e.g. file systems, key-value
stores, etc). Use DataFrame.write() to access this.
format(source)
Specifies the underlying output data source.
Parameters: source – string, name of the data source, e.g. ‘json’, ‘parquet’.
insertInto(tableName, overwrite=False)
Inserts the content of the DataFrame to the specified table.
It requires that the schema of the class:DataFrame is the same as the schema of the table.
Note: Don’t create too many partitions in parallel on a large cluster; otherwise Spark
might crash your external database systems.
mode(saveMode)
Specifies the behavior when data or table already exists.
Options include:
option(key, value)
Adds an output option for the underlying data source.
options(**options)
Adds output options for the underlying data source.
Note: Currently ORC support is only available together with Hive support.
partitionBy(*cols)
Partitions the output by the given columns on the file system.
If specified, the output is laid out on the file system similar to Hive’s partitioning scheme.
The data source is specified by the format and a set of options. If format is not specified,
the default data source configured by spark.sql.sources.default will be used.
In the case the table already exists, behavior of this function depends on the save mode,
specified by the mode function (default to throwing an exception). When mode is Overwrite,
the schema of the DataFrame does not need to be the same as that of the existing table.
text(path, compression=None)
Saves the content of the DataFrame in a text file at the specified path.
The DataFrame must have only one column that is of string type. Each row becomes a new
line in the output file.
pyspark.sql.types module
class pyspark.sql.types.DataType [source]
Base class for data types.
fromInternal(obj) [source]
Converts an internal SQL object into a native Python object.
json() [source]
jsonValue() [source]
needConversion() [source]
Does this type need to conversion between Python object and internal SQL object.
simpleString() [source]
toInternal(obj) [source]
Converts a Python object into an internal SQL object.
The data type representing None, used for the types that cannot be inferred.
EPOCH_ORDINAL = 719163
fromInternal(v) [source]
needConversion() [source]
toInternal(d) [source]
fromInternal(ts) [source]
needConversion() [source]
toInternal(dt) [source]
The DecimalType must have fixed precision (the maximum total number of digits) and scale (the
number of digits on the right of dot). For example, (5, 2) can support the value from [-999.99 to
999.99].
The precision can be up to 38, the scale must less or equal to precision.
When create a DecimalType, the default precision and scale is (10, 0). When infer schema from
decimal.Decimal objects, it will be DecimalType(38, 18).
jsonValue() [source]
simpleString() [source]
simpleString() [source]
simpleString() [source]
use DecimalType.
simpleString() [source]
simpleString() [source]
fromInternal(obj) [source]
jsonValue() [source]
needConversion() [source]
simpleString() [source]
toInternal(obj) [source]
fromInternal(obj) [source]
jsonValue() [source]
needConversion() [source]
simpleString() [source]
toInternal(obj) [source]
A field in StructType.
fromInternal(obj) [source]
jsonValue() [source]
needConversion() [source]
simpleString() [source]
toInternal(obj) [source]
fromInternal(obj) [source]
jsonValue() [source]
needConversion() [source]
simpleString() [source]
toInternal(obj) [source]
pyspark.sql.functions module
A collections of builtin functions
pyspark.sql.functions.abs(col)
Computes the absolute value.
pyspark.sql.functions.acos(col)
Computes the cosine inverse of the given value; the returned angle is in the range0.0 through pi.
pyspark.sql.functions.array(*cols) [source]
Creates a new array column.
Parameters: cols – list of column names (string) or list of Column expressions that have the
same data type.
pyspark.sql.functions.asc(col)
Returns a sort expression based on the ascending order of the given column name.
pyspark.sql.functions.ascii(col)
Computes the numeric value of the first character of the string column.
pyspark.sql.functions.asin(col)
Computes the sine inverse of the given value; the returned angle is in the range-pi/2 through pi/2.
pyspark.sql.functions.atan(col)
Computes the tangent inverse of the given value.
pyspark.sql.functions.atan2(col1, col2)
Returns the angle theta from the conversion of rectangular coordinates (x, y) topolar coordinates
(r, theta).
pyspark.sql.functions.avg(col)
Aggregate function: returns the average of the values in a group.
pyspark.sql.functions.base64(col)
Computes the BASE64 encoding of a binary column and returns it as a string column.
pyspark.sql.functions.bin(col) [source]
Returns the string representation of the binary value of the given column.
pyspark.sql.functions.bitwiseNOT(col)
Computes bitwise not.
pyspark.sql.functions.broadcast(df) [source]
Marks a DataFrame as small enough for use in broadcast joins.
pyspark.sql.functions.cbrt(col)
Computes the cube-root of the given value.
pyspark.sql.functions.ceil(col)
Computes the ceiling of the given value.
pyspark.sql.functions.coalesce(*cols) [source]
Returns the first column that is not null.
pyspark.sql.functions.col(col)
Returns a Column based on the given column name.
pyspark.sql.functions.collect_list(col)
Aggregate function: returns a list of objects with duplicates.
pyspark.sql.functions.collect_set(col)
Aggregate function: returns a set of objects with duplicate elements eliminated.
pyspark.sql.functions.column(col)
Returns a Column based on the given column name.
pyspark.sql.functions.concat(*cols) [source]
Concatenates multiple input string columns together into a single string column.
pyspark.sql.functions.cos(col)
Computes the cosine of the given value.
pyspark.sql.functions.cosh(col)
Computes the hyperbolic cosine of the given value.
pyspark.sql.functions.count(col)
Aggregate function: returns the number of items in a group.
pyspark.sql.functions.crc32(col) [source]
Calculates the cyclic redundancy check value (CRC32) of a binary column and returns the value
as a bigint.
pyspark.sql.functions.create_map(*cols) [source]
Creates a new map column.
Parameters: cols – list of column names (string) or list of Column expressions that grouped as
key-value pairs, e.g. (key1, value1, key2, value2, ...).
pyspark.sql.functions.cume_dist()
Window function: returns the cumulative distribution of values within a window partition, i.e. the
fraction of rows that are below the current row.
pyspark.sql.functions.current_date() [source]
Returns the current date as a date column.
pyspark.sql.functions.current_timestamp() [source]
A pattern could be for instance dd.MM.yyyy and could return a string like ‘18.03.1993’. All pattern
letters of the Java class java.text.SimpleDateFormat can be used.
Note: Use when ever possible specialized functions like year. These benefit from a specialized
implementation.
pyspark.sql.functions.dayofmonth(col) [source]
pyspark.sql.functions.dayofyear(col) [source]
Extract the day of the year of a given date as integer.
pyspark.sql.functions.degrees(col)
Converts an angle measured in radians to an approximately equivalent angle measured in
degrees.
pyspark.sql.functions.dense_rank()
Window function: returns the rank of rows within a window partition, without any gaps.
The difference between rank and dense_rank is that dense_rank leaves no gaps in ranking
sequence when there are ties. That is, if you were ranking a competition using dense_rank and
had three people tie for second place, you would say that all three were in second place and that
the next person came in third. Rank would give me sequential numbers, making the person that
came in third place (after the ties) would register as coming in fifth.
pyspark.sql.functions.desc(col)
Returns a sort expression based on the descending order of the given column name.
Computes the first argument into a binary from a string using the provided character set (one of
‘US-ASCII’, ‘ISO-8859-1’, ‘UTF-8’, ‘UTF-16BE’, ‘UTF-16LE’, ‘UTF-16’).
pyspark.sql.functions.exp(col)
Computes the exponential of the given value.
pyspark.sql.functions.explode(col) [source]
Returns a new row for each element in the given array or map.
pyspark.sql.functions.expm1(col)
Computes the exponential of the given value minus one.
pyspark.sql.functions.expr(str) [source]
Parses the expression string into the column that it represents
pyspark.sql.functions.factorial(col) [source]
Computes the factorial of the given value.
The function by default returns the first values it sees. It will return the first non-null value it sees
when ignoreNulls is set to true. If all values are null, then null is returned.
pyspark.sql.functions.floor(col)
Computes the floor of the given value.
pyspark.sql.functions.format_number(col, d) [source]
Formats the number X to a format like ‘#,–#,–#.–’, rounded to d decimal places with HALF_EVEN
round mode, and returns the result as a string.
datasource
pyspark.sql.functions.greatest(*cols) [source]
Returns the greatest value of the list of column names, skipping null values. This function takes at
least 2 parameters. It will return null iff all parameters are null.
pyspark.sql.functions.grouping(col) [source]
Aggregate function: indicates whether a specified column in a GROUP BY list is aggregated or not,
returns 1 for aggregated or 0 for not aggregated in the result set.
pyspark.sql.functions.grouping_id(*cols) [source]
Aggregate function: returns the level of grouping, equals to
Note: The list of columns should match with grouping columns exactly, or empty (means all the
grouping columns).
pyspark.sql.functions.hash(*cols) [source]
Calculates the hash code of given columns, and returns the result as an int column.
pyspark.sql.functions.hex(col) [source]
Computes hex value of the given column, which could be pyspark.sql.types.StringType,
pyspark.sql.types.BinaryType, pyspark.sql.types.IntegerType or
pyspark.sql.types.LongType.
pyspark.sql.functions.hour(col) [source]
Extract the hours of a given date as integer.
pyspark.sql.functions.hypot(col1, col2)
Computes sqrt(a^2 + b^2) without intermediate overflow or underflow.
pyspark.sql.functions.initcap(col) [source]
Translate the first letter of each word to upper case in the sentence.
pyspark.sql.functions.input_file_name() [source]
Creates a string column for the file name of the current Spark task.
Note: The position is not zero based, but 1 based index. Returns 0 if substr could not be found
in str.
pyspark.sql.functions.isnan(col) [source]
An expression that returns true iff the column is NaN.
pyspark.sql.functions.isnull(col) [source]
An expression that returns true iff the column is null.
pyspark.sql.functions.kurtosis(col)
Aggregate function: returns the kurtosis of the values in a group.
The function by default returns the last values it sees. It will return the last non-null value it sees
when ignoreNulls is set to true. If all values are null, then null is returned.
pyspark.sql.functions.last_day(date) [source]
Returns the last day of the month which the given date belongs to.
pyspark.sql.functions.least(*cols) [source]
Returns the least value of the list of column names, skipping null values. This function takes at
least 2 parameters. It will return null iff all parameters are null.
pyspark.sql.functions.length(col) [source]
Calculates the length of a string or binary expression.
pyspark.sql.functions.lit(col)
Creates a Column of literal value.
Note: The position is not zero based, but 1 based index. Returns 0 if substr could not be found
in str.
If there is only one argument, then this takes the natural logarithm of the argument.
pyspark.sql.functions.log10(col)
Computes the logarithm of the given value in Base 10.
pyspark.sql.functions.log1p(col)
Computes the natural logarithm of the given value plus one.
pyspark.sql.functions.log2(col) [source]
Returns the base-2 logarithm of the argument.
()
pyspark.sql.functions.lower(col)
Converts a string column to lower case.
pyspark.sql.functions.ltrim(col)
Trim the spaces from left end for the specified string value.
pyspark.sql.functions.max(col)
Aggregate function: returns the maximum value of the expression in a group.
pyspark.sql.functions.md5(col) [source]
Calculates the MD5 digest and returns the value as a 32 character hex string.
pyspark.sql.functions.mean(col)
Aggregate function: returns the average of the values in a group.
pyspark.sql.functions.min(col)
Aggregate function: returns the minimum value of the expression in a group.
pyspark.sql.functions.minute(col) [source]
Extract the minutes of a given date as integer.
pyspark.sql.functions.monotonically_increasing_id() [source]
A column that generates monotonically increasing 64-bit integers.
The generated ID is guaranteed to be monotonically increasing and unique, but not consecutive.
The current implementation puts the partition ID in the upper 31 bits, and the record number within
each partition in the lower 33 bits. The assumption is that the data frame has less than 1 billion
partitions, and each partition has less than 8 billion records.
As an example, consider a DataFrame with two partitions, each with 3 records. This expression
would return the following IDs: 0, 1, 2, 8589934592 (1L << 33), 8589934593, 8589934594.
pyspark.sql.functions.month(col) [source]
pyspark.sql.functions.ntile(n) [source]
Window function: returns the ntile group id (from 1 to n inclusive) in an ordered window partition.
For example, if n is 4, the first quarter of the rows will get value 1, the second quarter will get 2, the
third quarter will get 3, and the last quarter will get 4.
Parameters: n – an integer
pyspark.sql.functions.percent_rank()
Window function: returns the relative rank (i.e. percentile) of rows within a window partition.
pyspark.sql.functions.posexplode(col) [source]
Returns a new row for each element with position in the given array or map.
pyspark.sql.functions.pow(col1, col2)
Returns the value of the first argument raised to the power of the second argument.
pyspark.sql.functions.quarter(col) [source]
Extract the quarter of a given date as integer.
pyspark.sql.functions.radians(col)
Converts an angle measured in degrees to an approximately equivalent angle measured in
radians.
pyspark.sql.functions.rand(seed=None) [source]
Generates a random column with independent and identically distributed (i.i.d.) samples from
U[0.0, 1.0].
pyspark.sql.functions.randn(seed=None) [source]
Generates a column with independent and identically distributed (i.i.d.) samples from the standard
normal distribution.
pyspark.sql.functions.rank()
Window function: returns the rank of rows within a window partition.
The difference between rank and dense_rank is that dense_rank leaves no gaps in ranking
sequence when there are ties. That is, if you were ranking a competition using dense_rank and
had three people tie for second place, you would say that all three were in second place and that
the next person came in third. Rank would give me sequential numbers, making the person that
came in third place (after the ties) would register as coming in fifth.
pyspark.sql.functions.repeat(col, n) [source]
Repeats a string column n times, and returns it as a new string column.
pyspark.sql.functions.reverse(col)
Reverses the string column and returns it as a new string column.
pyspark.sql.functions.rint(col)
Returns the double value that is closest in value to the argument and is equal to a mathematical
integer.
pyspark.sql.functions.row_number()
Window function: returns a sequential number starting at 1 within a window partition.
pyspark.sql.functions.rtrim(col)
Trim the spaces from right end for the specified string value.
pyspark.sql.functions.second(col) [source]
Extract the seconds of a given date as integer.
pyspark.sql.functions.sha1(col) [source]
Returns the hex string result of SHA-1.
pyspark.sql.functions.signum(col)
Computes the signum of the given value.
pyspark.sql.functions.sin(col)
Computes the sine of the given value.
pyspark.sql.functions.sinh(col)
Computes the hyperbolic sine of the given value.
pyspark.sql.functions.size(col) [source]
Collection function: returns the length of the array or map stored in the column.
pyspark.sql.functions.skewness(col)
Aggregate function: returns the skewness of the values in a group.
pyspark.sql.functions.soundex(col) [source]
Returns the SoundEx encoding for a string
pyspark.sql.functions.spark_partition_id() [source]
A column for partition ID.
Note: This is indeterministic because it depends on data partitioning and task scheduling.
pyspark.sql.functions.sqrt(col)
Computes the square root of the specified float value.
pyspark.sql.functions.stddev(col)
Aggregate function: returns the unbiased sample standard deviation of the expression in a group.
pyspark.sql.functions.stddev_pop(col)
Aggregate function: returns population standard deviation of the expression in a group.
pyspark.sql.functions.stddev_samp(col)
Aggregate function: returns the unbiased sample standard deviation of the expression in a group.
pyspark.sql.functions.struct(*cols) [source]
Creates a new struct column.
pyspark.sql.functions.sum(col)
Aggregate function: returns the sum of all values in the expression.
pyspark.sql.functions.sumDistinct(col)
pyspark.sql.functions.tan(col)
Computes the tangent of the given value.
pyspark.sql.functions.tanh(col)
Computes the hyperbolic tangent of the given value.
pyspark.sql.functions.toDegrees(col)
pyspark.sql.functions.toRadians(col)
Parameters: col – name of column containing the struct or array of the structs
options – options to control converting. accepts the same options as the json
datasource
pyspark.sql.functions.trim(col)
Trim the spaces from both ends for the specified string column.
pyspark.sql.functions.unbase64(col)
Decodes a BASE64 encoded string column and returns it as a binary column.
pyspark.sql.functions.unhex(col) [source]
Inverse of hex. Interprets each pair of characters as a hexadecimal number and converts to the
byte representation of number.
pyspark.sql.functions.upper(col)
Converts a string column to upper case.
pyspark.sql.functions.var_pop(col)
Aggregate function: returns the population variance of the values in a group.
pyspark.sql.functions.var_samp(col)
Aggregate function: returns the unbiased variance of the values in a group.
pyspark.sql.functions.variance(col)
Aggregate function: returns the population variance of the values in a group.
pyspark.sql.functions.weekofyear(col) [source]
Extract the week number of a given date as integer.
Durations are provided as strings, e.g. ‘1 second’, ‘1 day 12 hours’, ‘2 minutes’. Valid interval
strings are ‘week’, ‘day’, ‘hour’, ‘minute’, ‘second’, ‘millisecond’, ‘microsecond’. If the
slideDuration is not provided, the windows will be tumbling windows.
The startTime is the offset with respect to 1970-01-01 00:00:00 UTC with which to start window
intervals. For example, in order to have hourly tumbling windows that start 15 minutes past the
hour, e.g. 12:15-13:15, 13:15-14:15... provide startTime as 15 minutes.
The output column will be a struct called ‘window’ by default with the nested columns ‘start’ and
‘end’, where ‘start’ and ‘end’ will be of pyspark.sql.types.TimestampType.
pyspark.sql.functions.year(col) [source]
pyspark.sql.streaming module
class pyspark.sql.streaming.StreamingQuery(jsq) [source]
A handle to a query that is executing continuously in the background as new data arrives. All these
methods are thread-safe.
Note: Evolving
awaitTermination(timeout=None) [source]
Waits for the termination of this query, either by query.stop() or by an exception. If the query
has terminated with an exception, then the exception will be thrown. If timeout is set, it returns
whether the query has terminated or not within the timeout seconds.
If the query has terminated, then all subsequent calls to this method will either return
immediately (if the query was terminated by stop()), or throw the exception immediately (if
the query has terminated with exception).
exception() [source]
Returns: the StreamingQueryException if the query was terminated by an exception, or
None.
explain(extended=False) [source]
Prints the (logical and physical) plans to the console for debugging purpose.
Parameters: extended – boolean, default False. If False, prints only the physical plan.
id [source]
Returns the unique id of this query that persists across restarts from checkpoint data. That is,
this id is generated when a query is started for the first time, and will be the same every time it
is restarted from checkpoint data. There can only be one query with the same id active in a
Spark cluster. Also see, runId.
isActive [source]
Whether this streaming query is currently active or not.
lastProgress [source]
Returns the most recent StreamingQueryProgress update of this streaming query or None if
there were no progress updates :return: a map
name [source]
Returns the user-specified name of the query, or null if not specified. This name can be
specified in the org.apache.spark.sql.streaming.DataStreamWriter as
dataframe.writeStream.queryName(“query”).start(). This name, if set, must be unique across
all active queries.
processAllAvailable() [source]
Blocks until all available data in the source has been processed and committed to the sink.
This method is intended for testing.
Note: In the case of continually arriving data, this method may block forever. Additionally,
this method is only guaranteed to block until data that has been synchronously appended
data to a stream source prior to invocation. (i.e. getOffset must immediately reflect the
addition).
recentProgress [source]
Returns an array of the most recent [[StreamingQueryProgress]] updates for this query. The
number of progress updates retained for each stream is configured by Spark session
configuration spark.sql.streaming.numRecentProgressUpdates.
runId [source]
Returns the unique id of this query that does not persist across restarts. That is, every query
that is started (or restarted from checkpoint) will have a different runId.
status [source]
Returns the current status of the query.
stop() [source]
Stop this streaming query.
Note: Evolving
active [source]
Returns a list of active queries associated with this SQLContext
awaitAnyTermination(timeout=None) [source]
Wait until any of the queries on the associated SQLContext has terminated since the creation
of the context, or since resetTerminated() was called. If any query was terminated with an
exception, then the exception will be thrown. If timeout is set, it returns whether the query has
terminated or not within the timeout seconds.
If a query has terminated, then subsequent calls to awaitAnyTermination() will either return
immediately (if the query was terminated by query.stop()), or throw the exception
immediately (if the query was terminated with exception). Use resetTerminated() to clear
past terminations and wait for new terminations.
In the case where multiple queries have terminated since resetTermination() was called, if
any query has terminated with exception, then awaitAnyTermination() will throw any of the
exception. For correctly documenting exceptions across multiple queries, users need to stop
all of them after any of them terminates with exception, and then check the query.exception()
for each query.
get(id) [source]
Returns an active query from this SQLContext or throws exception if an active query with this
name doesn’t exist.
resetTerminated() [source]
Forget about past terminated queries so that awaitAnyTermination() can be used again to
wait for new terminations.
Note: Evolving.
This function will go through the input once to determine the input schema if inferSchema is
enabled. To avoid going through the entire data once, disable inferSchema option or specify
the schema explicitly using schema.
Note: Evolving.
multiLine – parse one record, which may span multiple lines. If None is
set, it uses the default value, false.
format(source) [source]
Specifies the input data source format.
Note: Evolving.
Parameters: source – string, name of the data source, e.g. ‘json’, ‘parquet’.
JSON Lines (newline-delimited JSON) is supported by default. For JSON (one record per file),
set the multiLine parameter to true.
If the schema parameter is not specified, this function goes through the input once to
determine the input schema.
Note: Evolving.
Parameters: path – string represents path to the JSON dataset, or RDD of Strings
storing JSON objects.
schema – an optional pyspark.sql.types.StructType for the input
schema.
primitivesAsString – infers all primitive values as a string type. If None is
set, it uses the default value, false.
prefersDecimal – infers all floating-point values as a decimal type. If the
values do not fit in decimal, then it infers them as doubles. If None is set, it
uses the default value, false.
allowComments – ignores Java/C++ style comment in JSON records. If
None is set, it uses the default value, false.
allowUnquotedFieldNames – allows unquoted JSON field names. If
None is set, it uses the default value, false.
allowSingleQuotes – allows single quotes in addition to double quotes. If
None is set, it uses the default value, true.
allowNumericLeadingZero – allows leading zeros in numbers (e.g.
00012). If None is set, it uses the default value, false.
allowBackslashEscapingAnyCharacter – allows accepting quoting of all
character using backslash quoting mechanism. If None is set, it uses the
default value, false.
mode –
allows a mode for dealing with corrupt records during parsing. If None is
set, it uses the default value, PERMISSIVE.
Note: Evolving.
Note: Evolving.
options(**options) [source]
Adds input options for the underlying data source.
timeZone: sets the string that indicates a timezone to be used to parse timestamps
in the JSON/CSV datasources or partition values. If it isn’t set, it uses the
default value, session local timezone.
Note: Evolving.
parquet(path) [source]
Loads a Parquet file stream, returning the result as a DataFrame.
You can set the following Parquet-specific option(s) for reading Parquet files:
mergeSchema: sets whether we should merge schemas collected from all Parquet
part-files. This will override spark.sql.parquet.mergeSchema. The default value
is specified in spark.sql.parquet.mergeSchema.
Note: Evolving.
schema(schema) [source]
Specifies the input schema.
Some data sources (e.g. JSON) can infer the input schema automatically from data. By
specifying the schema here, the underlying data source can skip the schema inference step,
and thus speed up data loading.
Note: Evolving.
text(path) [source]
Loads a text file stream and returns a DataFrame whose schema starts with a string column
named “value”, and followed by partitioned columns if there are any.
Each line in the text file is a new row in the resulting DataFrame.
Note: Evolving.
Note: Evolving.
format(source) [source]
Specifies the underlying output data source.
Note: Evolving.
Parameters: source – string, name of the data source, which for now can be ‘parquet’.
Note: Evolving.
options(**options) [source]
Adds output options for the underlying data source.
Note: Evolving.
outputMode(outputMode) [source]
Specifies how data of a streaming DataFrame/Dataset is written to a streaming sink.
Options include:
Note: Evolving.
partitionBy(*cols) [source]
Partitions the output by the given columns on the file system.
If specified, the output is laid out on the file system similar to Hive’s partitioning scheme.
Note: Evolving.
queryName(queryName) [source]
Specifies the name of the StreamingQuery that can be started with start(). This name must
be unique among all the currently active queries in the associated SparkSession.
Note: Evolving.
The data source is specified by the format and a set of options. If format is not specified,
the default data source configured by spark.sql.sources.default will be used.
Note: Evolving.
Note: Evolving.