Getting Started Neo4j with Scala : An Introduction

Table of contents
Reading Time: 3 minutes

Earlier we used Relational Database for storing the data but there we store data in predefined table and than we define foreign key for references between tables or rows. We are using this in present time also. Now when we talk about the graph database, we stored data in the nodes. Graph database provides us flexibility to arrange data in easy way. When we transform from Relational Database Management System to Graph Database, Here are some transformation :

  • Table is represented by a label on nodes
  • Row in a entity table is a node
  • Columns on those tables become node properties.
  • Remove technical primary keys, keep business primary keys
  • Add unique constraints for business primary keys, add indexes for frequent lookup attributes
  • Replace foreign keys with relationships to the other table, remove them afterwards
  • Remove data with default values, no need to store those
  • Data in tables that is denormalized and duplicated might have to be pulled out into separate nodes to get a cleaner model.
  • Indexed column names, might indicate an array property
  • Join tables are transformed into relationships, columns on those tables become relationship properties
When we want to transform from Relational Database, this is very important that we know about these terms and graph model.
We used SQL Statement there for interacting with the database and here we used Cypher Statement for the same.
SQL Statement :
SELECT c.customer_id , c.customer_name FROM customer AS c WHERE c.customer_city = 'Delhi';
Cypher Statement :
Match (c: customer)
WHERE c.customer_city = 'Delhi'
RETURN c.customer_id , c.customer_name ;
Same and boring 😉 , we can write Cypher like this :
Match (c: customer{customer_city : 'Delhi'})
RETURN c.customer_id , c.customer_name ;

Now we see how we can use Scala with Neo4j. For using Neo4j we can use neo4j-java-driver for creating Driver and Session.
libraryDependencies += "org.neo4j.driver" % "neo4j-java-driver" % "1.0.4"

Create Driver and Session :

val driver = GraphDatabase.driver("bolt://localhost/7687", AuthTokens.basic("anurag", "@nurag06"))
val session = driver.session
In Neo4j we use Bolt protocol. It is based on the PackStream serialization and supports protocol versioning, authentication and TLS via certificats.
Now we can create case class where we can define its value. Here we have a case class :
case class User(name: String, last_name: String, age: Int, city: String)
Now for CRUD operation :
Create a Node :

val script = s"CREATE (user:Users {name:'${user.name}',last_name:'${user.last_name}',age:${user.age},city:'${user.city}'})"
val result = session.run(script)

Retrieve all Node :

val script = "MATCH (user:Users) RETURN user.name AS name, user.last_name AS last_name, user.age AS age, user.city AS city"
val result = session.run(script)

Update a Node :

val script =s"MATCH (user:Users) where user.name ='$name' SET user.name = '$newName' RETURN user.name AS name, user.last_name AS last_name, user.age AS age, user.city AS city"
val result = session.run(script)

Delete a Node :

val script =s"MATCH (user:Users) where user.name ='$name' Delete user"
val result = session.run(script)

Now we can create relation between the node. We implement a method which take user’s name, list of those user’s name with whom we want to create relation and relation_type(i.e. Friend, Family). We modify list in comma separated ( “\”, \””) string and pass that in script.

val nameOfFriends = "\"" + userList.mkString("\", \"") + "\""
val script = s"MATCH (user:Users {name: '${user_name}'}) FOREACH (name in [${nameOfFriends}] | CREATE (user)-[:$relation_name]->(:Users {name:name}))"
session.run(script)

Here we send a user’s name ‘Anurag’, List of Friend (“Sandy”, “Manish”, “Shivansh”) and relation between them is ‘Friends’.Screenshot from 2016-07-22 12:25:29

Now we create two more node as a friend of ‘Sandy’.

newFOF

Now we want to know the Friends of Friends. Here is the Cypher:

val script = s"MATCH (user:Users)-[:$relation_name]-(friend:Users)-[:$relation_name]-(foaf:Users) WHERE user.name = '$user_name' AND NOT (user)-[:$relation_name]-(foaf) RETURN foaf"
session.run(script)

Result For this Cypher is :

result FOF

For Deleting all relation’s record, we can use this Cypher:

val script = s"MATCH (n)-[relation:$relation_name]->(r) DELETE relation"
session.run(script)

So this is the basic idea that how we can use Neo4j with scala.

I hope it will help you to start with Graph Database(Neo4j). 🙂

You can get the above working example from the github repo, checkout : GitHub

Thanks.

Reference:

  1. Neo4j: SQL to Cypher

KNOLDUS-advt-sticker

Written by 

Anurag is the Sr. Software Consultant @ Knoldus Software LLP. In his 3 years of experience, he has become the developer with proven experience in architecting and developing web applications.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading