GraphX实现N度关系

简介:

背景

本文给出了一个简单的计算图中每个点的N度关系点集合的算法,也就是N跳关系。

之前通过官方文档学习和理解了一下GraphX的计算接口。

N度关系

目标:
在N轮里,找到某一个点的N度关系的点集合。

实现思路:
1. 准备好边数据集,即”1 3”, “4, 1” 这样的点关系。使用GraphLoader 的接口load成Graph
2. 初始化每个Vertice的属性为空Map
3. 使用aggregateMessagesVerticeIDtotalRounds传播出度点上,出度点把收集到的信息合成一个大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.RDD

val friendsGraph = GraphLoader.edgeListFile(sc, "data/friends.txt")
val totalRounds: Int = 3 // total N round
var targetVerticeID: Long = 6 // target vertice

// round one
var 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 1
4 1
1 2
6 3
7 3
7 6
6 7
3 7
4 3
1 6
6 1
Array(6, 1, 3, 7)

总结

实现的比较naive,还有许多可以优化的地方。

全文完 :)

目录
相关文章
|
应用服务中间件 Windows
tomcat出现中文乱码原因和解决办法(简单快捷易懂)
双击打开tomcat中的bin目录下的startup.bat会出现乱码问题 或者cmd里面打开也是乱码的问题
1979 0
tomcat出现中文乱码原因和解决办法(简单快捷易懂)
|
8天前
|
云安全 监控 安全
|
13天前
|
机器学习/深度学习 人工智能 自然语言处理
Z-Image:冲击体验上限的下一代图像生成模型
通义实验室推出全新文生图模型Z-Image,以6B参数实现“快、稳、轻、准”突破。Turbo版本仅需8步亚秒级生成,支持16GB显存设备,中英双语理解与文字渲染尤为出色,真实感和美学表现媲美国际顶尖模型,被誉为“最值得关注的开源生图模型之一”。
1433 8
|
7天前
|
人工智能 安全 前端开发
AgentScope Java v1.0 发布,让 Java 开发者轻松构建企业级 Agentic 应用
AgentScope 重磅发布 Java 版本,拥抱企业开发主流技术栈。
474 11
|
19天前
|
人工智能 Java API
Java 正式进入 Agentic AI 时代:Spring AI Alibaba 1.1 发布背后的技术演进
Spring AI Alibaba 1.1 正式发布,提供极简方式构建企业级AI智能体。基于ReactAgent核心,支持多智能体协作、上下文工程与生产级管控,助力开发者快速打造可靠、可扩展的智能应用。
1255 43
|
19天前
|
人工智能 前端开发 算法
大厂CIO独家分享:AI如何重塑开发者未来十年
在 AI 时代,若你还在紧盯代码量、执着于全栈工程师的招聘,或者仅凭技术贡献率来评判价值,执着于业务提效的比例而忽略产研价值,你很可能已经被所谓的“常识”困住了脚步。
1162 88
大厂CIO独家分享:AI如何重塑开发者未来十年