gpt4 book ai didi

apache-spark - 如何在udf中使用广播集合?

转载 作者:行者123 更新时间:2023-12-01 18:00:30 29 4
gpt4 key购买 nike

如何在 Spark SQL 1.6.1 udf 中使用广播集合。应从主 SQL 调用 Udf,如下所示

sqlContext.sql("""Select col1,col2,udf_1(key) as value_from_udf FROM table_a""")

udf_1() 应该通过广播小集合查找以将值返回到主 sql。

最佳答案

这是 pySpark 中的一个最小的可重现示例,说明了如何使用广播变量来执行查找,并在内部使用 lambda 函数作为 UDF SQL 语句。

# Create dummy data and register as table
df = sc.parallelize([
(1,"a"),
(2,"b"),
(3,"c")]).toDF(["num","let"])
df.registerTempTable('table')

# Create broadcast variable from local dictionary
myDict = {1: "y", 2: "x", 3: "z"}
broadcastVar = sc.broadcast(myDict)
# Alternatively, if your dict is a key-value rdd,
# you can do sc.broadcast(rddDict.collectAsMap())

# Create lookup function and apply it
sqlContext.registerFunction("lookup", lambda x: broadcastVar.value.get(x))
sqlContext.sql('select num, let, lookup(num) as test from table').show()
+---+---+----+
|num|let|test|
+---+---+----+
| 1| a| y|
| 2| b| x|
| 3| c| z|
+---+---+----+

关于apache-spark - 如何在udf中使用广播集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40673773/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com