Neo4j and JGraphT – A Perfect Team

Berlin_U-Bahn_S-Bahn

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();
graphLoader.setHost(neo4jHost);
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()
      .getProperty("name");
    LOG.debug(currentStation);
}

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:

<dependencies>
   ...
   <dependency>
      <groupId>org.murygin</groupId>
      <artifactId>jgrapht-neo4j-client</artifactId>
      <version>0.1</version>
   </dependency>
   ...
</dependencies>
...
<repositories>
   ...
   <repository>
      <id>git-murygin</id>
       <name>Murygin's Git based repo</name>
       <url>https://github.com/murygin/maven-repository/raw/master/</url>
   </repository>
   ...
</repositories>

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.

Hinterlasse einen Kommentar