Spark生态有GraphX的图计算模块。但它有诸多缺点:
- 性能差,不能从DataFrame和Catalyst查询优化器提供的性能改进中受益。
- 开发难度大,编写计算逻辑复杂。
- 只支持Scala语言。
GraphFrames完美解决了以上问题。它是一个构建在Sprak Graph之上的第三方开源包,但它不属于Spark生态。它扩展了GraphX以提供DataFrame API,使分析更容易使用更有效。使用户可以在不将数据移动到专门的图数据库的情况下执行图模式查询。
GraphFrames的核心抽象是GraphFrame,GraphFrame本质上由2个DataFrame组成,顶点DataFrame和边DateFrame。由于它的底层是DataFrane,自然就享受到了Catalyst优化器的性能提升,同时DataFrame是关系型结构,在编程上也简化了开发难度更易于上手。
maven中添加如下依赖
<dependency>
<groupId>graphframes</groupId>
<artifactId>graphframes</artifactId>
<version>0.8.2-spark2.4-s_2.11</version>
</dependency>
Scala代码样例
package org.example
import org.apache.spark.SparkConf
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.graphframes.GraphFrame
object GraphFrameTest {
def main(args: Array[String]): Unit = {
//创建spark运行环境
val sparkConfig = new SparkConf().setAppName("GraphFrames")
val spark: SparkSession = SparkSession.builder().config(sparkConfig).getOrCreate()
//构建GraphFrame,其中顶点的“id”和边的“src”,“dst”是常量不能改。
val vertexDataFrame :DataFrame =
spark.read.csv("hdfs://hostname:9000/vertex").toDF("id","name","age","gender")
val edgeDataFrame :DataFrame =
spark.read.csv("hdfs://hostname:9000/edge").toDF("src","dst","attr")
val g:GraphFrame = GraphFrame(vertexDataFrame,edgeDataFrame)
//图计算任务
g.vertices.filter("age > 30 and gender = '男' ").show()
g.edges.filter("attr > 5").show()
g.triplets.filter("edge.attr > 5").show()
g.outDegrees.groupBy().max().show()
spark.close()
}
}
如果依赖拉不下来就手动到官网把graphframes-0.8.2-spark2.4-s_2.11.jar拷贝到spark/jars目录下。