【问题标题】:Pyspark UDF - performance hit on complex return typePyspark UDF - 复杂返回类型的性能影响
【发布时间】:2019-10-11 14:00:52
【问题描述】:

我有一个 PySpark UDF,它返回一个字符串元组,我已将其编码为一个结构。这是一个玩具示例,

def my_func(x):
  return "1", x, "3"

spark.udf.register("my_func", lambda x: my_func(x), StructType([StructField("one", StringType(),
                                                                StructField("two", StringType(), 
                                                                StructField("three", StringType()])

我称之为

spark.sql("select col1, my_func(col1) from sdf").show()

与返回元组的一个元素相比,返回整个元组的性能提高了 10 到 20 倍,例如

spark.udf.register("my_func", lambda x: my_func(x)[1], StringType())

这是一个已知问题吗?有没有办法避免转换速度变慢?

【问题讨论】:

    标签: apache-spark pyspark


    【解决方案1】:

    这就是我让它工作的方式 - 如果有更有效的方法,请点击 lmk。为了解决性能问题,

    1) Transform the DataFrame to an RDD[Row]
    
    2) Apply the function to transform into a Row of the final output
    
    3) Convert back to a DataFrame
    

    代码:

    def map_to_new_row(row):
      NewRow = Row("one", "two", "three")
      return NewRow("1", row.col1, "3")
    
    rdd1 = df1.rdd.map(map_to_new_row)
    df2 = spark.createDataFrame(rdd1, StructType([StructField("one", StringType(), 
                                                  StructField("two", StringType(), 
                                                  StructField("three", StringType()]))
    

    这给了我更好的性能。

    【讨论】:

      猜你喜欢
      • 2021-04-13
      • 2017-02-06
      • 2022-11-24
      • 2016-08-18
      • 2021-11-21
      • 1970-01-01
      • 2020-05-09
      • 2018-11-29
      相关资源
      最近更新 更多