2

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.

jason
  • 3,932
  • 11
  • 52
  • 123

1 Answers1

1

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.

Community
  • 1
  • 1
Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
  • How can I make this sql query into neo4j query? **'SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin(radians(lat)) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;'** – jason Jul 27 '15 at 06:01
  • There is the haversin function in cypher too for this purpose: http://neo4j.com/docs/stable/query-functions-mathematical.html#functions-haversin – Michael Hunger Jul 27 '15 at 07:48
  • Awesome, TIL! Thanks, Michael! – Brian Underwood Jul 27 '15 at 14:20