Geodata with Neo4j

A primer on saving and operating on geolocation co-ordinates (latitude and longitude) in Neo4j

Neo4j stores geographical data using the built-in Point datatype, which enables native geolocation operations by modelling the Earth as an ellipsoid, so distance calculations use accurate geodetic math instead of 2D math.

Create Nodes with Point Geometry

Use Neo4j's point() function to store geolocation data (longitude, latitude) from the Fastah API as a Point property:

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

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

Calculating Distance

Use the point.distance() function to calculate the distance between two points. The result is rounded 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 from_ip,
  b.ip AS to_ip,
  round(
    point.distance(a.location, b.location) / 1000,
    2
  ) AS distance_in_km;