在 Spark 中,这被视为 Graph 问题并使用 Vertex Centric Programming 解决。不幸的是,GraphX 没有兼容 python 的 API。
另一种选择是使用graphframes。
我在这里包含了一个使用模仿 Vertex Centric Programming 但不使用任何库的连接的逻辑。前提是您可以将拥有的数据表示形式转换为具有id、parent_id 和name 列的数据框。
from pyspark.sql import functions as F
from pyspark.sql.functions import col as c
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local[1]").appName("nsankaranara").getOrCreate()
data = [(6, 3, "Child_3", ),
(5, 2, "Child_2", ),
(4, 2, "Child_1", ),
(3, 1, "Parent_2", ),
(2, 1, "Parent_1", ),
(1, None, "Root"), ]
df = spark.createDataFrame(data, ("id", "parent_id", "name", ))
df = (df.withColumn("mapped_parent_id", c("parent_id"))
.withColumn("visited", F.lit(False)))
start_nodes = df.filter(c("mapped_parent_id").isNull())
# Controls how deep we want to traverse
max_iter = 256
iter_counter = 0
# Iteratively identify the next child and add your name to them
while iter_counter < max_iter:
iter_counter += 1
df = (df.alias("a").join(start_nodes.alias("b"),
((c("a.parent_id") == c("b.id")) | (c("a.id") == c("b.id"))), how="left_outer"))
df = (df.select(c("a.id"),
c("a.parent_id"),
(F.when((c("b.id").isNotNull() & (c("a.id") != c("b.id"))), F.lit(None)).otherwise(c("a.mapped_parent_id"))).alias("mapped_parent_id"),
F.when((c("a.id") != c("b.id")), F.concat_ws(" ", c("a.name"), c("b.name"))).otherwise(c("a.name")).alias("name"),
(F.when(c("a.id") == c("b.id"), F.lit(True)).otherwise(c("a.visited"))).alias("visited")
)).cache()
start_nodes = df.filter(((c("mapped_parent_id").isNull()) & (c("visited") == False)))
if start_nodes.count() == 0:
# signifies that all nodes have been visited
break
df.select("id", "parent_id", "name").show(truncate = False)
输出
+---+---------+---------------------+
|id |parent_id|name |
+---+---------+---------------------+
|6 |3 |Child_3 Parent_2 Root|
|5 |2 |Child_2 Parent_1 Root|
|4 |2 |Child_1 Parent_1 Root|
|3 |1 |Parent_2 Root |
|2 |1 |Parent_1 Root |
|1 |null |Root |
+---+---------+---------------------+