Neo4j and JGraphT – A Perfect Team


Neo4j is an open-source graph database, implemented in Java. JGraphT is a free Java graph library that provides mathematical graph-theory objects and algorithms. JGraphT is a well fitting data model for Neo4j query results as well as it provides a rich pool of algorithms to process it. This article is about how to get a JGraphT graph object as a result from a Neo4j Cypher query. In order to reach this goal, I started the project jgrapht-neo4j-client.

Neo4j REST API provides a way to query the database with Cypher. Cypher is a declarative graph query language. See the Neo4j manual to learn more about it. The project jgrapht-neo4j-client contains classes to query Neo4j using the REST API and to convert the JSON result to a JGraphT graph object. The code is an GitHub in repository jgrapht-neo4j-client.

Usage example

In this example Neo4j is queried for train stations. In the JGraphT result object you can find the shortest path between two stations by Dijkstra’s shortest path algorithm which is implemented in JGraphT.

// Execute query, get result as graph
CypherToJGraphT graphLoader = new CypherToJGraphT();
DirectedGraph<Node, Edge> graph = graphLoader.execute(
  "MATCH (n:station)-[r:train]-() RETURN n,r");

// Read start and destination from result
Set<Node> allStations = graph.vertexSet();
Node start = getNodeByName(nodeSet, "Schlesisches Tor");
Node destination = getNodeByName(nodeSet, "Friedrichstrasse");

// Find shortest path from start to destination
List<Edge> shortestPath = DijkstraShortestPath.findPathBetween(
  graph, start, destination);

// Log shortest path
LOG.debug("Shortest path: ");
for (Edge edge : shortestPath) {
    String currentStation = edge.getTargetNode()

Maven configuration

To use the jgrapht-neo4j-client in a Maven projects you have to add a new dependency and repository to your pom.xml:

       <name>Murygin's Git based repo</name>

Implementation details

Class CypherToJGraphT is delegating REST calls to query Neo4j to class CypherToJson. You can read more about query Neo4j with Cypher using the REST API in a another blog post.

Converting the JSON result to a JGraphT graph is done in CypherToJGraphT in method convertJsonToGraph(JSONObject json).

Generic data model classes for JGraphT graphs are Node and Edge. In this classes all data from Neo4j nodes and relations are saved.

  1. No trackbacks yet.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

Du kommentierst mit Deinem Abmelden / Ändern )


Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )


Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s

%d Bloggern gefällt das: