Given user data in users.txt and follower data in followers.txt, with the column name is as illustrated, calculate pageRank with tolerence at 0.0001 for each user, sort the output by rank.
users.txt (user id, username, name)
1,BarackObama,Barack Obama
2,ladygaga,Goddess of Love
3,jeresig,John Resig
4,justinbieber,Justin Bieber
6,matei_zaharia,Matei Zaharia
7,odersky,Martin Odersky
8,anonsys
followers.txt: (follower user id, to be followed user id)
2 1
4 1
1 2
6 3
7 3
7 6
6 7
3 7
Code:
import org.apache.spark._
import org.apache.spark.graphx._
import org.apache.spark.rdd.RDD
import org.apache.spark.graphx.GraphLoader
// Load the edges as a graph
val graph = GraphLoader.edgeListFile(sc, "file:///home/dv6/spark/spark/data/graphx/followers.txt")
// Run PageRank, with 0.0001 as tolerence
val ranks = graph.pageRank(0.0001).vertices
ranks.foreach(println)
/*
user id, ranking
(4,0.15007622780470478)
(6,0.7017164142469724)
(2,1.3907556008752426)
(1,1.4596227918476916)
(3,0.9998520559494657)
(7,1.2979769092759237)
*/
// Join the ranks with the usernames
val users = sc.textFile("file:///home/dv6/spark/spark/data/graphx/users.txt").map { line =>
val fields = line.split(",")
(fields(0).toLong, fields(1))
}
val ranksByUsername = users.join(ranks).map {
case (id, (username, rank)) => (username, rank)
}
ranksByUsername.foreach(println)
/*
Output:
(BarackObama,1.4596227918476916)
(jeresig,0.9998520559494657)
(odersky,1.2979769092759237)
(justinbieber,0.15007622780470478)
(matei_zaharia,0.7017164142469724)
(ladygaga,1.3907556008752426)
*/
//Sortby ranking
ranksByUsername.toDF.withColumnRenamed("_1","username")
.withColumnRenamed("_2","rank")
.createOrReplaceTempView("ranksByusername")
spark.sql("select * from ranksByusername order by rank desc").show()
/*
Output:
+-------------+-------------------+
| username| rank|
+-------------+-------------------+
| BarackObama| 1.4596227918476916|
| ladygaga| 1.3907556008752426|
| odersky| 1.2979769092759237|
| jeresig| 0.9998520559494657|
|matei_zaharia| 0.7017164142469724|
| justinbieber|0.15007622780470478|
+-------------+-------------------+
*/