开发者社区> 仔仔930628> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

Graphx处理janusGraph数据实现

简介: Graphx处理janusGraph数据实现
+关注继续查看

声明:
此方案是在spark直接执行gremlinSQL方案实现受阻的情况下的备选方案,不涉及工作机密,不存在泄密可能,纯属个人思考,希望抛砖引玉

方案:
将gremlinSql的查询结果转化为startGraph,然后转写到HDFS,spark读取hdfs的starGraphJSon构建graphx可用的图,然后就可以调用graphx丰富的图计算算法;从而将实现graphX操作janusgraph的目的

1. gremlinSql的查询结果转换成starGraphJson

由于org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter保存的graphSon格式无法满足需求,所以将查询出的带path的点边数据自己转换成单点图的json结构,转化方法如下,然后存到hdfs,存储方法不再赘述。

public StringBuilder generatorStarGraphJson(Vertex vertex, Edge edge, StringBuilder starGraphJson){
    String inVId;
    String outVId;
    String VId;
    starGraphJson.append("{").append("\"id\":"+vertex.id()+","+"\"label\":\""+vertex.label()+"\",");
    //这种情况有outE和inE,outE中会有inV信息,inE会有一个inV
    inVId = edge.inVertex().id().toString();
    outVId = edge.outVertex().id().toString();
    VId = vertex.id().toString();
    if(inVId.equalsIgnoreCase(VId)){
        starGraphJson.append("\"outE\":{").append("\""+edge.label()+"\":[{").append("\"id\":\""+edge.id()+"\",")
                .append("\"inV\":"+edge.inVertex().id()+",").append("\"properties\":{"+concatEdgeProperties(edge)+"}}]},");
    }else if(outVId.equalsIgnoreCase(VId)){
        starGraphJson.append("\"inE\":{").append("\""+edge.label()+"\":[{").append("\"id\":\""+edge.id()+"\",")
                .append("\"outV\":"+edge.inVertex().id()+",").append("\"properties\":{"+concatEdgeProperties(edge)+"}}]},");
    }else{
        throw new Exception("点边不对应数据错误!!!");
    }
    //拼接点的properties
    starGraphJson.append("\"properties\":{").append(concatVertexProperties(vertex)).append("}}");
    return  starGraphJson;
}

2. spark读取指定路径的starGraph转成graph

class GraphSon2GraphXRDD() extends Serializable {

def getGraphConf(HDFSFilePath : String): BaseConfiguration ={ val inputGraphConf = new BaseConfiguration inputGraphConf.setProperty("gremlin.graph", classOf\[HadoopGraph\].getName) inputGraphConf.setProperty(Constants.GREMLIN\_HADOOP\_GRAPH\_READER, classOf\[GraphSONInputFormat\].getName) inputGraphConf.setProperty(Constants.GREMLIN\_HADOOP\_INPUT\_LOCATION, HDFSFilePath) inputGraphConf.setProperty(Constants.MAPREDUCE\_INPUT\_FILEINPUTFORMAT_INPUTDIR, HDFSFilePath) inputGraphConf }

def getSc(sparkHost:String ,isRemote:Boolean): SparkContext ={ var sparkConf = new SparkConf() if(isRemote){ //待完善 }else{ sparkConf.setMaster("local\[*\]").setAppName("GraphSon2GraphX") } val sc = new SparkContext(sparkConf) sc }

def getJavaRDD(conf : BaseConfiguration, sc : SparkContext): JavaPairRDD\[AnyRef, VertexWritable\] ={ val jsc = JavaSparkContext.fromSparkContext(sc) val graphRDDInput = new InputFormatRDD val vertexWritableJavaPairRDD = graphRDDInput.readGraphRDD(conf, jsc) vertexWritableJavaPairRDD }

def getVertexRDD(vertexWritableJavaPairRDD : JavaPairRDD\[AnyRef, VertexWritable\]): RDD\[(Long,util.HashMap\[String,java.io.Serializable\])\] ={ vertexWritableJavaPairRDD.rdd.map((tuple2: Tuple2\[AnyRef, VertexWritable\]) => { // Get the center vertex val v = tuple2._2.get val g = StarGraph.of(v) // In case the vertex id in TinkerGraph is not long type // val vid = convertStringIDToLongID([v.id](http://v.id)().toString) val vid = [v.id](http://v.id)().toString.toLong // Pass the vertex properties to GraphX vertex value map and remain the original vertex id var graphxValueMap : util.HashMap\[String,java.io.Serializable\] = new util.HashMapString,java.io.Serializable graphxValueMap.put("originalID",[v.id](http://v.id)().toString) graphxValueMap.putAll(g.traversal.V([v.id](http://v.id)).valueMap().next(1).get(0)) (vid,graphxValueMap) }) }

def getEdgeRDD(vertexWritableJavaPairRDD : JavaPairRDD\[AnyRef, VertexWritable\]): RDD\[graphx.Edge\[util.HashMap\[String, java.io.Serializable\]\]\] ={ val edge = vertexWritableJavaPairRDD.rdd.flatMap((tuple2: Tuple2\[AnyRef, VertexWritable\]) => { val v = tuple2._2.get val g = StarGraph.of(v) val edgelist:util.List\[Edge\] = g.traversal.V([v.id](http://v.id)).outE().toList

  // Put all edges of the center vertex into the list
  val list = new collection.mutable.ArrayBuffer[graphx.Edge[util.HashMap[String,java.io.Serializable]]]()
  var x = 0
  for(x <- 0 until edgelist.size()){
    var srcId = edgelist.get(x).inVertex.id().toString
    var dstId = edgelist.get(x).outVertex.id().toString
    //        val md1 = convertStringIDToLongID(srcId)
    //        val md2 = convertStringIDToLongID(dstId)
    val md1 = srcId.toLong
    val md2 = dstId.toLong
    // Get the properties of the edge
    var edgeAttr = new util.HashMap[String,java.io.Serializable]()
    var perporties : util.Iterator[Property[Nothing]] = edgelist.get(x).properties()
    while(perporties.hasNext){
      val property = perporties.next()
      edgeAttr.put(property.key(),property.value().toString)
    }
    list.append(graphx.Edge(md1,md2,edgeAttr))
  }
  list
})
val edgeRDD = edge.distinct()
edgeRDD

}

def doLAP(vertexWritableJavaPairRDD : JavaPairRDD\[AnyRef, VertexWritable\], iterationNum : Int): Array\[Array\[String\]\] = { val vertexRDD = getVertexRDD(vertexWritableJavaPairRDD)

val edgeRDD = getEdgeRDD(vertexWritableJavaPairRDD)

val graph = graphx.Graph[util.HashMap[String,java.io.Serializable],
  util.HashMap[String,java.io.Serializable]](vertexRDD,edgeRDD,new util.HashMap[String,java.io.Serializable]())

val LVMRsult = lib.LabelPropagation.run(graph , iterationNum).vertices.collect.sortWith (_._1 < _._1).map(f => {
  println(f.toString())
  f})
getFinalCommunit(LVMRsult)

}

def getFinalCommunit(LVMRsult:Array\[(Long,Long)\]): Array\[Array\[String\]\] ={ var result = new Array[Array\[String\]](LVMRsult.length) var tmp = new ArrayBufferString for(i <- 0 until LVMRsult.length){ var k = 0 val array = new ArrayBufferString
  //社区中包含多个值
  for(j &lt;- (i+1) until LVMRsult.length) {
    if(LVMRsult(i)._2.equals(LVMRsult(j)._2)){
      if(!tmp.contains(LVMRsult(i)._1.toString)){
        array += LVMRsult(i)._1.toString
        tmp += LVMRsult(i)._1.toString
      }
      if(!tmp.contains(LVMRsult(j)._1.toString)){
        array += LVMRsult(j)._1.toString
        tmp += LVMRsult(j)._1.toString
      }
      k = k+1
    }
  }

  //自己为一个社区
  if(k.equals(0)){
    if(!tmp.contains(LVMRsult(i)._1.toString)){
      array += LVMRsult(i)._1.toString
      tmp += LVMRsult(i)._1.toString
    }

  }
  if(array.length &gt; 0){
    result.update(i,array.toArray.distinct)
  }
}
result.filter(f =&gt; {
  println(if (f.length &gt;0) f.mkString("(",",",")"))
  f != null
})

}

def doPageRank(vertexWritableJavaPairRDD : JavaPairRDD\[AnyRef, VertexWritable\], stopThreshold : Double): Array\[Array\[Any\]\] = { val vertexRDD:RDD\[(Long,util.HashMap\[String,java.io.Serializable\])\] = getVertexRDD(vertexWritableJavaPairRDD)


val edgeRDD = getEdgeRDD(vertexWritableJavaPairRDD)

val graph = graphx.Graph[util.HashMap[String,java.io.Serializable],
  util.HashMap[String,java.io.Serializable]](vertexRDD,edgeRDD,new util.HashMap[String,java.io.Serializable]())
val gpgraph = graph.pageRank(stopThreshold).cache()

val titleAndPrGraph = graph.outerJoinVertices(gpgraph.vertices) {
  (v, title, rank) =&gt; (rank.getOrElse(0.0), title)
}

//倒序 false  正序 true

// titleAndPrGraph.vertices.sortBy((entry: (VertexId, (Double, Object))) => entry.\_2.\_1, false).foreach(f => println(f.\_1+":"+f.\_2._1))

val pageRank = titleAndPrGraph.vertices.sortBy((entry: (VertexId, (Double, Object))) =&gt; entry._2._1, false).map(f =&gt; {
  println(f._1+":"+f._2._1)
  Array(f._1.toString,f._2._1)
})
pageRank.collect()

}

}

这样就贯通了janusgraph和graphx,调用graphx的丰富的图计算功能就畅通无阻,就是实现有点挫,希望抛砖引玉

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
Hyperledger Fabric 2.x Java区块链应用
在上一篇文章中分享了智能合约的安装并使用cli客户端进行合约的调用;本文将使用Java代码基于fabric-gateway-java进行区块链网络的访问与交易,并集成SpringBoot框架。
99 0
阿里云 Linux 系统挂载数据盘:适用系统:Linux(Redhat , CentOS,Debian,Ubuntu)
阿里云 Linux 系统挂载数据盘:   适用系统:Linux(Redhat , CentOS,Debian,Ubuntu)   Linux的云服务器数据盘未做分区和格式化,可以根据以下步骤进行分区 Linux 系统挂载数据盘:   适用系统:Linux(Redhat , CentOS,Debian,Ubuntu) *  Linux的云服务器数据盘未做分区和格式化,可以根据以下步骤进行分区以及格式化操作。
3038 0
哟哟哟,JAVA组装的聊天室,最简单的实现
太码多码码,总是多些感觉~~~ 打了快一个小时啊, 但看着一行一行的出来, 还是有成就感的~~:) VerySimpleChatServer.java import java.io.*; import java.
885 0
NIO Framework 助你简单实现 Java 的异步网络通讯
Netty-socketio Overview This project is an open-source Java implementation of Socket.IO server. Based on Netty server framework. Checkout Demo project Licensed under the Apache License 2.0. HttpAsyncClient  0  项目介绍: HttpAsyncClient是一个异步的HTTP客户端开发包,是基于HttpCore NIO和HttpClient组件。
1401 0
Java面向对象基础--实现单向链表

1、设计节点类

以string为数据保存内容,还必须有一个属性保存下一个节点的引用地址。
class Node{		// 定义节点类
	private String data ;	// 保存节点内容
	private Node next ;		// 表示保存下一个节点
	p
957 0
+关注
仔仔930628
致力于hadoop全栈
16
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
冬季实战营第三期:MySQL数据库进阶实战
立即下载