• Graph API
    • Graph Representation
    • Graph Creation
    • Graph Properties
    • Graph Transformations
    • Graph Mutations
    • Neighborhood Methods
    • Graph Validation

    Graph API

    • Graph Representation
    • Graph Creation
    • Graph Properties
    • Graph Transformations
    • Graph Mutations
    • Neighborhood Methods
    • Graph Validation

    Graph Representation

    In Gelly, a Graph is represented by a DataSet of vertices and a DataSet of edges.

    The Graph nodes are represented by the Vertex type. A Vertex is defined by a unique ID and a value. Vertex IDs should implement the Comparable interface. Vertices without value can be represented by setting the value type to NullValue.

    1. // create a new vertex with a Long ID and a String value
    2. Vertex<Long, String> v = new Vertex<Long, String>(1L, "foo");
    3. // create a new vertex with a Long ID and no value
    4. Vertex<Long, NullValue> v = new Vertex<Long, NullValue>(1L, NullValue.getInstance());
    1. // create a new vertex with a Long ID and a String value
    2. val v = new Vertex(1L, "foo")
    3. // create a new vertex with a Long ID and no value
    4. val v = new Vertex(1L, NullValue.getInstance())

    The graph edges are represented by the Edge type. An Edge is defined by a source ID (the ID of the source Vertex), a target ID (the ID of the target Vertex) and an optional value. The source and target IDs should be of the same type as the Vertex IDs. Edges with no value have a NullValue value type.

    1. Edge<Long, Double> e = new Edge<Long, Double>(1L, 2L, 0.5);
    2. // reverse the source and target of this edge
    3. Edge<Long, Double> reversed = e.reverse();
    4. Double weight = e.getValue(); // weight = 0.5
    1. val e = new Edge(1L, 2L, 0.5)
    2. // reverse the source and target of this edge
    3. val reversed = e.reverse
    4. val weight = e.getValue // weight = 0.5

    In Gelly an Edge is always directed from the source vertex to the target vertex. A Graph may be undirected if forevery Edge it contains a matching Edge from the target vertex to the source vertex.

    Graph Creation

    You can create a Graph in the following ways:

    • from a DataSet of edges and an optional DataSet of vertices:
    1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    2. DataSet<Vertex<String, Long>> vertices = ...
    3. DataSet<Edge<String, Double>> edges = ...
    4. Graph<String, Long, Double> graph = Graph.fromDataSet(vertices, edges, env);
    1. val env = ExecutionEnvironment.getExecutionEnvironment
    2. val vertices: DataSet[Vertex[String, Long]] = ...
    3. val edges: DataSet[Edge[String, Double]] = ...
    4. val graph = Graph.fromDataSet(vertices, edges, env)
    • from a DataSet of Tuple2 representing the edges. Gelly will convert each Tuple2 to an Edge, where the first field will be the source ID and the second field will be the target ID. Both vertex and edge values will be set to NullValue.
    1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    2. DataSet<Tuple2<String, String>> edges = ...
    3. Graph<String, NullValue, NullValue> graph = Graph.fromTuple2DataSet(edges, env);
    1. val env = ExecutionEnvironment.getExecutionEnvironment
    2. val edges: DataSet[(String, String)] = ...
    3. val graph = Graph.fromTuple2DataSet(edges, env)
    • from a DataSet of Tuple3 and an optional DataSet of Tuple2. In this case, Gelly will convert each Tuple3 to an Edge, where the first field will be the source ID, the second field will be the target ID and the third field will be the edge value. Equivalently, each Tuple2 will be converted to a Vertex, where the first field will be the vertex ID and the second field will be the vertex value:
    1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    2. DataSet<Tuple2<String, Long>> vertexTuples = env.readCsvFile("path/to/vertex/input").types(String.class, Long.class);
    3. DataSet<Tuple3<String, String, Double>> edgeTuples = env.readCsvFile("path/to/edge/input").types(String.class, String.class, Double.class);
    4. Graph<String, Long, Double> graph = Graph.fromTupleDataSet(vertexTuples, edgeTuples, env);
    • from a CSV file of Edge data and an optional CSV file of Vertex data. In this case, Gelly will convert each row from the Edge CSV file to an Edge, where the first field will be the source ID, the second field will be the target ID and the third field (if present) will be the edge value. Equivalently, each row from the optional Vertex CSV file will be converted to a Vertex, where the first field will be the vertex ID and the second field (if present) will be the vertex value. In order to get a Graph from a GraphCsvReader one has to specify the types, using one of the following methods:

    • types(Class<K> vertexKey, Class<VV> vertexValue,Class<EV> edgeValue): both vertex and edge values are present.

    • edgeTypes(Class<K> vertexKey, Class<EV> edgeValue): the Graph has edge values, but no vertex values.
    • vertexTypes(Class<K> vertexKey, Class<VV> vertexValue): the Graph has vertex values, but no edge values.
    • keyType(Class<K> vertexKey): the Graph has no vertex values and no edge values.
    1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    2. // create a Graph with String Vertex IDs, Long Vertex values and Double Edge values
    3. Graph<String, Long, Double> graph = Graph.fromCsvReader("path/to/vertex/input", "path/to/edge/input", env)
    4. .types(String.class, Long.class, Double.class);
    5. // create a Graph with neither Vertex nor Edge values
    6. Graph<Long, NullValue, NullValue> simpleGraph = Graph.fromCsvReader("path/to/edge/input", env).keyType(Long.class);
    1. val env = ExecutionEnvironment.getExecutionEnvironment
    2. val vertexTuples = env.readCsvFile[String, Long]("path/to/vertex/input")
    3. val edgeTuples = env.readCsvFile[String, String, Double]("path/to/edge/input")
    4. val graph = Graph.fromTupleDataSet(vertexTuples, edgeTuples, env)
    • from a CSV file of Edge data and an optional CSV file of Vertex data.In this case, Gelly will convert each row from the Edge CSV file to an Edge.The first field of the each row will be the source ID, the second field will be the target ID and the third field (if present) will be the edge value.If the edges have no associated value, set the edge value type parameter (3rd type argument) to NullValue.You can also specify that the vertices are initialized with a vertex value.If you provide a path to a CSV file via pathVertices, each row of this file will be converted to a Vertex.The first field of each row will be the vertex ID and the second field will be the vertex value.If you provide a vertex value initializer MapFunction via the vertexValueInitializer parameter, then this function is used to generate the vertex values.The set of vertices will be created automatically from the edges input.If the vertices have no associated value, set the vertex value type parameter (2nd type argument) to NullValue.The vertices will then be automatically created from the edges input with vertex value of type NullValue.
    1. val env = ExecutionEnvironment.getExecutionEnvironment
    2. // create a Graph with String Vertex IDs, Long Vertex values and Double Edge values
    3. val graph = Graph.fromCsvReader[String, Long, Double](
    4. pathVertices = "path/to/vertex/input",
    5. pathEdges = "path/to/edge/input",
    6. env = env)
    7. // create a Graph with neither Vertex nor Edge values
    8. val simpleGraph = Graph.fromCsvReader[Long, NullValue, NullValue](
    9. pathEdges = "path/to/edge/input",
    10. env = env)
    11. // create a Graph with Double Vertex values generated by a vertex value initializer and no Edge values
    12. val simpleGraph = Graph.fromCsvReader[Long, Double, NullValue](
    13. pathEdges = "path/to/edge/input",
    14. vertexValueInitializer = new MapFunction[Long, Double]() {
    15. def map(id: Long): Double = {
    16. id.toDouble
    17. }
    18. },
    19. env = env)
    • from a Collection of edges and an optional Collection of vertices:
    1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    2. List<Vertex<Long, Long>> vertexList = new ArrayList...
    3. List<Edge<Long, String>> edgeList = new ArrayList...
    4. Graph<Long, Long, String> graph = Graph.fromCollection(vertexList, edgeList, env);

    If no vertex input is provided during Graph creation, Gelly will automatically produce the Vertex DataSet from the edge input. In this case, the created vertices will have no values. Alternatively, you can provide a MapFunction as an argument to the creation method, in order to initialize the Vertex values:

    1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    2. // initialize the vertex value to be equal to the vertex ID
    3. Graph<Long, Long, String> graph = Graph.fromCollection(edgeList,
    4. new MapFunction<Long, Long>() {
    5. public Long map(Long value) {
    6. return value;
    7. }
    8. }, env);
    1. val env = ExecutionEnvironment.getExecutionEnvironment
    2. val vertexList = List(...)
    3. val edgeList = List(...)
    4. val graph = Graph.fromCollection(vertexList, edgeList, env)

    If no vertex input is provided during Graph creation, Gelly will automatically produce the Vertex DataSet from the edge input. In this case, the created vertices will have no values. Alternatively, you can provide a MapFunction as an argument to the creation method, in order to initialize the Vertex values:

    1. val env = ExecutionEnvironment.getExecutionEnvironment
    2. // initialize the vertex value to be equal to the vertex ID
    3. val graph = Graph.fromCollection(edgeList,
    4. new MapFunction[Long, Long] {
    5. def map(id: Long): Long = id
    6. }, env)

    Graph Properties

    Gelly includes the following methods for retrieving various Graph properties and metrics:

    1. // get the Vertex DataSet
    2. DataSet<Vertex<K, VV>> getVertices()
    3. // get the Edge DataSet
    4. DataSet<Edge<K, EV>> getEdges()
    5. // get the IDs of the vertices as a DataSet
    6. DataSet<K> getVertexIds()
    7. // get the source-target pairs of the edge IDs as a DataSet
    8. DataSet<Tuple2<K, K>> getEdgeIds()
    9. // get a DataSet of <vertex ID, in-degree> pairs for all vertices
    10. DataSet<Tuple2<K, LongValue>> inDegrees()
    11. // get a DataSet of <vertex ID, out-degree> pairs for all vertices
    12. DataSet<Tuple2<K, LongValue>> outDegrees()
    13. // get a DataSet of <vertex ID, degree> pairs for all vertices, where degree is the sum of in- and out- degrees
    14. DataSet<Tuple2<K, LongValue>> getDegrees()
    15. // get the number of vertices
    16. long numberOfVertices()
    17. // get the number of edges
    18. long numberOfEdges()
    19. // get a DataSet of Triplets<srcVertex, trgVertex, edge>
    20. DataSet<Triplet<K, VV, EV>> getTriplets()
    1. // get the Vertex DataSet
    2. getVertices: DataSet[Vertex[K, VV]]
    3. // get the Edge DataSet
    4. getEdges: DataSet[Edge[K, EV]]
    5. // get the IDs of the vertices as a DataSet
    6. getVertexIds: DataSet[K]
    7. // get the source-target pairs of the edge IDs as a DataSet
    8. getEdgeIds: DataSet[(K, K)]
    9. // get a DataSet of <vertex ID, in-degree> pairs for all vertices
    10. inDegrees: DataSet[(K, LongValue)]
    11. // get a DataSet of <vertex ID, out-degree> pairs for all vertices
    12. outDegrees: DataSet[(K, LongValue)]
    13. // get a DataSet of <vertex ID, degree> pairs for all vertices, where degree is the sum of in- and out- degrees
    14. getDegrees: DataSet[(K, LongValue)]
    15. // get the number of vertices
    16. numberOfVertices: Long
    17. // get the number of edges
    18. numberOfEdges: Long
    19. // get a DataSet of Triplets<srcVertex, trgVertex, edge>
    20. getTriplets: DataSet[Triplet[K, VV, EV]]

    Graph Transformations

    • Map: Gelly provides specialized methods for applying a map transformation on the vertex values or edge values. mapVertices and mapEdges return a new Graph, where the IDs of the vertices (or edges) remain unchanged, while the values are transformed according to the provided user-defined map function. The map functions also allow changing the type of the vertex or edge values.
    1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    2. Graph<Long, Long, Long> graph = Graph.fromDataSet(vertices, edges, env);
    3. // increment each vertex value by one
    4. Graph<Long, Long, Long> updatedGraph = graph.mapVertices(
    5. new MapFunction<Vertex<Long, Long>, Long>() {
    6. public Long map(Vertex<Long, Long> value) {
    7. return value.getValue() + 1;
    8. }
    9. });
    1. val env = ExecutionEnvironment.getExecutionEnvironment
    2. val graph = Graph.fromDataSet(vertices, edges, env)
    3. // increment each vertex value by one
    4. val updatedGraph = graph.mapVertices(v => v.getValue + 1)
    • Translate: Gelly provides specialized methods for translating the value and/or type of vertex and edge IDs (translateGraphIDs), vertex values (translateVertexValues), or edge values (translateEdgeValues). Translation is performed by the user-defined map function, several of which are provided in the org.apache.flink.graph.asm.translate package. The same MapFunction can be used for all the three translate methods.
    1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    2. Graph<Long, Long, Long> graph = Graph.fromDataSet(vertices, edges, env);
    3. // translate each vertex and edge ID to a String
    4. Graph<String, Long, Long> updatedGraph = graph.translateGraphIds(
    5. new MapFunction<Long, String>() {
    6. public String map(Long id) {
    7. return id.toString();
    8. }
    9. });
    10. // translate vertex IDs, edge IDs, vertex values, and edge values to LongValue
    11. Graph<LongValue, LongValue, LongValue> updatedGraph = graph
    12. .translateGraphIds(new LongToLongValue())
    13. .translateVertexValues(new LongToLongValue())
    14. .translateEdgeValues(new LongToLongValue())
    1. val env = ExecutionEnvironment.getExecutionEnvironment
    2. val graph = Graph.fromDataSet(vertices, edges, env)
    3. // translate each vertex and edge ID to a String
    4. val updatedGraph = graph.translateGraphIds(id => id.toString)
    • Filter: A filter transformation applies a user-defined filter function on the vertices or edges of the Graph. filterOnEdges will create a sub-graph of the original graph, keeping only the edges that satisfy the provided predicate. Note that the vertex dataset will not be modified. Respectively, filterOnVertices applies a filter on the vertices of the graph. Edges whose source and/or target do not satisfy the vertex predicate are removed from the resulting edge dataset. The subgraph method can be used to apply a filter function to the vertices and the edges at the same time.
    1. Graph<Long, Long, Long> graph = ...
    2. graph.subgraph(
    3. new FilterFunction<Vertex<Long, Long>>() {
    4. public boolean filter(Vertex<Long, Long> vertex) {
    5. // keep only vertices with positive values
    6. return (vertex.getValue() > 0);
    7. }
    8. },
    9. new FilterFunction<Edge<Long, Long>>() {
    10. public boolean filter(Edge<Long, Long> edge) {
    11. // keep only edges with negative values
    12. return (edge.getValue() < 0);
    13. }
    14. })
    1. val graph: Graph[Long, Long, Long] = ...
    2. // keep only vertices with positive values
    3. // and only edges with negative values
    4. graph.subgraph((vertex => vertex.getValue > 0), (edge => edge.getValue < 0))

    Filter Transformations

    • Join: Gelly provides specialized methods for joining the vertex and edge datasets with other input datasets. joinWithVertices joins the vertices with a Tuple2 input data set. The join is performed using the vertex ID and the first field of the Tuple2 input as the join keys. The method returns a new Graph where the vertex values have been updated according to a provided user-defined transformation function.Similarly, an input dataset can be joined with the edges, using one of three methods. joinWithEdges expects an input DataSet of Tuple3 and joins on the composite key of both source and target vertex IDs. joinWithEdgesOnSource expects a DataSet of Tuple2 and joins on the source key of the edges and the first attribute of the input dataset and joinWithEdgesOnTarget expects a DataSet of Tuple2 and joins on the target key of the edges and the first attribute of the input dataset. All three methods apply a transformation function on the edge and the input data set values.Note that if the input dataset contains a key multiple times, all Gelly join methods will only consider the first value encountered.
    1. Graph<Long, Double, Double> network = ...
    2. DataSet<Tuple2<Long, LongValue>> vertexOutDegrees = network.outDegrees();
    3. // assign the transition probabilities as the edge weights
    4. Graph<Long, Double, Double> networkWithWeights = network.joinWithEdgesOnSource(vertexOutDegrees,
    5. new VertexJoinFunction<Double, LongValue>() {
    6. public Double vertexJoin(Double vertexValue, LongValue inputValue) {
    7. return vertexValue / inputValue.getValue();
    8. }
    9. });
    1. val network: Graph[Long, Double, Double] = ...
    2. val vertexOutDegrees: DataSet[(Long, LongValue)] = network.outDegrees
    3. // assign the transition probabilities as the edge weights
    4. val networkWithWeights = network.joinWithEdgesOnSource(vertexOutDegrees, (v1: Double, v2: LongValue) => v1 / v2.getValue)
    • Reverse: the reverse() method returns a new Graph where the direction of all edges has been reversed.

    • Undirected: In Gelly, a Graph is always directed. Undirected graphs can be represented by adding all opposite-direction edges to a graph. For this purpose, Gelly provides the getUndirected() method.

    • Union: Gelly’s union() method performs a union operation on the vertex and edge sets of the specified graph and the current graph. Duplicate vertices are removed from the resulting Graph, while if duplicate edges exist, these will be preserved.

    Union Transformation

    • Difference: Gelly’s difference() method performs a difference on the vertex and edge sets of the current graph and the specified graph.

    • Intersect: Gelly’s intersect() method performs an intersect on the edge sets of the current graph and the specified graph. The result is a new Graph that contains all edges that exist in both input graphs. Two edges are considered equal, if they have the same source identifier, target identifier and edge value. Vertices in the resulting graph have no value. If vertex values are required, one can for example retrieve them from one of the input graphs using the joinWithVertices() method. Depending on the parameter distinct, equal edges are either contained once in the resulting Graph or as often as there are pairs of equal edges in the input graphs.

    1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    2. // create first graph from edges {(1, 3, 12) (1, 3, 13), (1, 3, 13)}
    3. List<Edge<Long, Long>> edges1 = ...
    4. Graph<Long, NullValue, Long> graph1 = Graph.fromCollection(edges1, env);
    5. // create second graph from edges {(1, 3, 13)}
    6. List<Edge<Long, Long>> edges2 = ...
    7. Graph<Long, NullValue, Long> graph2 = Graph.fromCollection(edges2, env);
    8. // Using distinct = true results in {(1,3,13)}
    9. Graph<Long, NullValue, Long> intersect1 = graph1.intersect(graph2, true);
    10. // Using distinct = false results in {(1,3,13),(1,3,13)} as there is one edge pair
    11. Graph<Long, NullValue, Long> intersect2 = graph1.intersect(graph2, false);
    1. val env = ExecutionEnvironment.getExecutionEnvironment
    2. // create first graph from edges {(1, 3, 12) (1, 3, 13), (1, 3, 13)}
    3. val edges1: List[Edge[Long, Long]] = ...
    4. val graph1 = Graph.fromCollection(edges1, env)
    5. // create second graph from edges {(1, 3, 13)}
    6. val edges2: List[Edge[Long, Long]] = ...
    7. val graph2 = Graph.fromCollection(edges2, env)
    8. // Using distinct = true results in {(1,3,13)}
    9. val intersect1 = graph1.intersect(graph2, true)
    10. // Using distinct = false results in {(1,3,13),(1,3,13)} as there is one edge pair
    11. val intersect2 = graph1.intersect(graph2, false)

    -

    Graph Mutations

    Gelly includes the following methods for adding and removing vertices and edges from an input Graph:

    1. // adds a Vertex to the Graph. If the Vertex already exists, it will not be added again.
    2. Graph<K, VV, EV> addVertex(final Vertex<K, VV> vertex)
    3. // adds a list of vertices to the Graph. If the vertices already exist in the graph, they will not be added once more.
    4. Graph<K, VV, EV> addVertices(List<Vertex<K, VV>> verticesToAdd)
    5. // adds an Edge to the Graph. If the source and target vertices do not exist in the graph, they will also be added.
    6. Graph<K, VV, EV> addEdge(Vertex<K, VV> source, Vertex<K, VV> target, EV edgeValue)
    7. // adds a list of edges to the Graph. When adding an edge for a non-existing set of vertices, the edge is considered invalid and ignored.
    8. Graph<K, VV, EV> addEdges(List<Edge<K, EV>> newEdges)
    9. // removes the given Vertex and its edges from the Graph.
    10. Graph<K, VV, EV> removeVertex(Vertex<K, VV> vertex)
    11. // removes the given list of vertices and their edges from the Graph
    12. Graph<K, VV, EV> removeVertices(List<Vertex<K, VV>> verticesToBeRemoved)
    13. // removes *all* edges that match the given Edge from the Graph.
    14. Graph<K, VV, EV> removeEdge(Edge<K, EV> edge)
    15. // removes *all* edges that match the edges in the given list
    16. Graph<K, VV, EV> removeEdges(List<Edge<K, EV>> edgesToBeRemoved)
    1. // adds a Vertex to the Graph. If the Vertex already exists, it will not be added again.
    2. addVertex(vertex: Vertex[K, VV])
    3. // adds a list of vertices to the Graph. If the vertices already exist in the graph, they will not be added once more.
    4. addVertices(verticesToAdd: List[Vertex[K, VV]])
    5. // adds an Edge to the Graph. If the source and target vertices do not exist in the graph, they will also be added.
    6. addEdge(source: Vertex[K, VV], target: Vertex[K, VV], edgeValue: EV)
    7. // adds a list of edges to the Graph. When adding an edge for a non-existing set of vertices, the edge is considered invalid and ignored.
    8. addEdges(edges: List[Edge[K, EV]])
    9. // removes the given Vertex and its edges from the Graph.
    10. removeVertex(vertex: Vertex[K, VV])
    11. // removes the given list of vertices and their edges from the Graph
    12. removeVertices(verticesToBeRemoved: List[Vertex[K, VV]])
    13. // removes *all* edges that match the given Edge from the Graph.
    14. removeEdge(edge: Edge[K, EV])
    15. // removes *all* edges that match the edges in the given list
    16. removeEdges(edgesToBeRemoved: List[Edge[K, EV]])

    Neighborhood Methods

    Neighborhood methods allow vertices to perform an aggregation on their first-hop neighborhood.reduceOnEdges() can be used to compute an aggregation on the values of the neighboring edges of a vertex and reduceOnNeighbors() can be used to compute an aggregation on the values of the neighboring vertices. These methods assume associative and commutative aggregations and exploit combiners internally, significantly improving performance.The neighborhood scope is defined by the EdgeDirection parameter, which takes the values IN, OUT or ALL. IN will gather all in-coming edges (neighbors) of a vertex, OUT will gather all out-going edges (neighbors), while ALL will gather all edges (neighbors).

    For example, assume that you want to select the minimum weight of all out-edges for each vertex in the following graph:

    reduceOnEdges Example

    The following code will collect the out-edges for each vertex and apply the SelectMinWeight() user-defined function on each of the resulting neighborhoods:

    1. Graph<Long, Long, Double> graph = ...
    2. DataSet<Tuple2<Long, Double>> minWeights = graph.reduceOnEdges(new SelectMinWeight(), EdgeDirection.OUT);
    3. // user-defined function to select the minimum weight
    4. static final class SelectMinWeight implements ReduceEdgesFunction<Double> {
    5. @Override
    6. public Double reduceEdges(Double firstEdgeValue, Double secondEdgeValue) {
    7. return Math.min(firstEdgeValue, secondEdgeValue);
    8. }
    9. }
    1. val graph: Graph[Long, Long, Double] = ...
    2. val minWeights = graph.reduceOnEdges(new SelectMinWeight, EdgeDirection.OUT)
    3. // user-defined function to select the minimum weight
    4. final class SelectMinWeight extends ReduceEdgesFunction[Double] {
    5. override def reduceEdges(firstEdgeValue: Double, secondEdgeValue: Double): Double = {
    6. Math.min(firstEdgeValue, secondEdgeValue)
    7. }
    8. }

    reduceOnEdges Example

    Similarly, assume that you would like to compute the sum of the values of all in-coming neighbors, for every vertex. The following code will collect the in-coming neighbors for each vertex and apply the SumValues() user-defined function on each neighborhood:

    1. Graph<Long, Long, Double> graph = ...
    2. DataSet<Tuple2<Long, Long>> verticesWithSum = graph.reduceOnNeighbors(new SumValues(), EdgeDirection.IN);
    3. // user-defined function to sum the neighbor values
    4. static final class SumValues implements ReduceNeighborsFunction<Long> {
    5. @Override
    6. public Long reduceNeighbors(Long firstNeighbor, Long secondNeighbor) {
    7. return firstNeighbor + secondNeighbor;
    8. }
    9. }
    1. val graph: Graph[Long, Long, Double] = ...
    2. val verticesWithSum = graph.reduceOnNeighbors(new SumValues, EdgeDirection.IN)
    3. // user-defined function to sum the neighbor values
    4. final class SumValues extends ReduceNeighborsFunction[Long] {
    5. override def reduceNeighbors(firstNeighbor: Long, secondNeighbor: Long): Long = {
    6. firstNeighbor + secondNeighbor
    7. }
    8. }

    reduceOnNeighbors Example

    When the aggregation function is not associative and commutative or when it is desirable to return more than one values per vertex, one can use the more generalgroupReduceOnEdges() and groupReduceOnNeighbors() methods.These methods return zero, one or more values per vertex and provide access to the whole neighborhood.

    For example, the following code will output all the vertex pairs which are connected with an edge having a weight of 0.5 or more:

    1. Graph<Long, Long, Double> graph = ...
    2. DataSet<Tuple2<Vertex<Long, Long>, Vertex<Long, Long>>> vertexPairs = graph.groupReduceOnNeighbors(new SelectLargeWeightNeighbors(), EdgeDirection.OUT);
    3. // user-defined function to select the neighbors which have edges with weight > 0.5
    4. static final class SelectLargeWeightNeighbors implements NeighborsFunctionWithVertexValue<Long, Long, Double,
    5. Tuple2<Vertex<Long, Long>, Vertex<Long, Long>>> {
    6. @Override
    7. public void iterateNeighbors(Vertex<Long, Long> vertex,
    8. Iterable<Tuple2<Edge<Long, Double>, Vertex<Long, Long>>> neighbors,
    9. Collector<Tuple2<Vertex<Long, Long>, Vertex<Long, Long>>> out) {
    10. for (Tuple2<Edge<Long, Double>, Vertex<Long, Long>> neighbor : neighbors) {
    11. if (neighbor.f0.f2 > 0.5) {
    12. out.collect(new Tuple2<Vertex<Long, Long>, Vertex<Long, Long>>(vertex, neighbor.f1));
    13. }
    14. }
    15. }
    16. }
    1. val graph: Graph[Long, Long, Double] = ...
    2. val vertexPairs = graph.groupReduceOnNeighbors(new SelectLargeWeightNeighbors, EdgeDirection.OUT)
    3. // user-defined function to select the neighbors which have edges with weight > 0.5
    4. final class SelectLargeWeightNeighbors extends NeighborsFunctionWithVertexValue[Long, Long, Double,
    5. (Vertex[Long, Long], Vertex[Long, Long])] {
    6. override def iterateNeighbors(vertex: Vertex[Long, Long],
    7. neighbors: Iterable[(Edge[Long, Double], Vertex[Long, Long])],
    8. out: Collector[(Vertex[Long, Long], Vertex[Long, Long])]) = {
    9. for (neighbor <- neighbors) {
    10. if (neighbor._1.getValue() > 0.5) {
    11. out.collect(vertex, neighbor._2)
    12. }
    13. }
    14. }
    15. }

    When the aggregation computation does not require access to the vertex value (for which the aggregation is performed), it is advised to use the more efficient EdgesFunction and NeighborsFunction for the user-defined functions. When access to the vertex value is required, one should use EdgesFunctionWithVertexValue and NeighborsFunctionWithVertexValue instead.

    Graph Validation

    Gelly provides a simple utility for performing validation checks on input graphs. Depending on the application context, a graph may or may not be valid according to certain criteria. For example, a user might need to validate whether their graph contains duplicate edges or whether its structure is bipartite. In order to validate a graph, one can define a custom GraphValidator and implement its validate() method. InvalidVertexIdsValidator is Gelly’s pre-defined validator. It checks that the edge set contains valid vertex IDs, i.e. that all edge IDsalso exist in the vertex IDs set.

    1. ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    2. // create a list of vertices with IDs = {1, 2, 3, 4, 5}
    3. List<Vertex<Long, Long>> vertices = ...
    4. // create a list of edges with IDs = {(1, 2) (1, 3), (2, 4), (5, 6)}
    5. List<Edge<Long, Long>> edges = ...
    6. Graph<Long, Long, Long> graph = Graph.fromCollection(vertices, edges, env);
    7. // will return false: 6 is an invalid ID
    8. graph.validate(new InvalidVertexIdsValidator<Long, Long, Long>());
    1. val env = ExecutionEnvironment.getExecutionEnvironment
    2. // create a list of vertices with IDs = {1, 2, 3, 4, 5}
    3. val vertices: List[Vertex[Long, Long]] = ...
    4. // create a list of edges with IDs = {(1, 2) (1, 3), (2, 4), (5, 6)}
    5. val edges: List[Edge[Long, Long]] = ...
    6. val graph = Graph.fromCollection(vertices, edges, env)
    7. // will return false: 6 is an invalid ID
    8. graph.validate(new InvalidVertexIdsValidator[Long, Long, Long])