Neo4j is popular Graph Database system that allows you to manipulate data as nodes related with each other. Following a graph approach on data allows you to implement applications with special characteristics such as apps where users are following other users or pages. Actually, it’s almost impossible to simulate a graph data structure with conventional relational databases (SQL) or even with key-value storage systems. Graph databases is a single way to go, at least if you want to be able to scale for users more than your social circle.
Amongst the existing graph databases solutions, neo4j is gaining popularity. This can be because of it’s robust implementation, the complete documentation that the neo4j wiki page [http://wiki.neo4j.org]offers and the hooks for languages such as ruby, java, python.
In our case, the goal is to implement a simple user-following-user Ruby on Rails application that stores the following information in the graph database, neo4j.
First we need to install and use jruby. Relying to rvm we run start with
rvm install jruby
Then we need to generate a gemset for jruby and create a rails app, using this gemset.
rvm use jruby-1.6.3 rvm gemset create neotest rvm use jruby-1.6.3@neotest |
To hook the neo4j database with ruby, we should install and use (require) the neo4j gemset. So we run
gem install neo4j |
Now Let’s run a simple test. Create a file and paste the following code.
require "rubygems" require "neo4j" #domain model class Waypoint include Neo4j::NodeMixin #the persistent properties of this class property :name, :lon, :lat #friend relationships to other persons has_n :roads index :name end #populate the db Neo4j::Transaction.run do #the waypoints NYC = Waypoint.new :name=>'New York', :lon=>-74.007124, :lat=>40.714550 SF = Waypoint.new :name=>'San Francisco', :lon=>-122.420139, :lat=>37.779600 SEA = Waypoint.new :name=>'Seattle', :lon=>-122.329439, :lat=>47.603560 #the roads NYC.roads << SF NYC.roads << SEA SEA.roads << SF end Neo4j::Transaction.run do #do a fulltext search over all Waypoints Waypoint.find(:name => 'New York').each { |x| puts "Found Waypoint: #{x.name}" } end |
Now save the file as neotest.rb
Go to terminal and run the file
$ jruby neotest.rb. |
So now we have all the basic setup to start playing with neo4j graph database and ruby. As I just started messing with neo4j and graph database structure, I promise that there will be many following posts about these topics.