Skip to content

Instantly share code, notes, and snippets.

@darekmydlarz
Created July 29, 2012 09:13
Show Gist options
  • Save darekmydlarz/3196925 to your computer and use it in GitHub Desktop.
Save darekmydlarz/3196925 to your computer and use it in GitHub Desktop.
Scala + Neo4j sample
import org.neo4j.graphdb.RelationshipType
import org.neo4j.kernel.EmbeddedGraphDatabase
import org.neo4j.graphdb.GraphDatabaseService
import org.neo4j.graphdb.Node
import org.neo4j.graphdb.Relationship
object RelTypes extends Enumeration {
type RelTypes = Value
val KNOWS, MAYOR_OF = Value
implicit def conv(rt: RelTypes) = new RelationshipType() {
def name = rt.toString()
}
}
import RelTypes._
object EmbeddedNeo4jScala {
private val DB_PATH = "target/neo4j-scala-db"
private val USERNAME_KEY = "username"
private val graphDb: GraphDatabaseService = new EmbeddedGraphDatabase(DB_PATH)
private def registerShutdownHook =
Runtime.getRuntime.addShutdownHook(new Thread() {
override def run = shutdown
})
private def shutdown = graphDb.shutdown
private def createUser(username: String) = {
val node = graphDb.createNode
node.setProperty(USERNAME_KEY, username)
node
}
private def doTx(f: GraphDatabaseService => Unit) = {
val tx = graphDb.beginTx
try {
f(graphDb)
tx.success
} finally {
tx.finish
}
}
def main(args: Array[String]): Unit = {
registerShutdownHook
doTx {
db =>
val firstNode: Node = createUser("userOne")
firstNode.setProperty("message", "Hello")
val secondNode: Node = createUser("userTwo")
secondNode.setProperty("message", "World")
val relationship: Relationship = firstNode.createRelationshipTo(secondNode, KNOWS)
relationship.setProperty("message", "neo4j-scala")
println(firstNode.getProperty("message") + " " + relationship.getProperty("message") + " " + secondNode.getProperty("message"))
val it = firstNode.getRelationships().iterator()
while (it.hasNext()) {
val r: Relationship = it.next()
val nodes: Array[Node] = r.getNodes()
println(nodes(0).getProperty("message") + " " + r.getProperty("message") + " " + nodes(1).getProperty("message"))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment