Spark GraphX 入门实例完整scala代码

Scala编译graphX PageRank算法的简单实例 注意: 使用GraphLoader函数时对于Scala、Spark版本有兼容问题。 由于之前scalaVersion用的别的版本,所以一直出现版本不兼容的问题,导致代码无法生成jar包 Error:scalac: bad symbolic reference to org.apache.spark.Logging encountered in class file’GraphLoader.cla... 阅读详情

由于天然符合互联网中很多场景的需求,图计算正受到越来越多的青睐。Spark GraphX 是作为 Spark 技术堆栈中的一员,担负起了 Spark 在图计算领域中的重任。网络上已经有很多图计算和 Spark GraphX 的概念介绍,此处就不再赘述。 本文将一篇很好的 Spark GraphX 入门文章中代码块整合为一个完整的可执行类,并加上必要注释以及执行结果,以方便有兴趣的朋友快速从 API 角度了解 Spark GraphX。

本文引用的代码块和多数文字描述均摘引自网文 graph-analytics-with-graphx, 在此特向作者表以感谢!


[1] 完整可执行scala 代码:

package scala.spark.graphx

import org.apache.spark.graphx._
import org.apache.spark.rdd.RDD
import org.apache.spark._
import org.apache.spark.SparkContext._

object GraphXExample {
  def main(args: Array[String]) {

    val conf = new SparkConf().setAppName("GraphXExample")
    val sc = new SparkContext(conf)

    // [A] creating the Property Graph from arrays of vertices and edges
    println("[A] creating the Property Graph from arrays of vertices and edges");
    // Each vertex is keyed by a unique 64-bit long identifier (VertexID), like '1L'
    val vertexArray = Array(
      (1L, ("Alice", 28)),
      (2L, ("Bob", 27)),
      (3L, ("Charlie", 65)),
      (4L, ("David", 42)),
      (5L, ("Ed", 55)),
      (6L, ("Fran", 50)))
    // the Edge class stores a srcId, a dstId and the edge property
    val edgeArray = Array(
      Edge(2L, 1L, 7),
      Edge(2L, 4L, 2),
      Edge(3L, 2L, 4),
      Edge(3L, 6L, 3),
      Edge(4L, 1L, 1),
      Edge(5L, 2L, 2),
      Edge(5L, 3L, 8),
      Edge(5L, 6L, 3))

    // construct the following RDDs from the vertexArray and edgeArray variables.
    val vertexRDD: RDD[(Long, (String, Int))] = sc.parallelize(vertexArray)
    val edgeRDD: RDD[Edge[Int]] = sc.parallelize(edgeArray)

    // build a Property Graph
    val graph: Graph[(String, Int), Int] = Graph(vertexRDD, edgeRDD)

    // [B] Extract the vertex and edge RDD views of a graph
    println("[B] Extract the vertex and edge RDD views of a graph");
    // Solution 1
    println("Solution 1:============")
    graph.vertices.filter { case (id, (name, age)) => age > 30 }.collect.foreach {
      case (id, (name, age)) => println(s"$name is $age")
    }

    // Solution 2
    println("Solution 2:============")
    graph.vertices.filter(v => v._2._2 > 30).collect.foreach(v => println(s"${v._2._1} is ${v._2._2}"))

    // Solution 3
    println("Solution 3:============")
    for ((id, (name, age)) <- graph.vertices.filter { case (id, (name, age)) => age > 30 }.collect) {
      println(s"$name is $age")
    }

    // [C] Exposes a triplet view which logically joins the vertex and edge properties yielding an RDD[EdgeTriplet[VD, ED]]
    println("[C] Exposes a triplet view which logically joins the vertex and edge properties yielding an RDD[EdgeTriplet[VD, ED]]");
    println("Use the graph.triplets view to display who likes who: ")
    for (triplet <- graph.triplets.collect) {
      println(s"${triplet.srcAttr._1} likes ${triplet.dstAttr._1}")
    }

    // For extra credit, find the lovers.
    // If someone likes someone else more than 5 times than that relationship is getting pretty serious.
    println("For extra credit, find the lovers if has:============")
    for (triplet <- graph.triplets.filter(t => t.attr > 5).collect) {
      println(s"${triplet.srcAttr._1} loves ${triplet.dstAttr._1}")
    }

    // [D] Graph Operators
    // Property Graphs also have a collection of basic operations
    println("[D] Graph Operators")

    // compute the in-degree of each vertex
    val inDegrees: VertexRDD[Int] = graph.inDegrees

    // Define a class to more clearly model the user property
    case class User(name: String, age: Int, inDeg: Int, outDeg: Int)
    // Create a user Graph
    val initialUserGraph: Graph[User, Int] = graph.mapVertices { case (id, (name, age)) => User(name, age, 0, 0) }

    // Fill in the degree information
    val userGraph = initialUserGraph.outerJoinVertices(initialUserGraph.inDegrees) {
      case (id, u, inDegOpt) => User(u.name, u.age, inDegOpt.getOrElse(0), u.outDeg)
    }.outerJoinVertices(initialUserGraph.outDegrees) {
      case (id, u, outDegOpt) => User(u.name, u.age, u.inDeg, outDegOpt.getOrElse(0))
    }

    // Here we use the outerJoinVertices method of Graph which has the following (confusing) type signature:
    // def outerJoinVertices[U, VD2](other: RDD[(VertexID, U)])(mapFunc: (VertexID, VD, Option[U]) => VD2): Graph[VD2, ED]

    // Using the degreeGraph print the number of people who like each user:
    println("Using the degreeGraph print the number of people who like each user:============")
    for ((id, property) <- userGraph.vertices.collect) {
      println(s"User $id is called ${property.name} and is liked by ${property.inDeg} people.")
    }

    // Print the names of the users who are liked by the same number of people they like.
    userGraph.vertices.filter {
      case (id, u) => u.inDeg == u.outDeg
    }.collect.foreach {
      case (id, property) => println(property.name)
    }

    // [D.1] The Map Reduce Triplets Operator
    // The mapReduceTriplets operator enables neighborhood aggregation and find the oldest follower of each user
    println("[D.1] The Map Reduce Triplets Operator")
    // Find the oldest follower for each user
    println("Find the oldest follower for each user:============")
    val oldestFollower: VertexRDD[(String, Int)] = userGraph.mapReduceTriplets[(String, Int)](
      // For each edge send a message to the destination vertex with the attribute of the source vertex
      edge => Iterator((edge.dstId, (edge.srcAttr.name, edge.srcAttr.age))),
      // To combine messages take the message for the older follower
      (a, b) => if (a._2 > b._2) a else b)
    userGraph.vertices.leftJoin(oldestFollower) { (id, user, optOldestFollower) =>
      optOldestFollower match {
        case None => s"${user.name} does not have any followers."
        case Some((name, age)) => s"${name} is the oldest follower of ${user.name}."
      }
    }.collect.foreach { case (id, str) => println(str) }

    // Try finding the average follower age of the followers of each user
    println("Try finding the average follower age of the followers of each user:============")
    val averageAge: VertexRDD[Double] = userGraph.mapReduceTriplets[(Int, Double)](
      // map function returns a tuple of (1, Age)
      edge => Iterator((edge.dstId, (1, edge.srcAttr.age.toDouble))),
      // reduce function combines (sumOfFollowers, sumOfAge)
      (a, b) => ((a._1 + b._1), (a._2 + b._2))).mapValues((id, p) => p._2 / p._1)

    // Display the results
    userGraph.vertices.leftJoin(averageAge) { (id, user, optAverageAge) =>
      optAverageAge match {
        case None => s"${user.name} does not have any followers."
        case Some(avgAge) => s"The average age of ${user.name}\'s followers is $avgAge."
      }
    }.collect.foreach { case (id, str) => println(str) }

    // [D.2] Subgraph
    // The subgraph operator that takes vertex and edge predicates and returns the graph 
    // containing only the vertices that satisfy the vertex predicate (evaluate to true) 
    // and edges that satisfy the edge predicate and connect vertices that satisfy the 
    // vertex predicate.
    println("[D.2] Subgraph")
    // restrict our graph to the users that are 30 or older
    println("restrict our graph to the users that are 30 or older:============")
    val olderGraph = userGraph.subgraph(vpred = (id, user) => user.age >= 30)
    // compute the connected components
    val cc = olderGraph.connectedComponents
    // display the component id of each user:
    olderGraph.vertices.leftJoin(cc.vertices) {
      case (id, user, comp) => s"${user.name} is in component ${comp.get}"
    }.collect.foreach { case (id, str) => println(str) }

  }

}


[2] 执行结果:

[A] creating the Property Graph from arrays of vertices and edges
[B] Extract the vertex and edge RDD views of a graph
Solution 1:============
David is 42
Fran is 50
Charlie is 65
Ed is 55
Solution 2:============
David is 42
Fran is 50
Charlie is 65
Ed is 55
Solution 3:============
David is 42
Fran is 50
Charlie is 65
Ed is 55
[C] Exposes a triplet view which logically joins the vertex and edge properties yielding an RDD[EdgeTriplet[VD, ED]]
Use the graph.triplets view to display who likes who: 
Bob likes Alice
Bob likes David
Charlie likes Bob
Charlie likes Fran
David likes Alice
Ed likes Bob
Ed likes Charlie
Ed likes Fran
For extra credit, find the lovers if has:============
Bob loves Alice
Ed loves Charlie
[D] Graph Operators
Using the degreeGraph print the number of people who like each user:============
User 4 is called David and is liked by 1 people.
User 6 is called Fran and is liked by 2 people.
User 2 is called Bob and is liked by 2 people.
User 1 is called Alice and is liked by 2 people.
User 3 is called Charlie and is liked by 1 people.
User 5 is called Ed and is liked by 0 people.
David
Bob
[D.1] The Map Reduce Triplets Operator
Find the oldest follower for each user:============
Bob is the oldest follower of David.
Charlie is the oldest follower of Fran.
Charlie is the oldest follower of Bob.
David is the oldest follower of Alice.
Ed is the oldest follower of Charlie.
Ed does not have any followers.
Try finding the average follower age of the followers of each user:============
The average age of David's followers is 27.0.
The average age of Fran's followers is 60.0.
The average age of Bob's followers is 60.0.
The average age of Alice's followers is 34.5.
The average age of Charlie's followers is 55.0.
Ed does not have any followers.
[D.2] Subgraph
restrict our graph to the users that are 30 or older:============
David is in component 4
Fran is in component 3
Charlie is in component 3
Ed is in component 3

Spark GraphX宝刀出鞘,图文并茂研习图计算秘笈与熟练的掌握Scala语言【大数据Spark实战高手之路】 Spark GraphX宝刀出鞘,图文并茂研习图计算秘笈       大数据的概念与应用,正随着智能手机、平板电脑的快速流行而日渐普及,大数据中图的并行化处理一直是一个非常热门的话题。图计算正在被广泛地应用于社交网络、电子商务,地图等领域。对于图计算的两个核心问题:图存储模式和图计算模型,Spark GraphX给出了近乎完美的答案,       而Spark GraphX作为图计 阅读详情

相关推荐

避坑指南:在IntelliJ IDEA里跑通Spark GraphX第一个图程序(基于Scala 2.12)

本文详细指导如何在IntelliJ IDEA中配置并运行基于Scala 2.12的Spark GraphX图程序,涵盖环境搭建、依赖配置、构建图及常见问题解决。重点解决版本兼容、依赖冲突等典型问题,并提供完整可运行示例和性能优化建议,帮助开发者快速上手Spark GraphX开发。

sym19862006的专栏 412

Spark—GraphX实战 OneID

ID Mapping 是OneID 的提前,OneID 是ID Mapping 的结果,所以要想做OneID必须先做ID MappingOneID 是为了打通整个数据体系的数据,所以OneID 需要以服务的方式对外提供服务,在数仓里面就是作为基础表使用,对外的话我们就需要提供接口对外提供服务。

5万+

跟着罗某人认识spark和scala带你上大分

Spark是一种基于内存的快速、通用、可扩展的大数据分析计算引擎。是加州大学伯克利分校AMP实验室(Algorithms, Machines, and People Lab)开发的通用内存并行计算框架Spark得到了众多大数据公司的支持,这些公司包括Hortonworks、IBM、Intel、Cloudera、MapR、Pivotal、百度、阿里、腾讯、京东、携程、优酷土豆。当前百度的Spark已应用于大搜索、直达号、百度大数据等业务;

2301_80975885的博客 1275

Spark项目实战,详细操作图文详解(基于Spark MLlib的鸢尾花聚类项目实战、基于Spark GraphX的航班飞行网图分析)

Spark项目实战,图文教程详解释,小白可上手 1)基于MLlib的鸢尾花聚类项目实战 2)基于GraphX的航班飞行网图分析

weixin_45440484的博客 4860

大数据技术之_19_Spark学习_05_Spark GraphX 应用解析 + Spark GraphX 概述、解析 + 计算模式 + Pregel API + 图算法参考代码 + PageRank

大数据技术之_19_Spark学习_05_Spark GraphX 应用解析 + Spark GraphX 概述、解析 + 计算模式 + Pregel API + 图算法参考代码 + PageRank

黑泽君 1283

GraphX原理与代码实例讲解

1. 背景介绍 1.1 问题的由来 在大规模图处理中,面临的主要问题是如何在数十亿甚至数千亿的节点和边上进行高效的图计算。传统的单机解决方案在处理大规模图数据时会遇到硬件资源限制,而分布式计算框架如Hadoop、Spark等虽然能够处理大规模数据,但并不能很好地支持图计算的需求。因此,需要一种既能处理大规

AI天才研究院 1054

大数据Spark实战第六集 图像处理和GraphX实战

什么是图:图模式,图相关技术与使用场景 在本模块中,我们将学习 Spark 如何处理图,也就是 Spark 的图挖掘套件 GraphX。虽然图这种数据结构在最近几年中,越来越多地出现在业务场景中,但平心而论,图的使用频率相比前面所学的内容还没有那么频繁。但是,一旦有这方面的需求,无论是工程师还是科学家,都可以用 Spark 提供的解决方案很好地完成任务,甚至可以说是“屠龙技”也不为过,经过本模块的学习之后,相信你也会有这样的感受。 本课时主要围绕图这种核心结构介绍,分为以下三个部分: 图结构 图存储

fegus的博客 3003

大数据书籍-Spark Graph X实战(高清)

本书详细介绍如何利用Spark Graph组件进行图计算,并依托项目背景,对Spark图计算进行深入研究,适合Spark爱好者进行阅读

Spark入门实战系列--9.Spark图计算GraphX介绍及实例

1、GraphX介绍 1.1 GraphX应用背景 Spark GraphX是一个分布式图处理框架,它是基于Spark平台提供对图计算和图挖掘简洁易用的而丰富的接口,极大的方便了对分布式图处理的需求。 众所周知·,社交网络中人与人之间有很多关系链,例如Twitter、Facebook、微博和微信等,这些都是大数据产生的地方都需要图计算,现在的图处理基本都是分布式的图处理,而并非单机处理。Sp

yyy 1944

保姆级教程:RK3588部署yolo目标检测模型

RK3588部署yolo目标检测模型非常详细的保姆级教程

ling913的专栏 5488

CCS导入工程报错?手把手教你安装C2000编译器(附最新下载链接)

本文详细解析CCS导入工程报错的常见原因,并提供三种安装C2000编译器的解决方案(TI官网离线安装、CCS内置更新和App Center渠道)。通过版本匹配技巧和路径配置要点,帮助开发者快速解决编译器缺失问题,确保项目顺利导入和编译。

weixin_30374009的博客 664

Spark GraphX 入门实例完整Scala代码

原文:http://blog.youkuaiyun.com/samhacker/article/details/42045539 [1] 完整可执行Scala 代码: [plain] view plain copy package scala.spark.graphx      import org.apache.spark.graphx._   import org.apache.spa

3581

佳能C3025打印机扫描方法

佳能C3025彩色打印机扫描方法 步骤一、如果打印机处于休眠状态,可按图中标记的按钮唤醒打印机; 然后点击屏幕上的【扫描】 步骤二、扫描类型选择【文件】 步骤三、点击屏幕上的【地址簿】 步骤四、此时屏幕胡看到名字,如果看不到自己的名字,可往下滑动直到看到自己的名字,然后点击自己的名字,再点击右下角的【应用】 步骤五、点击【发送设置】,可看到文件格式为PDF,点击可以选择JPEG的图片格式。...

weixin_46019317的博客 2万+

spark里使用scala_如何使用带Scala的Apache Spark GraphX入门

spark里使用scala 编者注:不要错过有关如何使用Apache Spark创建数据管道应用程序的新的免费按需培训课程-在此处了解更多信息。 这篇文章将帮助您开始在MapR沙盒上将Apache Spark GraphX和Scala一起使用。 GraphX是用于图并行计算的Apache Spark组件,它基于称为图论的数学分支建立。 它是一个位于Spark核心之上的分布式图形处理框架。 ...

617

Stata: 空间面板数据模型及Stata实现

  作者:游万海 (福州大学) Stata 连享会: 知乎 | 简书 | 码云 | 优快云   来源:Golgher 和 Voss (2016)   1. 背景介绍 由于面板数据模型所具有的众多优点 (刻画个体异质性,减弱模型共线性和增加自由度等),其被广泛应用于实证计量中。在 「 Stata: 面板数据模型-一文读懂」 文中,我们已对面板数据模型进行了介绍。 然而,当研究样本涉及到多个...

Stata连享会 7万+

思科模拟器CIsco Packet Tracer利用三层交换机实现VLAN间路由

版权声明:如果对大家有帮助,大家可以自行转载的。 1.技术原理: 三层交换机具备网络层的功能,实现 VLAN 相互访问的原理是:利用三层交换机的路由功能,通过识别数据包的 IP 地址,查找路由表进行选路转发,三层交换机利用直连路由可以实现不同 VLAN 之间的相互访问。三层交换机给接口配置 IP 地址。采用 SVI(交换虚拟接口)的方式实现 VLAN 间互连。SVI 是指为交换机中的VLAN 创建...

qq_37992321的博客 1万+

实验十九 Spark实验:GraphX

实验指导: 19.1 实验目的 1.了解Spark的图计算框架GraphX的基本知识; 2.能利用GraphX进行建图; 3.能利用GraphX进行基本的图操作; 4.理解GraphX图操作的算法。 19.2 实验要求 要求实验结束时,每位学生能完成正确运行Spark GraphX的示例程序,正确上传到集群中运行得到正确的实验结果。 实验结束时能对实验代码进行一定的理解。 19....

WistWill的博客 2004

基于PLC智能立体车库控制系统设计

摘要 本系统设计以三层立体车库为研究对象,通过对立体车库的原理分析、动作流程设计和一系列的软硬件设计,达到立体车库自动化控制的目的。系统采用可编程控制器作为立体车库控制系统的控制单元,实现该系统的工艺要求,通过程序仿真调试,完成系统的各种动作要求,达到自动控制的目的。系统设计分为总体设计、硬件设计以及软件设计。按照立体车库控制系统的控制策略进行图纸设计;重点分析工艺流程图,对立体车库控制系统进行程序编译和MCGS上位机调试,通过系统的调试和修改,达到了基本控制的要求。系统设计明确了工艺要求,确定

DX884164131的博客 3600

如何将Apache Spark GraphX与Scala一起使用

编者注:不要错过有关如何使用Apache Spark创建数据管道应用程序的新的免费按需培训课程-在此处了解更多信息。 这篇文章将帮助您开始在MapR沙盒上将Apache Spark GraphX和Scala一起使用。 GraphX是用于图并行计算的Apache Spark组件,它建立在称为图论的数学分支上。 它是一个位于Spark核心之上的分布式图形处理框架。 一些图形概念概述 图形...

532

CFturbo 2024保姆级教程:从流量扬程到三维叶轮,手把手搞定离心泵水力设计

本文提供CFturbo 2024离心泵水力设计的全流程实战指南,从流量扬程参数输入到三维叶轮模型导出,详细解析设计步骤与优化技巧。涵盖叶轮尺寸确定、子午面型线设计、叶片角度调整等关键环节,帮助工程师高效完成CAE辅助的离心泵水力设计,提升设计质量与效率。

weixin_42569329的博客 933

超声波传感器(CH101&ch201) - Ⅰ

压电微机械超声换能器(PMUT)和超声波信号处理的可编程片上系统(SoC)集成在一起的传感器

nicole088的专栏 2796

Spark_GraphX安装记录

下载spark ,注意,选择直接下载似乎比较快,我开始选择镜像,结果慢的不行。 另外,手动编译需要安装sbt,这个类似maven, 很麻烦,我只是想运行下GraphX, 因此直接下载pre-built版本,可以直接运行的,无需安装sbt  然后修改配置文件 mv spark-env.sh.template spark-env.sh export HADOOP_CON

cloudeagle_bupt的专栏 2851

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

一篇文章教你如何搭建scala和spark(超详细)

Spark是一种基于内存的快速、通用、可扩展的大数据分析计算引擎。是加州大学伯克利分校AMP实验室(Algorithms, Machines, and People Lab)开发的通用内存并行计算框架Spark得到了众多大数据公司的支持,这些公司包括Hortonworks、IBM、Intel、Cloudera、MapR、Pivotal、百度、阿里、腾讯、京东、携程、优酷土豆。当前百度的Spark已应用于大搜索、直达号、百度大数据等业务;

az111gh的博客 2267

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Spark Graphx计算有向环

在工作过程中有使用到Spark Graphx做一些图的计算,开发环境如下: 开发工具:IDEA JDK:1.7.0_80 Maven:3.3.9 对于图计算,其实可以有很多技术框架等,例如使用python的networx,spark的graphx,以及阿里也有开源框架,此处我们使用Graphx为计算框架,由于个人简单案例,就以单机环境实现,并且简单数据输入。 在Graphx中,通常类似的操作可...

世界那么大,我想去看看! 948

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

04 graphx 从源节点到其他节点的路径 scala & java 版本

前言 呵呵 最近刚好有一些需要使用到 图的相关计算 然后 需求是 需要计算图中 源点 到 目标节点 的所有路径 另外本文会提供一个 scala 版本的测试用例, 以及 一个java 版本的测试用例(写的有点惨) 环境如下 : spark2.4.5 + scala2.11 + jdk8 java 版本的代码基于 :spark-graphx_2.12 2.4.6 另外 java 版本的代码, 会遇到各种问题, 这里也会 介绍一下(写出来也是很不美观, 可读性也不太好) 本文的图...

970655147的专栏 1363
上一篇: Google Protocol Buffers Java实例
下一篇: 通过 Job History Server 的 web console 查阅在 Yarn 上 MapReduce job 的 job conf xml 文件
坡上的云
博客等级 码龄20年 50粉丝 30原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值