NoSQL Zone is brought to you in partnership with:

Max De Marzi, is a seasoned web developer. He started building websites in 1996 and has worked with Ruby on Rails since 2006. The web forced Max to wear many hats and master a wide range of technologies. He can be a system admin, database developer, graphic designer, back-end engineer and data scientist in the course of one afternoon. Max is a graph database enthusiast. He built the Neography Ruby Gem, a rest api wrapper to the Neo4j Graph Database. He is addicted to learning new things, loves a challenge and finding pragmatic solutions. Max is very easy to work with, focuses under pressure and has the patience of a rock. Max is a DZone MVB and is not an employee of DZone and has posted 57 posts at DZone. You can read more from them at their website. View Full User Profile

Crunchbase on Neo4j

11.15.2012
| 4905 views |
  • submit to reddit

NeoTechnology was featured on TechCrunch after raising a Series B round, and it has an entry on CrunchBase. If you look at CrunchBase closely you’ll notice it’s a graph. Who invested in what, who co-invested, what are the common investment themes between investors, how are companies connected by board members, etc. These are questions we can ask of the graph and are well suited for graph databases.

So let’s get to it. This project and dataset are available on Github, but if you want to play it on your own you’ll have to register on http://developer.crunchbase.com and get an API key. Once you have one you can take a look at the JSON returned by heading over to the IO Docs. Here is part of the “neo-technology” company record.

{
"name": "Neo Technology",
"permalink": "neo-technology",
"crunchbase_url": "http://www.crunchbase.com/company/neo-technology",
"homepage_url": "http://www.neotechnology.com",
"blog_url": "",
"blog_feed_url": "",
"twitter_username": "",
"category_code": "software",
"number_of_employees": null,
"founded_year": 2007,
"founded_month": null,
"founded_day": null,
"deadpooled_year": null,
"deadpooled_month": null,
"deadpooled_day": null,
"deadpooled_url": null,
"tag_list": "graphs, open-soure-graphs, graph-systems, commercial-graphs, graph-database",
"alias_list": "",
"email_address": "",
"phone_number": "",
"description": "Graph Database",
 ...

I’m not going to map all of CrunchBase, but I’ll grab a few things of interest. I’ll import companies, people, financial organizations, and tags as Nodes and employee, investor, tagged, and competitor connections as Relationships into Neo4j.

I am using the wonderful CrunchBase gem by Tyler Cunnion. I start by getting all the entities I am interested in (for example here is People):

all_people = Crunchbase::Person.all
 all_people.each do |ap|
   begin
     next unless ap.permalink
     file = "crunchbase/people/#{ap.permalink}"
     if File.exist?(file)
       person = Marshal::load(File.open(file, 'r'))
     else
       person = ap.entity
       File.open(file, 'wb') { |fp| fp.write(Marshal::dump(person)) }      
     end

     people << {:name => "#{person.first_name || ""} #{person.last_name || ""}",
                :permalink      => person.permalink,
                :crunchbase_url => person.crunchbase_url || "",
                :homepage_url   => person.homepage_url || "",
                :overview       => person.overview || ""
                }

   rescue Exception => e   
     puts e.message
   end    

 end

I am saving the JSON returned from the CrunchBase API to a file in case something goes wrong and I need to restart my import. Neo4j doesn’t like null values for properties, so just in case I use an empty string if no value is found.

I will be using a fulltext lucene index to allow people to find their favorite company, person, tag, or financial organization by permalink, so I create that first.

neo = Neography::Rest.new
neo.create_node_index("node_index", "fulltext", "lucene") 

Then I will be creating the nodes for these entities (while saving the node id returned in a hash):

people_nodes = {}
people.each_slice(100) do |slice|
  commands = []
  slice.each_with_index do |person, index|
    commands << [:create_unique_node, 
                 "node_index", 
                 "permalink", 
                 person[:permalink], 
                 person]
  end

  batch_results = neo.batch *commands

  batch_results.each do |result|
    people_nodes[result["body"]["data"]["permalink"]] = result["body"]["self"].split('/').last
  end
end

I am using the Neo4j Rest Batch method sending 100 commands at a time.

I then create the relationships to each other. For example employees of companies:

employees.each_slice(100) do |slice|
  commands = []
  slice.each do |employee|
    commands << [:create_relationship, 
                 employee[:type], 
                 people_nodes[employee[:from]], 
                 company_nodes[employee[:to]], 
                 employee[:properties]] 
  end
  batch_results = neo.batch *commands  
end

For the front end, I need two basic methods. One will return all the nodes and relationships types connected to one node:

cypher = "START me=node(#{params[:id]}) 
          MATCH me -[r?]- related
          RETURN me, r, related"

connections = neo.execute_query(cypher)["data"]

A second query will handle full text search and format the output to a JSON hash that JQuery Autocomplete can work with:

get '/search' do 
  content_type :json
  neo = Neography::Rest.new    

  cypher = "START me=node:node_index({query}) 
            RETURN ID(me), me.name
            ORDER BY me.name
            LIMIT 15"
  query = "permalink:*#{params[:term]}* OR name:*#{params[:term]}*"
  neo.execute_query(cypher, 
                    {:query => query })["data"].
                      map{|x| 
                           { label: x[1], 
                             value: x[0] }
                         }.to_json   
end

Notice how I am passing in the whole lucene query as a parameter? This is the right way to do it. I indexed people, companies, and financial organizations by permalink, but indexed tags by name. I use an “OR” clause to grab them both.

You can skip the graph building step if you just want to use the data as it existed the day of this blog post since it is available on the github repository.

You can clone the repository, create a heroku app, and get this up and running in no time.

git clone https://github.com/maxdemarzi/neo_crunch.git
cd neo_crunch
heroku apps:create
heroku addons:add neo4j:try
git push heroku master

Then go to your Heroku apps https://dashboard.heroku.com/apps/

Find your app, and go to your Neo4j add-on.

In the Back-up and Restore section click “choose file”, find the crunchbase.zip file and click submit. It will take a little while to upload the data, but once you will be able to navigate to your application and see this:

Click the image above to see a live version of it.




Published at DZone with permission of Max De Marzi, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)