anmol-idf
anmol-idf

Reputation: 61

How to do 'getNearest' geospatial query in RethinkDB?

I was going through RethinkDB docs and found out about geospatial queries. So I thought, why not give it a try to build an UBER kind of database to get Drivers near a User.

So here is how I approached:

Creating the Customer and Driver

r.table('customer').insert({
 name: "John",
 currentLocation:  [77.627108, 12.927923]
})

r.table('driver').insert({
 name: "Carl",
 currentLocation: [77.612319, 12.934784]
})

Creating a geospatial index on Driver table as Customer will be searching for Drivers nearest to them.

 r.table('driver').indexCreate('currentLocation', {geo: true})

According to their docs, we can find the nearest point using getNearest api

r.table('driver').getNearest(r.point(77.627108, 12.927923),
 {index: 'currentLocation', maxDist: 2000, unit: 'm'}
)

(r.point(77.627108, 12.927923) is on Customer. Right now I am not concerned with querying the Customer table and turning that into ReQL geometry object)

Theoretically, the above query should work but it isn't. It returns an empty array. Am I missing something?

Upvotes: 3

Views: 341

Answers (1)

anmol-idf
anmol-idf

Reputation: 61

ANSWER

Just found this - I missed this important line in docs "A geospatial index field should contain only geometry objects. It will work with geometry ReQL terms (getIntersecting and getNearest) as well as index-specific terms (indexStatus, indexWait, indexDrop and indexList)."

All the queries are fine except I have to make a small modification in Driver query:

r.table('driver').insert({
 name: "Carl",
 currentLocation: r.point(77.612319, 12.934784)
})

currentLocation attribute needs to have geometry object and not an array. After making this change, everything worked fine.

Upvotes: 2

Related Questions