User defined functions 我应该在哪里注册泛型函数的spark UDF

User defined functions 我应该在哪里注册泛型函数的spark UDF,user-defined-functions,pyspark-sql,User Defined Functions,Pyspark Sql,我有一个通用函数,它针对不同的参数执行多次。此方法使用自定义项来处理日期和年份。在调用UDF的方法中注册UDF是一种好的做法吗?如果不是,那么哪一种是最佳实践?一次又一次注册同一个UDF会对性能产生什么影响 def get_date_from_year_and_month(year_month): """Returns year and month in the format YYYY-MM. year, month = year_month return str(ye

我有一个通用函数,它针对不同的参数执行多次。此方法使用自定义项来处理日期和年份。在调用UDF的方法中注册UDF是一种好的做法吗?如果不是,那么哪一种是最佳实践?一次又一次注册同一个UDF会对性能产生什么影响

def get_date_from_year_and_month(year_month):
    """Returns year and month in the format YYYY-MM.
    year, month = year_month

    return str(year) + '-' + str(month).zfill(2)

def function_that_uses_udf(param):
    # Should this be done outside the function?
    get_date_from_year_and_month_udf = F.udf(get_date_from_year_and_month)

    df = df_old.withColumn(
    'date', get_date_from_year_and_month_udf(F.struct([F.col('year'), F.col('month')]))

例如,在这里,每次通过spark上下文:

def squared(s):
   return s * s

spark.udf.register("squaredWithPython", squared)

不像Hive那样,它可以存储在数据库中。

您能接受答案吗,或者告诉我其他情况吗?@thebluephantom感谢您回答最佳实践。我还想知道在循环中注册相同的UDF对性能的影响。Spark,懒惰,它是如何在这个寄存器的后台工作的。不要在循环中这样做,只在前面做一次。这有点令人失望。你能接受这个答案吗