我有一個代表樹的有向邊串列。'uv' 表示你是 v 的孩子。
sc = SparkContext(conf = conf)
lines = sc.textFile("/content/sample_data/data.txt")
lines.take(10)
['0 0', '1 0', '2 0', '3 1', '4 1', '5 2', '6 2', '7 3', '8 3', '9 4']
我將上述內容轉換為以下形式存盤為intermediate:
[(0, ('out', 0)),
(0, ('in', 0)),
(1, ('out', 0)),
(0, ('in', 1)),...]
我正在嘗試從上面構建表單的鄰接串列:
[(8721, [('out', 4360), ('in', 17443), ('in', 17444)]),
(9291, [('out', 4645), ('in', 18583), ('in', 18584)]),
(9345, [('out', 4672), ('in', 18691), ('in', 18692)]),..]
這里,第一行告訴我們 8721 是 4360 的孩子,而 [17443, 17444] 是 8721 的孩子
我正在使用groupByKey或reduceByKey由 Spark 模塊公開的方法。
intermediate.groupByKey().mapValues(list)
上面的線需要很多時間。在具有 12 GB RAM 的 8 核機器上處理 100 MB 的測驗資料需要將近 250 秒。我最終必須在分布式環境中為 >15GB 的資料部署它。
我知道 groupByKey 會導致所有節點的資料混洗。在我的情況下,有什么辦法可以避免它嗎?任何有關如何優化此操作的建議表示贊賞。
uj5u.com熱心網友回復:
在對資料集的行進行分組時,您無法避免無序排列。但是,您可以使用資料幀 API 代替 RDD。Dataframe API 比 RDD 性能更高,請參閱此答案
如果你的txt檔案格式如下:
0 0
0 1
...
然后您可以將其作為資料幀讀取。
df = spark.read.csv('test.txt', sep=' ')
df.show()
--- ---
|_c0|_c1|
--- ---
| 0| 0|
| 1| 0|
| 2| 0|
| 3| 1|
| 4| 1|
| 5| 2|
| 6| 2|
| 7| 3|
| 8| 3|
| 9| 4|
--- ---
通過附加型別列進行交叉連接或 unionAll:
df2 = df.withColumn('_c2', f.lit('in')).unionAll(df.select('_c1', '_c0').withColumn('_c2', f.lit('out')))
df2.show()
--- --- ---
|_c0|_c1|_c2|
--- --- ---
| 0| 0| in|
| 1| 0| in|
| 2| 0| in|
| 3| 1| in|
| 4| 1| in|
| 5| 2| in|
| 6| 2| in|
| 7| 3| in|
| 8| 3| in|
| 9| 4| in|
| 0| 0|out|
| 0| 1|out|
| 0| 2|out|
| 1| 3|out|
| 1| 4|out|
| 2| 5|out|
| 2| 6|out|
| 3| 7|out|
| 3| 8|out|
| 4| 9|out|
--- --- ---
和groupBy結果。
df3 = df2.groupBy('_c0').agg(f.collect_list(f.array('_c2','_c1'))).toDF('edge', 'list')
df3.show(truncate=False)
df3.printSchema()
---- ---------------------------------------
|edge|list |
---- ---------------------------------------
|7 |[[in, 3]] |
|3 |[[in, 1], [out, 7], [out, 8]] |
|8 |[[in, 3]] |
|0 |[[in, 0], [out, 0], [out, 1], [out, 2]]|
|5 |[[in, 2]] |
|6 |[[in, 2]] |
|9 |[[in, 4]] |
|1 |[[in, 0], [out, 3], [out, 4]] |
|4 |[[in, 1], [out, 9]] |
|2 |[[in, 0], [out, 5], [out, 6]] |
---- ---------------------------------------
root
|-- edge: string (nullable = true)
|-- list: array (nullable = false)
| |-- element: array (containsNull = false)
| | |-- element: string (containsNull = true)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366883.html
