Groovy web console

subscribe to the feed Subscribe
to this
site
Neo4j Getting Started example in Groovy (via #groovywebconsole)
tweet this snippet Tweet
this
script

Neo4j Getting Started example in Groovy

Published 3 years ago by paulk_asert
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
// don't run in Groovy Web Console - run locally (e.g. paste in GroovyConsole)

@GrabResolver(name='neo4j-public-repo', root='http://m2.neo4j.org')
@Grab('org.neo4j:neo4j-kernel:1.1.1')
import org.neo4j.kernel.EmbeddedGraphDatabase
import org.neo4j.graphdb.*

// an enum helper
enum MyRelationshipTypes implements RelationshipType { knows }

// some optional metaclass syntactic sugar
Node.metaClass {
  propertyMissing { String name, val -> delegate.setProperty(name, val) }
  propertyMissing { String name -> delegate.getProperty(name) }
  methodMissing { String name, args -> delegate.createRelationshipTo(args[0], MyRelationshipTypes."$name") }
}
Relationship.metaClass {
  propertyMissing { String name, val -> delegate.setProperty(name, val) }
  propertyMissing { String name -> delegate.getProperty(name) }
}

// real example starts here
def graphDb = new EmbeddedGraphDatabase("graphdb")
def tx = graphDb.beginTx()
def firstNode, secondNode, relationship
try {
   firstNode = graphDb.createNode()
   secondNode = graphDb.createNode()
   relationship = firstNode.knows(secondNode)
   firstNode.message = "Hello,"
   secondNode.message = "world!"
   relationship.message = "brave Neo4j"
   tx.success()
} finally {
   tx.finish()
   println "$firstNode.message $relationship.message $secondNode.message"
   // => Hello, brave Neo4j world!
   graphDb.shutdown()
}