Sunday, June 14, 2015

Simple Neo4J example...

I've been using a graph database at work named Titan ( It's open source, and has some pretty nice features such as the ability to choose between a number of different databases for storage (Cassandra DB, HBase, Berkeley DB, etc), and use Solr or Elastic Search for external indexing of data. However, I wanted to try out Neo4J for home project. Here are a few of the things that I learned.

1. Neo4J is incredibly easy to add to your project using Maven. Just add a dependency like this:


2. I used Neo4J as an embedded database like this:

GraphDatabaseService graphDb;
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );

3. The Neo4J documentation recommended that you use try with resource:

try (Transaction tx = graphDb.beginTx()) {
  populateDb(graphDb, someDataToAdd);
} catch (Exception e) {

4. Adding nodes and relationships is very straightforward:

// Add nodes using createNode, then 
// use setProperty for each property
someDataToAdd.forEach(d -> {
  Node node = graphDb.createNode();
  node.setProperty("name", d.getName());
  node.setProperty("email", d.getEmail());
  node.setProperty("id", d.getId());
// Add relationships by calling createRelationshipTo 
// on the source node.
// Also, search for nodes by calling findNodes
Node friend = graphDb.findNodes(
DynamicLabel.label("Person"), "id", id).next();
node.createRelationshipTo(friend, RelTypes.FRIEND);

5. Get all relationships and nodes by using the GlobalGraphOperations:
.getAllRelationships().forEach(n -> n.delete());
.getAllNodes().forEach(n -> n.delete());

It's possible to query the graph using cypher - I just found it to be easier and more intuitive to use the Java API.