Archive for June, 2012

Neo 4J Graph Database

In this post, I will give a brief introduction to Neo 4J database, installation and basic usage with JAVA .

Firstly, Neo4J is a NO-SQL database. It is used to store data in the form of a graph data structure , i.e. a structure having nodes and edges(called relationships) among the various nodes. This form of database finds its use case in many applications such as storing a social network in systems like facebook , twitter ,etc . More information on what Neo 4J can be found here .

Now, coming to the setup of neo 4J graph database. You can download the installation package from the official site here. Save the tar in a local folder and extract the contents. For this post I am going to run a sample code in neo 4j using eclipse(Details about eclipse can be found here).

Open the eclipse IDE and create a new project , say “firstNeo4jApp”. Add a class named graphDb.java in the default package. Now here comes the important step, to add the neo4j libraries to the build path of eclipse.(Improperly configured build path can lead to errors while compiling the code). To add the neo4j libraries , right click on the project name > Build Path . In the window that appears, select libraries tab and click on external JAR. Now, browse to the downloaded neo4j package folder and go to the lib sub folder. Select all the JAR files in that folder and click on OK. Now, refresh the project and the build path will be configured. You will be able to use the neo4j libraries in you code now.

Let us now look at a simple neo4j example.In this example we will see how to create a node ,set relationship between two nodes and how to get the relationship between two nodes.

Creating a Node in neo 4j


public Node createNode() {
	Node n = null;
	Transaction tx = GraphDb.getDb().handle().beginTx();

	try {
		n = this.gdb.createNode();
		n.setProperty("property1", "property1 key");
		tx.success();
	} finally {
		tx.finish();
	}
	return n;
}

Every write operation to the graph in neo4j must be written within a transaction. For this purpose , we will use the interface org.neo4j.graphdb.Transaction. To start a transaction, we will use the beginTx() function of the org.neo4j.graphdb.GraphDatabaseService interface. this interface also provides the function createNode() which creates a node in the graph. We can set numerous properties to the node based on a simple key-value schema. Also, it is important to finish every transaction. The transaction will not release the locks or memory it has acquired until it has been finished.

Set relationship between two nodes

public static void set(Node A, Node B) {
	Transaction tx = GraphDb.getDb().handle().beginTx();
	Relationship relship = null;

	try {
	        RelationshipIndex rolesIdx = GraphDb.getDb().relationshipIndex();
                
                //Creates a relationship between node A and node B  
	        relship = A.createRelationshipTo(B, RelationshipEnum.RELATED);
                
                //Adds special properties to relation; a key-value pair
		relship.setProperty("key 1", "value 1");
                
                //Adds the relationship object to the graph 
		rolesIdx.add(relship, "name", "related");
		rolesIdx.add(relship, "id", relship.getId());
		tx.success();
	} finally {
		tx.finish();
	}
}

public enum RelationshipEnum implements RelationshipType {
		RELATED
}

Again, since a write operation is performed on the graph, we have to enclose it within a transaction. We can also set properties to the edge(or relationship) like in this case, the property is “key 1″ and the value is “value 1″. Finally , the Relationship object is added to the graph. We are intentionally storing it as “name”:”related pair and “id”:id pair,so that we can query based on the name property also.

Get relationship between two nodes

public static List get(Node A, Node B) {
	RelationshipIndex rolesIdx = GraphDb.getDb().relationshipIndex();
        
        // Get the edge(or relationship) between Node A and Node B having the key value pair as "name":"related" 
	IndexHits roles = rolesIdx.get("name", "related", A, B);

	List rships = new ArrayList();

	//Convert the IndexHits to a List 
        try {
             
	    for (Relationship role : roles) {
                rships.add(role);
	    }
	} finally {
		roles.close();
        }

	return rships;

}

As for the querying the graph, since no write operation is performed on the graph, hence , there is no need to enclose it within a transaction.

The above pieces of code gave a overall idea of how to create a node , create a relationship between two nodes and get a particular kind of relationship between two nodes. The entire code for all three can be downloaded here .

Follow

Get every new post delivered to your Inbox.