I was trying out Neo4j due to my curiosity of the graph specialization. Although Neo4j is not designed to run stand-alone like a database server there is a sub-project that adds a REST API to allow non-Java applications to make use of Neo4j. Neo4j is pretty simple, you basically have nodes, relationships, and properties on both. That’s about it.
In this post is a very basic hypothetical scenario (mainly about Neo4j) of a digital posting system where:
- Users can have a relationship with other users
- Users can post messages
- Users can hide other users’s messages
Please be aware that I have not thoroughly tested this.
Just so you have a visual idea of what it looks like inside Neo4j I wrote a simple graph via Graphviz. Green = KNOWS, Blue = POSTED, and Red = HIDES.
Here’s some snippets of code (that should really be cleaned up to more reflect the image but I know you will understand) to create some nodes and relationships using the Neo4J-REST-PHP-API-client library. This is minimal to maintain clarity so feel free to add more users, messages, and relationships.
<?php //client setup require('php-neo-rest.php'); $graphDb = new GraphDatabaseService('http://localhost:9999/'); $uri = 'http://localhost:9999/node/1/traverse/node'; //User_A $f1 = $graphDb->createNode(); $f1->user_id = 1; $f1->save(); //UserB $f2 = $graphDb->createNode(); $f2->user_id = 2; $f2->save(); //Post_B_1 $f2m1 = $graphDb->createNode(); $f2m1->message = 'f2 post'; $f2m1->timestamp = time(); $f2m1->save(); //User_A knows User_B $f1rf2 = $f1->createRelationshipTo($f2, 'KNOWS'); $f1rf2->save(); //User_B posting Post_B_1 $f1rm2 = $f1->createRelationshipTo($f1m2, 'POSTED'); $f1rm2->save(); //User_A hiding User_B's Post_B_1 $f1rf2m1 = $f1->createRelationshipTo($f2m1, 'HIDE'); $f1rf2m1->save();
And finally, the traversal:
This traversal can be paraphrased as “find UserA’s (identified by an ID of 1) friend’s message postings that have not been hidden by UserA”. We’re only interested in messages so skip (by returning false) any nodes without a “message” property. We then get all the relationships on that node, grab an iterator to loop over the relationships, and skip it if that node has been posted or hidden by UserA.