pyspark.sql.functions.try_multiply#

pyspark.sql.functions.try_multiply(left, right)[source]#

Returns left`*`right and the result is null on overflow. The acceptable input types are the same with the * operator.

New in version 3.5.0.

Parameters
leftColumn or column name

multiplicand

rightColumn or column name

multiplier

Examples

Example 1: Integer multiplied by Integer.

>>> import pyspark.sql.functions as sf
>>> spark.createDataFrame(
...     [(6000, 15), (1990, 2)], ["a", "b"]
... ).select("*", sf.try_multiply("a", "b")).show()
+----+---+------------------+
|   a|  b|try_multiply(a, b)|
+----+---+------------------+
|6000| 15|             90000|
|1990|  2|              3980|
+----+---+------------------+

Example 2: Interval multiplied by Integer.

>>> import pyspark.sql.functions as sf
>>> df = spark.range(6).select(sf.make_interval(sf.col("id"), sf.lit(3)).alias("itvl"), "id")
>>> df.select("*", sf.try_multiply("itvl", "id")).show()
+----------------+---+----------------------+
|            itvl| id|try_multiply(itvl, id)|
+----------------+---+----------------------+
|        3 months|  0|             0 seconds|
|1 years 3 months|  1|      1 years 3 months|
|2 years 3 months|  2|      4 years 6 months|
|3 years 3 months|  3|      9 years 9 months|
|4 years 3 months|  4|              17 years|
|5 years 3 months|  5|     26 years 3 months|
+----------------+---+----------------------+

Example 3: Overflow results in NULL when ANSI mode is on

>>> import pyspark.sql.functions as sf
>>> origin = spark.conf.get("spark.sql.ansi.enabled")
>>> spark.conf.set("spark.sql.ansi.enabled", "true")
>>> try:
...     spark.range(1).select(sf.try_multiply(sf.lit(sys.maxsize), sf.lit(sys.maxsize))).show()
... finally:
...     spark.conf.set("spark.sql.ansi.enabled", origin)
+------------------------------------------------------+
|try_multiply(9223372036854775807, 9223372036854775807)|
+------------------------------------------------------+
|                                                  NULL|
+------------------------------------------------------+