jason
jason

Reputation: 3962

find nearest users around me using neo4j cypher query

I am using the queries below to create users with lat,lng .

MERGE (n { user:'a', id:1,lat:40.736184,lng:-73.992006 })   
MERGE (n { user:'b', id:2,lat:40.748475,lng:-73.993808 })
MERGE (n { user:'c', id:3,lat:40.744638,lng:-73.982135 }) 
MERGE (n { user:'d', id:4,lat:40.708929,lng:-74.005567 }) 
MERGE (n { user:'e', id:5,lat:40.729615,lng:-73.975698 })  

How to get all users around 40.724152, -74.001276 within 1 km radius? I really appreciate any help.

Upvotes: 2

Views: 670

Answers (1)

Brian Underwood
Brian Underwood

Reputation: 10856

Here's the link to the neo4j spatial plugin:

https://github.com/neo4j-contrib/spatial

I've not used it before, but most of the instructions are for using it in embedded mode. But if you're using it in server mode here's a link to the pre-compiled plugins:

https://github.com/neo4j-contrib/spatial#using-the-neo4j-spatial-server-plugin

You can do something in Cypher like:

ABS(user1.lat - user2.lat) < LAT_NUMBER AND ABS(user1.long - user2.long) < LONG_NUMBER

Of course that considers a square. Also LAT_NUMBER AND LONG_NUMBER would have to be an approximation because a kilometer doesn't have the same ratio to latitude/longitude everywhere on the each (see this SO question/answer.

You could also maybe use good `ol Pythagoras' theorem, though I don't see a way to square numbers in Cypher. Again, you would then just be coming up with a hypotenuse which is a mix of latitude and longitude.

(EDIT: See Michael's comment, particularly the link to the docs which has an example of Cypher you could use)

The spatial plugin should provide the most accurate and predictable results.

Upvotes: 1

Related Questions