Neo4j Spatial Queries and Cypher


Neo4j is a really cool, really rad graph database that has the clubs pumpin’. Okay, yes, computers has a different definition of “cool” and “rad” (especially RAD), but Neo4j is quite funky nonetheless.

Building on Neo4j’s aforementioned funkiness is a bundled ability to deal with spatial data. In my journeys through systems, peoples and cities to this place, Mainframe, I’ve found a strange lack of details on how to work with your own spatial data rather than just spinning the DB up with a shapefile (which, don’t get me wrong, is a fun application for spatial databases too).

In an attempt to change this slightly, this article focuses on a couple of basic steps – let’s:

  • get a node (or many! thousands!) into a spatial layer
  • and then query for nodes again

It’s nice and easy, so let’s dive in.

Neo4j Spatial

Neo4j’s spatial plugin is pretty easy to install, so I’ll leave you to it.

To query Neo4j’s spatial procedures, execute this in the Neo4j browser:

Assuming your instance of Neo4j has spatial capabilities, this should return a ton of exciting rows with procedures just waiting on your beck and call. Huzzah!

Put something into the database

Neo4j spatial works with nodes that are already in your database. You add the items that you wish to track to a spatial layer, which has the advantage of allowing you to perform some high level filtering as well. So, first off, we need a layer. We’ll call it test-layer, and add it using the following command:

This should return a single node, with a not particularly fascinating set of properties. Next up, we need to add a node to this layer.

The layers work on nodes that have longitude and latitude properties. A node that satisfies this can be added to the layer – for this, let’s assume we have one node with a Location label that has location data. We can add this node (or these nodes) by calling the following.

This matches all of our Location nodes, then calls addNode  to add them to our layer.

Finding something in the database

Most of the work is done, really, once we have data in the database. To turn this into more useful information, we need to run queries on our database. A classic crowd-pleaser is the old “what is within XXX metres of this spot?” query, so let’s try that one.

Assuming the previously mentioned node was at the location specified (welcome to Joburg!), this query will return the single node we just added, given that it is within the 100km we specified.

Easy enough?

Further reading

There’s a great set of test cases that you can check out here – let me know if you find anything exciting.

Tagged with: , , , ,
Posted in Neo4j, Technology

Leave a Reply