Geodata with Neo4j

A primer on saving and operating on geolocation coordinates (latitude and longitude) in Neo4j

Neo4j stores geographical data using the built-in Point datatype. This type models the Earth as an ellipsoid, so distance calculations use accurate geodetic math instead of flat 2D approximations.

Create nodes with point geometry

Use Neo4j's point() function to store geolocation data from the Fastah API as a spatial property. The API returns locationData.lat and locationData.lng:

UNWIND [
  { ip: "8.8.8.8",   lng: 144.94, lat: -37.84 },
  { ip: "14.1.82.2", lng: 151.20, lat: -33.86 }
] AS event

CREATE (:IPAddress {
  ip: event.ip,
  location: point({
    latitude: event.lat,
    longitude: event.lng
  })
});

Calculate distance between IPs

Use point.distance() to find the distance between two points. We round to two decimal places since IP-based geolocations are approximate:

MATCH (a:IPAddress { ip: "8.8.8.8" }),
      (b:IPAddress { ip: "14.1.82.2" })

RETURN
  a.ip AS fromIp,
  b.ip AS toIp,
  round(
    point.distance(a.location, b.location) / 1000,
    2
  ) AS distanceKm;