Sunday, June 14, 2015

Simple Neo4J example...

I've been using a graph database at work named Titan (https://github.com/thinkaurelius/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:

<dependency>
    <groupId>org.neo4j</groupId>
    <artifactId>neo4j</artifactId>
    <version>2.2.2</version>
</dependency>

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);
  tx.success();
} catch (Exception e) {
  e.printStackTrace();
}

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());
  node.addLabel(DynamicLabel.label("Person"));
});
// 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:

GlobalGraphOperations.at(graphDb)
.getAllRelationships().forEach(n -> n.delete());
GlobalGraphOperations.at(graphDb)
.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.