Tag Archives: neo4j

running Neo4j graphgists locally with docker.io

Neo4j has a excellent tool for documenting graph models called graphgists. As the name suggests graphgists are typically stored as github gists in asciidoc format. Additionally to the regular asciidoc you can embed executable cypher and a Neo4j console in a graphgist. For most people it’s perfectly fine hosting their graphgists at github or dropbox. If you want to keep your graphgists private just use a secret gist.

However there are companies with an higher demand for security and privacy that don’t want to expose their stuff onto public networks. Graphgists itself is javascript based and works locally. For the console part it by default connects to http://console.neo4j.org to do the graph operations.

One of my colleagues at Neo Technology recently pointed me to docker.io, a nice LXC based tool to create, maintain, run and share lightweight containers. To get familiar with docker I’ve decided to set up a small project to make graphgists and Neo4j console available in a docker container. This approach allows to handle with your graphgists 100% locally – nothing leaves the container.

How the docker container is built up

Docker containers are assembled by a cookbook called a dockerfile. It specifies the container you want to inherit from and then issue couple of commands to apply your customizations. In my case we need to install a servlet container (tomcat7 here). Neo4j console’s source repo is https://github.com/neo4j-contrib/rabbithole. Based on a recent change it now allows to build a war file ready for deployment into servlet containers. Of course we could have installed maven and clone the repo and exec mvn war:war to build neo4j console. I’ve decided to provide and use a prebuilt war file located at bintray, this removes the need for downloaded a massive number of dependencies for the in-container maven installation. Neo4j console’s war file is deployed as console.war and therefore available in the console context of tomcat.

The graphgist repo is cloned into the location of tomcat’s root context and the location of CONSOLE_URL_BASE is adopted to the locally available neo4j console. Finally tomcat is started as a service. Here’s the full Dockerfile:

[getgit userid=”sarmbruster” repoid=”docker_neo4j_graphgist” path=”Dockerfile” language=”bash”]

How to use the docker container

Of course you need to install docker locally. The procedure differs among operating system and is documented here. Next is to pull the preconfigured container and run it:

This procedure might take some time on first invocation – a good candidate for having a nice espresso.

The second command maps a local directory (it’s crucial to use absolute path) into a in-container directory for accessing the gists. Port 8080 is mapped to the in-container port 8080.

When done your local graphgist setup is finished point your browser to http://localhost:8080. To create a gist, open your favourite text editor and save a <myname>.adoc file in the local gist directory used above when starting docker. For some samples of graphgist files, see https://github.com/neo4j-contrib/graphgist/tree/master/gists.Pointing the browser to http://localhost:8080?myname (without .adoc) should render your graphgist.

Using docker ps and docker stop <containerId> can be used to stop the graphgist containter.

closing words

Since I’m absolutely new to docker there might be better and more elegant ways to achieve locally running graphgists. I’m looking forward to read your comments and feedback on this.

 

some experiments with ratpack and neo4j

Back in May this year I’ve attended the Gr8conf in Copenhagen. As always this conference added couple of things to my personal “take-a-look-at-this” list. The most exciting thingy for me was ratpack, a lean toolkit for building web applications on the JVM. Ratpack is powered by Netty and provides an event driven network engine as opposed to classic servlet based containers like Tomcat or Jetty which bind threads to requests. In high load scenarios with a huge number of concurrent requests the thread based model suffers from thread blocking wheres Ratpack is almost non blocking. To get familiar with Ratpack I’ve decided to implement a server component for Neo4j based on Ratpack. The first goal was to have a cypher endpoint, just like the standard Neo4j offers. Secondary goals were some more features:

  • support for multiple output formats: json, html, csv, message pack
  • ability to get a list of currently running queries and a button to abort each one individually. This is IMHO a feature lacking in classic Neo4j server. Esp. people getting started with cypher tend to write queries that run very long and there is currently now way to abort them.

For the future I’d like to add some more features:

  • transactional cypher endpoint
  • tbd (if you have ideas, please send a comment)

The goal is by far not to create a full fledged alternative to the existing Neo4j server. This project should focus on maximum throughput and ease of use for a cypher-only server component. To get started I’ve cloned https://github.com/ratpack/example-ratpack-gradle-groovy-app. You’ll find my code at https://github.com/sarmbruster/neo4j-ratpack.

Handling Requests

In ratpack you either write inline handlers in src/ratpack/ratpack.groovy or, for more complex cases, write a handler class derived from AbstractHandler and register that in ratpack.groovy.

Ratpack features Google Guice as well, so we can register e.g. a GraphDatabaseService as injectable component. See Neo4jModule, we’re exposing and configuring a GraphDatabaseService, a Cypher ExecutionEngine, a guard (see below) and a QueryRegistry. Other components can refer to them using the @Inject constructor annotation.

The core piece of code is CypherHandler, it parses the cypher command and parameters out of the request, runs it and renders the result depending on the requested content type.

Terminate Queries

From tech perspective this was the most interesting part to write. Neo4j can be run with a optional guard. Since this feature is not part of the public API it is not officially documented and might therefore be changed without further notice – be warned. To enable the guard feature a config option execution_guard_enabled needs to be set to true. However you can get access to the guard by calling ((GraphDatabaseAPI)graphDb).dependencyResolver.resolveDependency(Guard.class). In neo4j-ratpack the guard is exposed as a guice component so any ratpack handler can just inject it.

Each query is registered with a QueryRegistry. Part of that process is setting up a VetoGuard that throws an exception based on a boolean flag. In case of an exception the query is aborted.

Load Tests

Next step was running some load tests to a standard Neo4j server and neo4j-ratpack in order to compare the performance of the server components. All tests were run on my ThinkPad x230 (i7-3520M, 2.9GHz, 16 GB RAM, Ubuntu 13.04). For simplicity load generation and the server itself were running on the same machine – which is by far not perfect, but a starting point.

The intention of these load tests is not measuring Neo4j itself – it focusses on the server component only.

Using jmeter I’ve run a cypher query

with different parameters against a graph db consisting of 1.6M nodes, 7M relationships and 7M properties. Kudos to my colleague Alex who helped me setting up the dataset based from the LDBC project he’s involved with.

Exactly the same graph.db was used by both Neo4j server and neo4j-ratpack. No specific JVM tuning parameters were set. I’ve run the load test with a increasing number of concurrent threads and focussed on observing throughput and latency. The following diagrams were created using a python matplot script orginating from http://www.metaltoad.com/blog/plotting-your-load-test-jmeter. Please note, the latency is displayed in green on logarithmic axis, throughput is in blue on linear axis (ranges are different for the diagrams).

neo4jserver_jdk7

.
ratpack_jdk7

 

We’re observing a increasing rate of errors when going beyond 25k threads. Since the loadgenerator is colocated with the system to test this seems to be point where jmeter’s own memory and CPU consumption influences the system under test too much – so we’ll disregard the range above 25k.

The most interesting finding is that with ratpack the latency remains nearly constant in the range of [2.5k – 10k] threads whereas the standard neo4j server shows increasing latency. At 2.5k threads ratpack shows fully saturated CPU that’s why throughput decreases. With more or faster CPU we could improve both, latency and throughput. The explanation for the difference observed can be found in the different threading model. Neo4j server uses internally jetty which does blocking IO in opposite to ratpack using Netty. To verify this, I’ve taken threaddumps with yourkit:

threading telemetry of neo4j server

threading telemetry of neo4j server

threading telemetry of neo4j-ratpack

threading telemetry of neo4j-ratpack

It’s interesting to see that Neo4j server uses 10 worker threads per core (40 in total on my laptop). Most of the time, most of them are in blocked status indicated by the red color. Ratpack on the other side has 8 worker threads being mostly in ‘green’ aka runnable status. So ratpack indeed uses non blocking IO.

Conclusion

For cypher-only use cases with high concurrency requirements using ratpack instead of neo4j server might be an interesting alternative. However be aware, ratpack is bleeding edge, the current version is 0.9-SNAPSHOT.

 

nice addition back in Neo4j 1.9.1: closeable ExecutionResult

When using Cypher from Java code one instantiates a ExecutionEngine and calls execute to get a instance of ExecutionResult. ExecutionResult is an Iterable and therefore provides access to an iterator() method. Up to Neo4j 1.9 it is recommended to fully consume the iterator until hasNext() returns null, otherwise it’s not guaranteed that all resources are freed up again.

Since Neo4j 1.9.1 ExecutionResult implements ResourceIterable as well. This means the iterator has a close() method to free up bound resources without completely consuming the iterator.

I guess a lot of Neo4j users might not have explored that small but very helpful addition yet, so I think it’s worth mentioning.

assigning UUIDs to Neo4j nodes and relationships

TL;DR: This blog post features a small demo project on github: neo4j-uuid and explains how to automatically assign UUIDs to nodes and relationships in Neo4j. A very brief introduction into Neo4j 1.9’s KernelExtensionFactory is included as well.

a little rant on Neo4j node/relationship ids

In a lot of use cases there is demand for storing a reference to a Neo4j node or relationship in a third party system. The first naive idea probably is to use the internal node/relationship id that Neo4j provides. Do not do that! Never!

You ask why? Well, Neo4j’s id is basically a offset in one of the store files Neo4j uses (with some math involved). Assume you delete couple of nodes. This produces holes in the store files that Neo4j might reclaim when creating new nodes later on. And since the id is a file offset there is a chance that the new node will have exactly the same id like the previously deleted node. If you don’t synchronously update all node id references stored elsewhere, you’re in trouble. If neo4j would be completely redeveloped from scratch the getId() method would not be part of the public API.

As long as you use node ids only inside e.g. a request of an application there’s nothing wrong. To repeat myself: Never ever store a node id in a third party system. I have officially warned you.

UUIDs

Enough of ranting, let’s see what we can do to safely store node references in an external system. Basically we need an identifier that has no semantics in contrast to the node id. A common approach to this is using Universally Unique Identifiers (UUID). Java JDK offers a UUID implementation, so we could potentially use UUID.randomUUID(). Unfortunately random UUIDs are slow to generate. A preferred approach is to use the machine’s MAC and a timestamp as base for the UUID – this should provide enough uniqueness. There a nice library out there at http://wiki.fasterxml.com/JugHome providing exactly what we need.

automatic UUID assignments

For convenience it would be great if all fresh created nodes and relationships get automatically assigned a uuid property without doing this explicitly. Fortunately Neo4j supports TransactionEventHandlers, a callback interface pluging into transaction handling. A TransactionEventHandler has a chance to modify or veto any transaction. It’s a sharp tool which can have significant negative performance impact if used the wrong way.

I’ve implemented a UUIDTransactionEventHandler that performs the following tasks:

  • populate a uuid property for each new node or relationship
  • reject a transaction if a manual modification of a uuid is attempted, either assigment or removal

[getgit repoid=neo4j-uuid userid=sarmbruster path=”src/main/java/org/neo4j/extension/uuid/UUIDTransactionEventHandler.java” language=”java” startloc=20 stoploc=72]

setting up using KernelExtensionFactory

There are two remaining tasks for full automation of UUID assignments:

  • we need to setup autoindexing for uuid properties to have a convenient way to look up nodes or relationships by UUID
  • we need to register UUIDTransactionEventHandler with the graph database

Since version 1.9 Neo4j has the notion of KernelExtensionFactory. Using KernelExtensionFactory you can supply a class that receives lifecycle callbacks when e.g. Neo4j is started or stopped. This is the right place for configuring autoindexing and setting up the TransactionEventHandler. Since JVM’s ServiceLoader is used KernelExtenstionFactories need to be registered in a file META-INF/services/org.neo4j.kernel.extension.KernelExtensionFactory by listing all implementations you want to use:

[getgit repoid=neo4j-uuid userid=sarmbruster path=”src/main/resources/META-INF/services/org.neo4j.kernel.extension.KernelExtensionFactory” language=”java”]

KernelExtensionFactories can declare dependencies, therefore declare a inner interface (“Dependencies” in code) below that just has getters. Using proxies Neo4j will implement this class and supply you with the required dependencies. The dependencies are match on requested type, see Neo4j’s source code what classes are supported for being dependencies. KernelExtensionFactories must implement a newKernelExtension method that is supposed to return a instance of LifeCycle.

For our UUID project we return a instance of UUIDLifeCycle:

[getgit repoid=neo4j-uuid userid=sarmbruster path=”src/main/java/org/neo4j/extension/uuid/UUIDLifeCycle.java” language=”java”]

Most of the code is pretty much straight forward, l.44/45 set up autoindexing for uuid property. l48 registers the UUIDTransactionEventHandler with the graph database. Not that obvious is the code in the init() method. Neo4j’s NodeAutoIndexerImpl configures autoindexing itself and switches it on or off depending on the respective config option. However we want to have autoindexing always switched on. Unfortunately NodeAutoIndexerImpl is run after our code and overrides our settings. That’s we l.37-40 tweaks the config settings to force nice behaviour of NodeAutoIndexerImpl.

looking up nodes or relationships for uuid

For completeness the project also contains a trivial unmanaged extension for looking up nodes and relationships using the REST interface, see UUIDRestInterface. By sending a HTTP GET to http://localhost:7474/db/data/node/<myuuid> the node’s internal id returned.

build system and testing

For building the project, Gradle is used;  build.gradle is trivial. Of course couple of tests are included. As a long standing addict I’ve obviously used Spock for testing. See the test code here.

final words

A downside of this implementation is that each and every node and relationships gets indexed. Indexing always trades write performance for read performance. Keep that in mind. It might make sense to get rid of unconditional auto indexing and put some domain knowledge into the TransactionEventHandler to assign only those nodes uuids and index them that are really used for storing in an external system.

how to use Cypher over JDBC from Groovy

Groovy has a very convenient to use API for accessing databases over JDBC. My colleagues at Neo Technology brought up a JDBC driver for Cypher. It’s very easy to bring these two together. The only ugly thing here is that you have to use a class called “Sql” to emit Cypher statements.

@GrabResolver(name="neo4j", root="http://m2.neo4j.org/")
@GrabResolver(name="restlet", root="http://maven.restlet.org/")
@GrabConfig(systemClassLoader = true)
@Grab('org.neo4j:neo4j-jdbc:1.9')

import groovy.sql.*

def sql = Sql.newInstance('jdbc:neo4j://localhost:7474/')

println "simple cypher statement"
sql.eachRow("start n=node(*) return n") {
	println "row $it"
}

println "parameterized cypher statement"
sql.eachRow("start n=node({1}) return n", [0]) {
	println "row $it"
}

Dependency management is done by using the @Grab annotations. However there is some tweaking required. Not all required libraries are found on Maven central, so we need to add to repos, one for neo4j and one for restlet. Since we need to register a JDBC driver, the dependencies must be configured on system classloader level.

Update:

Neo4j Cypher JDBC driver also allows the usage of parameterized Cypher which know JDBC users by the term “prepared statement”. This is shows in l. 16. Since JDBC does not support named parameters you have to use numbers for the parameters, starting with “{1}” and provide a list of parameter values.

With this small example you can access your Neo4j server very easily.

 

 

upgrading an old Neo4j database using Groovy

In a project I’m involved with there is still a very old Neo4j 1.0 database used. Now this database should be used with an up-to-date version of Neo4j (1.7.2 as of this writing).

Following Neo4j docs, upgrades are done incrementally with every x.y in-between version by starting up and shutting the DB. For upgrading, a config parameter allow_store_upgrade=true must be set.

I’ve found manually downloading each intermediate version too boring and hacked a short groovy script helping with upgrading the datastore, see https://gist.github.com/3011606.

The script must be configured with the right database directory and for the desired target version of Neo4j uncomment the matching @Grab annotation. So when going from 1.0 – 1.8 this script must be called 8 times, each time with the next subsequent @Grab activated.

For those who wonder what the @Grab annotation does: it accesses a maven repository, downloads the dependencies behinde the scene and adds them to the class path.

The upgrade itself is trivial, just fire up an EmbeddedGraphDatabase with allow_store_upgrade=true and shut it down afterwards.

update on Grails Neo4j GORM plugin

The milestone release 1.0.0.M2 of the  Neo4j Grails GORM plugin was published a couple of days ago. The plugin provides a GORM compliant implementation backed by a Neo4j datastore. This means you can switch any Grails application to use Neo4j by simply exchanging the GORM plugin used.

Plugin documentation can be found at http://springsource.github.com/grails-data-mapping/neo4j/manual/index.html http://projects.spring.io/grails-data-mapping/neo4j/index.html. There is also a very minimal demo application available at http://neo4j-grails-demo.herokuapp.com/, see https://github.com/sarmbruster/neo4jsample for the source code. The demo app consists of three trivial domain classes with scaffolding controllers – nothing more for now.

Since there is currently the Neo4j Challange in progress, I’ve decided to participate there. As already stated the neo4jsample demo application is very minimal but it its intention is to serve as a starting point for your own Grails application using Neo4j as datastore backend. If you want support this project in the neo4j challenge, please send a tweet.

Grails Neo4j plugin 0.3 released

Today I released an update of the Grails Neo4j plugin (http://www.grails.org/plugin/neo4j). The main changes are:

  • compatibility with Grails 1.3.x. Be aware, Grails 1.3 – 1.3.3 are suffering from http://jira.codehaus.org/browse/GRAILS-6427, so either use Grails 1.2.x, or be brave and use a recent git build of Grails 1.3.4.SNAPSHOT.
  • usage of Neo4j 1.1 (released today just a few hours ago, so get it while it’s hot).

All changes:

  • [GRAILSPLUGINS-2302] – “home” link broken in the org.codehaus.groovy.grails.plugins.neo4j.Neo4jController views
  • [GRAILSPLUGINS-2303] – Problems with annotation Neo4jEntity
  • [GRAILSPLUGINS-2345] – upgrade to Neo4j 1.1
  • [GRAILSPLUGINS-2346] – <domainclass>.get() throws exception if id is not invalid
  • [GRAILSPLUGINS-2347] – <domainClass>.findAllBy<Field>(value) fails
  • [GRAILSPLUGINS-2349] – provide compatibility for Grails 1.3.x

Grails Neo4j plugin 0.2.1 released

Today I released a minor update of the Grails Neo4j plugin. The changes are:

  • performance improvement by no longer calling map constructor in createInstanceForNode
  • fixed transaction handling by replacing interceptor with a “real” servlet filter
  • support for primitve arrays as properties in domain classes
  • bugfix: handling of bidirectional many-to-many relationships
  • bugfix: setProperties does no longer null out properties that have not been set
  • support for encodeAsXXXX methods from CodecsGrailsPlugin. In previous versions encoding did not work, since the ‘node’
    property of the domain classes could not be encoded (it’s a neo4j internal class!). Workaround: add getNode()==null method
    in AST transformation.

Everyone using the 0.2 release is recommended to upgrade.

Grails Neo4j plugin 0.2 released

Today an important update of the Grails Neo4j plugin has been released. Neo4j is a graph database, it’s main concepts are described in brevity in a previous post.  The plugin provides a convenient way to use Neo4j as a persistence layer for Grails domain classes.

The key features / changes of this release are:

  • domain classes managed by Neo4j can now co-existing with traditional domain classes (aka mapped by Hibernate)
  • Upgrade to Neo4j 1.0
  • usage of Grails dependency resolution instead of embedding the jars in /lib directory
  • added a seperate controller to inspect the Neo4j node space
  • major refactoring using AST transformation, just like in the couchdb plugin
  • support for the Neo4j indexer
  • support for non-declared properties
  • support for traversers

Continue reading