SparkGraphx计算指定节点的N度关系节点
直接上代码:
package horizon.graphx.util import java.security.InvalidParameterException import horizon.graphx.util.CollectionUtil.CollectionHelper
import org.apache.spark.graphx._
import org.apache.spark.rdd.RDD
import org.apache.spark.storage.StorageLevel import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag /**
* Created by yepei.ye on 2017/1/19.
* Description:用于在图中为指定的节点计算这些节点的N度关系节点,输出这些节点与源节点的路径长度和节点id
*/
object GraphNdegUtil {
val maxNDegVerticesCount = 10000
val maxDegree = 1000 /**
* 计算节点的N度关系
*
* @param edges
* @param choosedVertex
* @param degree
* @tparam ED
* @return
*/
def aggNdegreedVertices[ED: ClassTag](edges: RDD[(VertexId, VertexId)], choosedVertex: RDD[VertexId], degree: Int): VertexRDD[Map[Int, Set[VertexId]]] = {
val simpleGraph = Graph.fromEdgeTuples(edges, 0, Option(PartitionStrategy.EdgePartition2D), StorageLevel.MEMORY_AND_DISK_SER, StorageLevel.MEMORY_AND_DISK_SER)
aggNdegreedVertices(simpleGraph, choosedVertex, degree)
} def aggNdegreedVerticesWithAttr[VD: ClassTag, ED: ClassTag](graph: Graph[VD, ED], choosedVertex: RDD[VertexId], degree: Int, sendFilter: (VD, VD) => Boolean = (_: VD, _: VD) => true): VertexRDD[Map[Int, Set[VD]]] = {
val ndegs: VertexRDD[Map[Int, Set[VertexId]]] = aggNdegreedVertices(graph, choosedVertex, degree, sendFilter)
val flated: RDD[Ver[VD]] = ndegs.flatMap(e => e._2.flatMap(t => t._2.map(s => Ver(e._1, s, t._1, null.asInstanceOf[VD])))).persist(StorageLevel.MEMORY_AND_DISK_SER)
val matched: RDD[Ver[VD]] = flated.map(e => (e.id, e)).join(graph.vertices).map(e => e._2._1.copy(attr = e._2._2)).persist(StorageLevel.MEMORY_AND_DISK_SER)
flated.unpersist(blocking = false)
ndegs.unpersist(blocking = false)
val grouped: RDD[(VertexId, Map[Int, Set[VD]])] = matched.map(e => (e.source, ArrayBuffer(e))).reduceByKey(_ ++= _).map(e => (e._1, e._2.map(t => (t.degree, Set(t.attr))).reduceByKey(_ ++ _).toMap))
matched.unpersist(blocking = false)
VertexRDD(grouped)
} def aggNdegreedVertices[VD: ClassTag, ED: ClassTag](graph: Graph[VD, ED],
choosedVertex: RDD[VertexId],
degree: Int,
sendFilter: (VD, VD) => Boolean = (_: VD, _: VD) => true
): VertexRDD[Map[Int, Set[VertexId]]] = {
if (degree < 1) {
throw new InvalidParameterException("度参数错误:" + degree)
}
val initVertex = choosedVertex.map(e => (e, true)).persist(StorageLevel.MEMORY_AND_DISK_SER)
var g: Graph[DegVertex[VD], Int] = graph.outerJoinVertices(graph.degrees)((_, old, deg) => (deg.getOrElse(0), old))
.subgraph(vpred = (_, a) => a._1 <= maxDegree)
//去掉大节点
.outerJoinVertices(initVertex)((id, old, hasReceivedMsg) => {
DegVertex(old._2, hasReceivedMsg.getOrElse(false), ArrayBuffer((id, 0))) //初始化要发消息的节点
}).mapEdges(_ => 0).cache() //简化边属性 choosedVertex.unpersist(blocking = false) var i = 0
var prevG: Graph[DegVertex[VD], Int] = null
var newVertexRdd: VertexRDD[ArrayBuffer[(VertexId, Int)]] = null
while (i < degree + 1) {
prevG = g
//发第i+1轮消息
newVertexRdd = prevG.aggregateMessages[ArrayBuffer[(VertexId, Int)]](sendMsg(_, sendFilter), (a, b) => reduceVertexIds(a ++ b)).persist(StorageLevel.MEMORY_AND_DISK_SER)
g = g.outerJoinVertices(newVertexRdd)((vid, old, msg) => if (msg.isDefined) updateVertexByMsg(vid, old, msg.get) else old.copy(init = false)).cache()
prevG.unpersistVertices(blocking = false)
prevG.edges.unpersist(blocking = false)
newVertexRdd.unpersist(blocking = false)
i += 1
}
newVertexRdd.unpersist(blocking = false) val maped = g.vertices.join(initVertex).mapValues(e => sortResult(e._1)).persist(StorageLevel.MEMORY_AND_DISK_SER)
initVertex.unpersist()
g.unpersist(blocking = false)
VertexRDD(maped)
} private case class Ver[VD: ClassTag](source: VertexId, id: VertexId, degree: Int, attr: VD = null.asInstanceOf[VD]) private def updateVertexByMsg[VD: ClassTag](vertexId: VertexId, oldAttr: DegVertex[VD], msg: ArrayBuffer[(VertexId, Int)]): DegVertex[VD] = {
val addOne = msg.map(e => (e._1, e._2 + 1))
val newMsg = reduceVertexIds(oldAttr.degVertices ++ addOne)
oldAttr.copy(init = msg.nonEmpty, degVertices = newMsg)
} private def sortResult[VD: ClassTag](degs: DegVertex[VD]): Map[Int, Set[VertexId]] = degs.degVertices.map(e => (e._2, Set(e._1))).reduceByKey(_ ++ _).toMap case class DegVertex[VD: ClassTag](var attr: VD, init: Boolean = false, degVertices: ArrayBuffer[(VertexId, Int)]) case class VertexDegInfo[VD: ClassTag](var attr: VD, init: Boolean = false, degVertices: ArrayBuffer[(VertexId, Int)]) private def sendMsg[VD: ClassTag](e: EdgeContext[DegVertex[VD], Int, ArrayBuffer[(VertexId, Int)]], sendFilter: (VD, VD) => Boolean): Unit = {
try {
val src = e.srcAttr
val dst = e.dstAttr
//只有dst是ready状态才接收消息
if (src.degVertices.size < maxNDegVerticesCount && (src.init || dst.init) && dst.degVertices.size < maxNDegVerticesCount && !isAttrSame(src, dst)) {
if (sendFilter(src.attr, dst.attr)) {
e.sendToDst(reduceVertexIds(src.degVertices))
}
if (sendFilter(dst.attr, dst.attr)) {
e.sendToSrc(reduceVertexIds(dst.degVertices))
}
}
} catch {
case ex: Exception =>
println(s"==========error found: exception:${ex.getMessage}," +
s"edgeTriplet:(srcId:${e.srcId},srcAttr:(${e.srcAttr.attr},${e.srcAttr.init},${e.srcAttr.degVertices.size}))," +
s"dstId:${e.dstId},dstAttr:(${e.dstAttr.attr},${e.dstAttr.init},${e.dstAttr.degVertices.size}),attr:${e.attr}")
ex.printStackTrace()
throw ex
}
} private def reduceVertexIds(ids: ArrayBuffer[(VertexId, Int)]): ArrayBuffer[(VertexId, Int)] = ArrayBuffer() ++= ids.reduceByKey(Math.min) private def isAttrSame[VD: ClassTag](a: DegVertex[VD], b: DegVertex[VD]): Boolean = a.init == b.init && allKeysAreSame(a.degVertices, b.degVertices) private def allKeysAreSame(a: ArrayBuffer[(VertexId, Int)], b: ArrayBuffer[(VertexId, Int)]): Boolean = {
val aKeys = a.map(e => e._1).toSet
val bKeys = b.map(e => e._1).toSet
if (aKeys.size != bKeys.size || aKeys.isEmpty) return false aKeys.diff(bKeys).isEmpty && bKeys.diff(aKeys).isEmpty
}
}
其中sortResult方法里对Traversable[(K,V)]类型的集合使用了reduceByKey方法,这个方法是自行封装的,使用时需要导入,代码如下:
/**
* Created by yepei.ye on 2016/12/21.
* Description:
*/
object CollectionUtil {
/**
* 对具有Traversable[(K, V)]类型的集合添加reduceByKey相关方法
*
* @param collection
* @param kt
* @param vt
* @tparam K
* @tparam V
*/
implicit class CollectionHelper[K, V](collection: Traversable[(K, V)])(implicit kt: ClassTag[K], vt: ClassTag[V]) {
def reduceByKey(f: (V, V) => V): Traversable[(K, V)] = collection.groupBy(_._1).map { case (_: K, values: Traversable[(K, V)]) => values.reduce((a, b) => (a._1, f(a._2, b._2))) } /**
* reduceByKey的同时,返回被reduce掉的元素的集合
*
* @param f
* @return
*/
def reduceByKeyWithReduced(f: (V, V) => V)(implicit kt: ClassTag[K], vt: ClassTag[V]): (Traversable[(K, V)], Traversable[(K, V)]) = {
val reduced: ArrayBuffer[(K, V)] = ArrayBuffer()
val newSeq = collection.groupBy(_._1).map {
case (_: K, values: Traversable[(K, V)]) => values.reduce((a, b) => {
val newValue: V = f(a._2, b._2)
val reducedValue: V = if (newValue == a._2) b._2 else a._2
val reducedPair: (K, V) = (a._1, reducedValue)
reduced += reducedPair
(a._1, newValue)
})
}
(newSeq, reduced.toTraversable)
}
}
}
SparkGraphx计算指定节点的N度关系节点的更多相关文章
- JavaScript---网络编程(7)-Dom模型(节点间的层次关系,节点的增、删、改)
利用节点间的层次关系获取节点: 上一节讲了3中获取的方式: * ※※一.绝对获取,获取元素的3种方式:-Element * 1.getElementById(): 通过标签中的id属性值获来取该标签对 ...
- 基于Spark GraphX计算二度关系
关系计算问题描述 二度关系是指用户与用户通过关注者为桥梁发现到的关注者之间的关系.目前微博通过二度关系实现了潜在用户的推荐.用户的一度关系包含了关注.好友两种类型,二度关系则得到关注的关注.关注的好友 ...
- Spark 计算人员三度关系
1.一度人脉:双方直接是好友 2.二度人脉:双方有一个以上共同的好友,这时朋友网可以计算出你们有几个共同的好友并且呈现数字给你.你们的关系是: 你->朋友->陌生人 3.三度人脉:即你朋友 ...
- Spark 计算人员二度关系
1.一度人脉:双方直接是好友 2.二度人脉:双方有一个以上共同的好友,这时朋友网可以计算出你们有几个共同的好友并且呈现数字给你.你们的关系是: 你->朋友->陌生人 3.三度人脉:即你朋友 ...
- DOM节点关系,节点关系
DOM节点关系 定义 节点中的各种关系可以用传统的家族关系来描述,相当于把文档树比喻成家谱. 属性 [nodeType.nodeName.nodeValue] 每个节点都有这三个属性,且节点类型不同, ...
- js小功能合集:计算指定时间距今多久、评论树核心代码、字符串替换和去除。
1.计算指定时间距今多久 var date1=new Date('2017/02/08 17:00'); //开始时间 var date2=new Date(); //当前时间 var date3=d ...
- 探索未知种族之osg类生物---状态树与渲染树以及节点树之间的关系
节点树 首先我们来看一个场景构建的实例,并通过它来了解一下“状态节点”StateGraph 和“渲染叶”RenderLeaf 所构成的状态树,“渲染台”RenderStage 和“渲染元”Render ...
- GraphX实现N度关系
背景 本文给出了一个简单的计算图中每一个点的N度关系点集合的算法,也就是N跳关系. 之前通过官方文档学习和理解了一下GraphX的计算接口. N度关系 目标: 在N轮里.找到某一个点的N度关系的点集合 ...
- MySQL 树形结构 根据指定节点 获取其所有叶子节点
背景说明 需求:MySQL树形结构, 根据指定的节点,获取其下属的所有叶子节点. 叶子节点:如果一个节点下不再有子节点,则为叶子节点. 问题分析 1.可以使用类似Java这种面向对象的语言,对节点集合 ...
随机推荐
- 【12c OCP】CUUG OCP认证071考试原题解析(34)
34.choose two View the Exhibit and examine the structure of the PRODUCT_INFORMATION and INVENTORIES ...
- 多个音频audio2
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- WEB基础技术(汇聚页)
WEB基础技术(汇聚页) ------------------------------------------------- WEB WEB概述 HTML CSS JavaScript JavaScr ...
- 浅析Postgres中的并发控制(Concurrency Control)与事务特性(下)
上文我们讨论了PostgreSQL的MVCC相关的基础知识以及实现机制.关于PostgreSQL中的MVCC,我们只讲了元组可见性的问题,还剩下两个问题没讲.一个是"Lost Update& ...
- 43.oracle同义词
不愿长大,好多人如此,其实这是一种逃避责任没有担当的表象. 同义词 从字面上理解就是别名的意思,和视图的功能类似,就是一张映射关系. 私有同义词:一般是普通用户自己建立的同义词,创建者需要create ...
- web环境中的spring MVC
1. web.xml文件的简单详解 在web环境中, spring MVC是建立在IOC容器的基础上,要了解spring mvc,首先要了解Spring IOC容器是如何在web环境中被载入并起作用的 ...
- Eclipse 的SVN 的分支
分支 概念 在版本控制过程中,使用多个分支同时推进多个不同功能开发. 不使用分支开发:人与人之间协作 使用分支开发:小组和小组之间协作 作用 多个功能开发齐头并进同时进行 任何一个分支上功能 ...
- Could not parse UiSelector argument: 'XXX' is not a string 错误解决办法
ebDriverWait(driver,20).until(EC.visibility_of_element_located((MobileBy.ANDROID_UIAUTOMATOR,new UiS ...
- 对 云寻觅贴吧(http://tieba.yunxunmi.com/)的简要分析
1. 云寻觅的用户需求:一方面是很多用户有很多问题,需要高质量的答案,但是搜索引擎无法满足这种需求,百度知道做得不够好,所以用户需要一个平台可以解决他们的问题:另外一方面,又有很多经济良好,时间较为充 ...
- IT人生的价值和意义 感觉真的有了
为了做新闻APP,我居然短短一个月利用业余时间做了: 一个通用新闻采集器. 一个新闻后台审核网站. 一个通用采集器下载网站. 一个新闻微网站. 一个新闻APP, 而且还给新闻微网站和新闻 APP练就 ...