Finding Distance in km between two nodes

37 views
Skip to first unread message

ahmad Reza

unread,
Mar 17, 2018, 8:21:30 PM3/17/18
to Neo4j
Hi Guys

I have a database and want to find the distance between tow node. I have the Lattitude(y) and Longitude (x) for each one and the query language is cypher. I have added the spatial neo4j plugin but I don't know the query. 
Thank you so much.

Craig Taverner

unread,
Mar 18, 2018, 8:04:44 AM3/18/18
to ne...@googlegroups.com
You do not need the spatial plugin to calculate the distance because Cypher has a built-in function for this. For example, assuming you have two places labelled Place with unique identifier 'key' and the coordinates are 'x' and 'y':

    MATCH (a:Place {key:1}), (b: Place {key:2})
    RETURN distance(point({latitude: a.y, longitude: a.x}), point({latitude: b.y, longitude: b.x})) / 1000.0 as km

If the node's properties are 'latitude' and 'longitude' instead of 'y' and 'x', you can simplify this to:

    MATCH (a:Place {key:1}), (b: Place {key:2})
    RETURN distance(point(a), point(b)) / 1000.0 as km

This simplification is relying on the fact that nodes look like Maps (dictionaries). Not that if you use this syntax with 'x' and 'y', the point function will think you are not talking about geographic points, but cartesian points and give you a different answer, so take care. The geographic distance function assumes locations are in degrees and will return the answer in meters. The cartesian distance function will not perform any assumption of units and do a simply pythagoras calculation returning the distance in whatever units x and y have.

If you really want to use the spatial plugin, the syntax is a bit more complex because that is a data modelling library and you need to first define a mapping from node properties to points (called a layer), and then add the nodes to the layer (where they get indexed), and finally perform the function on them. Much more work, and only worth doing it if you have much more complex spatial/GIS plans in mind.


--
You received this message because you are subscribed to the Google Groups "Neo4j" group.
To unsubscribe from this group and stop receiving emails from it, send an email to neo4j+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages