Neo4j is a great database for building social services and Scala is a programming language that’s become popular for doing high performance concurrency servers.

In this post I’ll show you how to use Scala to map classes to nodes & relationships on the Neo4j database.

In a new or existing project add the dependency for the library on the build.sbt file:

libraryDependencies ++= Seq("com.kreattiewe" %% "neo4s" % "2.2.1")

Add two classes that will represent the User on our social network and their relationships:

case class User(name: String, email: String)



case class Friendship(from: User, to: User, active: Boolean) extends Rel[User, User]

Now create a Mapper that will convert a case class to a Map:

import com.kreattiewe.mapper.macros.Mappable implicit val userMapper = Mapper.build[User]

implicit val friendshipMapper = Mapper.build[Friendship]

Create a NeoNode that is the class that will persist the nodes on the database:

implicit val neoUser = NeoNode("user", "email", (user: User) => user.email)

The NeoNode.apply method takes the label for the node, the unique column and a function that receives an Instance of my user and returns a string that represents the unique key in the database for the node.

For creating the NeoRel we need the implicits for the User and Friendship Mappers and the NeoNode for User.

implicit val neoRel = NeoRel[Friendship, User, User]("friendship", true)

That’s it, now you can save nodes on the database but first the connection must be set:

implicit val connection = Neo4jREST("localhost", 7474, "/db/data/", "user", "password")

Creating the nodes:

val user = User("Michel Perez", "michel.ingesoft@gmail.com")

val friend = User("Juan David", "juda@hotmail.com")

Every CRUD operation on the database will return a future response, so I’ll use a for comprehension to handle these operations:

val fut = for {

_ <- user.save()

_ <- friend.save()

saved <- Friendship(user, friend, true).save()

} yield saved



val saved = Await.result(fut, 1 second)

This way I can create two nodes on the database and create a relationship, you can query on the web console for Neo4J and you’ll get this graph:

You can learn more about this library here and find the full example here, feel free to contribute and report bugs.