Using Three.js with Neo4j

Last week we saw Sigma.js, and as promised here is a graph visualization with Three.js and Neo4j. Three.js is a lightweight 3D library, written by Mr. Doob and a small army of contributors.

The things you can do with Three.js are amazing, and my little demo here doesn’t give it justice, but nonetheless I’ll show you how to build it.

We need to pass the nodes and relationships to Three.js, one of the ways we can do that easily is with the Gon gem, since we’re using sinatra, we’ll use the special gon-sinatra gem.

class App < Sinatra::Base
  register Gon::Sinatra
  
  def nodes
    neo = Neography::Rest.new
    cypher_query =  " START node = node:nodes_index(type='User')"
    cypher_query << " RETURN ID(node), node"
    neo.execute_query(cypher_query)["data"].collect{|n| {"id" => n[0]}.merge(n[1]["data"])}
  end  
  
  def edges
    neo = Neography::Rest.new
    cypher_query =  " START source = node:nodes_index(type='User')"
    cypher_query << " MATCH source -[rel]-> target"
    cypher_query << " RETURN ID(rel), ID(source), ID(target)"
    neo.execute_query(cypher_query)["data"].collect{|n| {"id" => n[0], "source" => n[1], "target" => n[2]} }
  end
  
  get '/' do
    neo = Neography::Rest.new
    gon.nodes = nodes  
    gon.edges = edges
    erb :index
  end
end

In our view we will add”include_gon” which ties our nodes and edges to our html page.

<!doctype html>
<html lang="en">
	<head>
		<title>Three.js and Neo4j</title>
		<%= include_gon %>
		<meta charset="utf-8">
		<script type="text/javascript" src="Three.js"></script>
		<link type="text/css" rel="stylesheet" href="neo_three.css"/>
	</head>
	<body>
		<script type="text/javascript" src="neo_three.js"></script>
	</body>
</html>

If you view the source of index.html, you’ll see our nodes and edges.

window.gon = {};
gon.nodes=[{"id":1,
            "rotation_x":5.061454830783556,
            "name":"zfbushqe",
            "position_y":256,
            "position_x":658,
            "position_z":577,
            "rotation_y":3.543018381548489},              
           {"id":2,
            "rotation_x":4.572762640225143,
            "name":"afntayhh",
            "position_y":-22,
            "position_x":510,
            "position_z":404,
            "rotation_y":2.2689280275926285}
            ...
gon.edges=[{"id":3,"source":1,"target":198},
           {"id":2,"source":1,"target":39},
           {"id":1,"source":1,"target":21}
           ...
           ]

To use Three.js, we’ll need to create a camera, a scene and pick a renderer to use.

  camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
  camera.position.z = 100;

  scene = new THREE.Scene();

  scene.add( camera );

  renderer = new THREE.CanvasRenderer();
  renderer.setSize( window.innerWidth, window.innerHeight );
  container.appendChild( renderer.domElement );

To create our nodes, we’ll use Spheres and use a normal material. We’ll grab the nodes from gon and use their properties to position and set the orientation of our spheres.

  var geometry = new THREE.SphereGeometry( 50, 8, 7, false );
  var material = new THREE.MeshNormalMaterial();
    
  group = new THREE.Object3D();
		
  for (n in gon.nodes) {
	
    var mesh = new THREE.Mesh( geometry, material );
    mesh.position.x = gon.nodes[n].position_x;
    mesh.position.y = gon.nodes[n].position_y;
    mesh.position.z = gon.nodes[n].position_z;
    mesh.rotation.x = gon.nodes[n].rotation_x;
    mesh.rotation.y = gon.nodes[n].rotation_y;
    mesh.matrixAutoUpdate = false;
    mesh.updateMatrix();
    group.add( mesh );

  }

  scene.add( group );

For our edges, we’ll create simple lines of random colors between the source and target nodes.

  for (n in gon.edges) {
    var line_segment = new THREE.Geometry();
    line_segment.vertices.push( new THREE.Vertex( group.children[gon.edges[n].source - 1].position ) );
    line_segment.vertices.push( new THREE.Vertex( group.children[gon.edges[n].target - 1].position ) );
    var line = new THREE.Line( line_segment, 
                              new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff, 
                                                             opacity: 0.5 } ) );

    scene.add(line)
  }

We’ll animate our visualization by rendering the scene and controlling the camera with the mouse.

document.addEventListener( 'mousemove',  onDocumentMouseMove,  false );

function onDocumentMouseMove(event) {
  mouseX = event.clientX - windowHalfX;
  mouseY = event.clientY - windowHalfY;
}

function animate() {
  requestAnimationFrame( animate );
  render();
}

function render() {
  camera.position.x += ( mouseX - camera.position.x ) * .05;
  camera.position.y += ( - mouseY + 200 - camera.position.y ) * .05;
  camera.lookAt( scene.position );
  renderer.render( scene, camera );
}

I’m going to skip the graph creation but all the code is available on github as usual, and you’ll definitively want to see this live on Heroku.

If you want to learn more about Three.js, check out these tutorial and these videos.

Tagged , , , , , ,

2 thoughts on “Using Three.js with Neo4j

  1. […] Using Three.js with Neo4j by Max De Marzi. […]

  2. […] “Neo4j is a high-performance, NOSQL graph database with all the features of a mature and robust database”. Here’s how to hook it up to Three.js, using Ruby on the server side. […]

Leave a comment