我很新兴,但我想从Hive表中获得的关系创建一个图表。我发现一个函数可以在不定义顶点的情况下允许它,但是我无法使它工作。
我知道这不是一个可重现的例子,但这是我的代码:
import org.apache.spark.SparkContext
import org.apache.spark.graphx._
import org.apache.spark.rdd.RDD
val sqlContext= new org.apache.spark.sql.hive.HiveContext(sc)
val data = sqlContext.sql("select year, trade_flow, reporter_iso, partner_iso, sum(trade_value_us) from comtrade.annual_hs where length(commodity_code)='2' and not partner_iso='WLD' group by year, trade_flow, reporter_iso, partner_iso").collect()
val data_2010 = data.filter(line => line(0)==2010)
val couples = data_2010.map(line=>(line(2),line(3)) //country to country
val graph = Graph.fromEdgeTuples(couples, 1)
最后一行产生以下错误:
val graph = Graph.fromEdgeTuples(sc.parallelize(couples), 1)
<console>:31: error: type mismatch;
found : Array[(Any, Any)]
required: Seq[(org.apache.spark.graphx.VertexId,org.apache.spark.graphx.VertexId)]
Error occurred in an application involving default arguments.
val graph = Graph.fromEdgeTuples(sc.parallelize(couples), 1)
夫妇看起来像这样:
couples: Array[(Any, Any)] = Array((MWI,MOZ), (WSM,AUS), (MDA,CRI), (KNA,HTI), (PER,ERI), (SWE,CUB), (DEU,PRK), (THA,DJI), (BIH,SVK), (RUS,THA), (SGP,BLR), (MEX,TGO), (TUR,ZAF), (ZWE,SYC), (UGA,GHA), (OMN,SVN), (NZL,SYR), (CHE,SLV), (CZE,LUX), (TGO,COM), (TTO,WLF), (NGA,PAN), (FJI,UKR), (BRA,ECU), (EGY,SWE), (ITA,ARG), (MUS,MLT), (MDG,DZA), (ARE,SUR), (CAN,GUY), (OMN,COG), (NAM,FIN), (ITA,HMD), (SWE,CHE), (SDN,NER), (TUN,USA), (THA,GMB), (HUN,TTO), (FRA,BEN), (NER,TCD), (CHN,JPN), (DNK,ZAF), (MLT,UKR), (ARM,OMN), (PRT,IDN), (BEN,PER), (TTO,BRA), (KAZ,SMR), (CPV,""), (ARG,ZAF), (BLR,TJK), (AZE,SVK), (ITA,STP), (MDA,IRL), (POL,SVN), (PRY,ETH), (HKG,MOZ), (QAT,GAB), (THA,MUS), (PHL,MOZ), (ITA,SGS), (ARM,KHM), (ARG,KOR), (AUT,GMB), (SYR,COM), (CZE,GBR), (DOM,USA), (CYP,LAO), (USA,LBR)
如何转换为合适的格式?
答案 0 :(得分:7)
首先,您无法将String
用作VertexId
,因此您必须将标签映射到Long
。然后,我们需要准备从label到id的映射。只要唯一值的数量相对较小,最简单的方法是创建广播变量:
val idMap = sc.broadcast(couples // -> Array[(Any, Any)]
// Make sure we use String not Any returned from Row.apply
// And convert to Seq so we can flatten results
.flatMap{case (x: String, y: String) => Seq(x, y)} // -> Array[String]
// Get different keys
.distinct // -> Array[String]
// Create (key, value) pairs
.zipWithIndex // -> Array[(String, Int)]
// Convert values to Long so we can use it as a VertexId
.map{case (k, v) => (k, v.toLong)} // -> Array[(String, Long)]
// Create map
.toMap) // -> Map[String,Long]
接下来我们可以使用上面的方法来执行映射:
val edges: RDD[(VertexId, VertexId)] = sc.parallelize(couples
.map{case (x: String, y: String) => (idMap.value(x), idMap.value(y))}
)
最后我们得到一个图表:
val graph = Graph.fromEdgeTuples(edges, 1)