Calling Neo4j from Javascript

An optional introduction…

Originally, all I thought of posting was the code example below, together with a couple of lines of explanation. But then I thought of people who have never heard of Neo4j, but if they knew it could find it useful and interesting. Hence this little introduction.
Graph databases belong to the new breed of NoSQL (“Not only SQL”) databases.
Neo4j is one such graph database. It incorporates the basic functionality of a relational database with records made up of fields, but in addition it allows the definition of relationships between these records. Say you have two kind of records in your database, persons and technical skills. Between these records you can define relationships like “has_skill” (between persons and skills), “reports_to” (between persons), etc. These relationships can even have fields of their own, say, “skillLevel” for the “has_skill” relationship.
And all this information you can retrieve through powerful queries, such as “show me all the skills of the people reporting to Joe” or even “show me all the skills with a skill level of ‘expert’ of all the people reporting to any of Joe’s managers” (who in turn are, of course, reporting to Joe).

Now suppose you have a homepage, an app or anything which runs in your browser. Assume you want this page to access your Neo4j database to retrieve, update or store information. You could (and for security reasons actually should) implement this access on your internet server. So you would send your request to the server which has some code that accesses your database (on the same or another server) and serves the result to your browser.
If you search the internet on how to do this you will find a good number of places for solutions using node.js or a variety of drivers like here at Neo4j or at StackOverflow.
What I want to show here is a bit different: just the minimal code required to directly access a Neo4j server from within your html.

 

A minimal working example

I’ll deliberately pick a trivial example to show just the mechanism of accessing the database. Assume we have a couple of programming skills in our database which we could have inserted using the Cypher (Neo4j’s query language) statement:
CREATE (s1:Skill {name: “Java”}), (s2:Skill {name: “XML”}), (s3:Skill {name: “HTML”})
Now from inside our homepage we want to query the database to retrieve all the skills it currently knows of and display them as a list in the browser window. Here is all the code we need:

<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$.ajax({
		url: "http://localhost:7474/db/data/cypher",
		accepts: "application/json; charset=UTF-8",
		dataType:"json",
		data: {
			"query" : "Match (n:Skill) return n.name",
			"params" : {}
		},
		type:"POST",
		success:function(result,xhr,status)
		{
			console.log(result);
			var list = "";
			result.data.forEach(function(item){
				list+="<li>"+item[0]+"</li>";
			}
			);
			document.getElementById("message").innerHTML = list;
		},
		error:function(xhr,err,msg){
			console.log(xhr);
			console.log(err);
			console.log(msg);
		}
});
</script>
<div id="message">***</div>

 
A couple of comments concerning the code:

line 1: load the jQuery library whose ajax method we want to use for sending a http POST request.
line 2: start our own javascript
line 3: call jQuery’s ajax method to initiate our http request
line 4: the url for the request assuming we are running the Neo4j server locally on its default port 7474. The path is that of the cypher endpoint.
(There is also a Transactional Cypher HTTP endpoint which allows you to execute a series of Cypher statements and then either commit them
or roll back.)
line 8: the actual Cypher query
line 9: no parameters used in this query
line 11: this is a http POST request
line 12: an anonymous callback function called if the request succeeds, which will
line 16: iterate over all requested skill names
line 17: and concatenate them wrapped in <li> tags
line 20: show them in the html element “message”
line 22: in case of error log the error to the console
line 29: this is the only html code on our page, which will show the results

And this is what you should see in your browser window:

  • Java
  • XML
  • HTML
  •  

    An optional epilogue

    If you don’t have Neo4j installed but would like to play around with it you can install the free Community Edition from here. After installing it start it up and point your browser to http://localhost:7474
    If you like enter the Cypher query from our example in the editor (the command line shown at the top of the page) to create the 3 skills:

    CREATE (s1:Skill {name: “Java”}), (s2:Skill {name: “XML”}), (s3:Skill {name: “HTML”})

    Then create a new record (called “node” in Neo4j), this time of type (“label”) “Person”:

    CREATE (john:Person {name: “John Doe”})

    Now define a relationship “Knows” from this Person node to all the Skill nodes:

    MATCH (p:Person {name: “John Doe”}), (s:Skill) CREATE (p)-[:Knows]->(s)

    Watch the diagram shown in the browser window.
    Finally, since John doesn’t know Java delete the link from John to Java:

    MATCH x-[r:Knows]->y WHERE y.name=”Java” DELETE r

    and if you substitute the Cypher query in our example by:

    Match (person)-[:Knows]->(s) Return s.name

    and reload the page you should only get the skills known by some person in the database, i.e. Java is no longer listed.

    Advertisements

    3 thoughts on “Calling Neo4j from Javascript

    1. I was having problem importing node.js modules to make a simple POST request. This is a simple solution for my problem! Thank you!

      Like

    2. In neo4j 3.0.0:
      (1) Double quotations above need to be single quotations e.g:
      CREATE (s1:Skill {name: ‘Java’}), (s2:Skill {name: ‘XML’}), (s3:Skill {name: ‘HTML’})
      (2) Brackets required in the MATCH statement:
      MATCH (x)-[r:Knows]->(y) WHERE y.name=’Java’ delete r

      Liked by 1 person

    Leave a Comment

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s