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="")
@GrabResolver(name="restlet", root="")
@GrabConfig(systemClassLoader = true)

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.


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.



Leave a Reply

Your email address will not be published. Required fields are marked *