GraphX實現N度關係

來源:互聯網
上載者:User

標籤:圖計算   graphx   

背景

本文給出了一個簡單的計算圖中每個點的N度關係點集合的演算法,也就是N跳關係。

之前通過官方文檔學習和理解了一下GraphX的計算介面。

N度關係

目標:
在N輪裡,找到某一個點的N度關係的點集合。

實現思路:
1. 準備好邊資料集,即”1 3”, “4, 1” 這樣的點關係。使用GraphLoader 的介面load成Graph
2. 初始化每個Vertice的屬性為空白Map
3. 使用aggregateMessages把VerticeID和totalRounds傳播出度點上,出度點把收集到的資訊合成一個大Map
4. 更新後的Vertice與原圖進行”Join”,更新圖中的變化過的點屬性
5. 重複步驟3和4,最後輸出更新了N輪之後的有關係的Vertice

spark-shell下可執行檔代碼:

import org.apache.spark._import org.apache.spark.graphx._import org.apache.spark.rdd.RDDval friendsGraph = GraphLoader.edgeListFile(sc, "data/friends.txt")val totalRounds: Int = 3 // total N roundvar targetVerticeID: Long = 6 // target vertice// round onevar roundGraph = friendsGraph.mapVertices((id, vd) => Map())var roundVertices = roundGraph.aggregateMessages[Map[Long, Integer]](  ctx => {    if (targetVerticeID == ctx.srcId) {      // only the edge has target vertice should send msg      ctx.sendToDst(Map(ctx.srcId -> totalRounds))    }  },   _ ++ _)for (i <- 2 to totalRounds) {  val thisRoundGraph = roundGraph.outerJoinVertices(roundVertices){ (vid, data, opt) => opt.getOrElse(Map[Long, Integer]()) }  roundVertices = thisRoundGraph.aggregateMessages[Map[Long, Integer]](    ctx => {      val iterator = ctx.srcAttr.iterator      while (iterator.hasNext) {        val (k, v) = iterator.next        if (v > 1) {          val newV = v - 1          ctx.sendToDst(Map(k -> newV))          ctx.srcAttr.updated(k, newV)        } else {          // do output and remove this entry        }      }    },    (newAttr, oldAttr) => {      if (oldAttr.contains(newAttr.head._1)) { // optimization to reduce msg        oldAttr.updated(newAttr.head._1, 1) // stop sending this ever      } else {        oldAttr ++ newAttr      }    }  )}val result = roundVertices.map(_._1).collect
資料和輸出
2 14 11 26 37 37 66 73 74 31 66 1
Array(6, 1, 3, 7)
總結

實現的比較naive,還有許多可以最佳化的地方。

全文完 :)

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

GraphX實現N度關係

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.