Location queries with Couchbase and Elasticsearch

Reading time ~1 minute

I recently changed my geolocation queries from Couchbase GeoCouch to Elasticsearch since Elasticsearch offers more flexibility with the search parameters. However, the switch was not as easy as I thought so with some help from Clinton I wrote together some information on how to replicate from Couchbase to Elasticsearch and write a first geo query.

There is a good tutorial on how to install the Couchbase-Elasticsearch-Plugin and configure the XDCR (Cross Datacenter Replication), which is required to get started.

The first thing that didn’t really work for me in Elasticsearch was the PUT update of an index with the geolocation properties, so it is required to DELETE the current index and create (POST) a new one with the JSON below:

<pre>{ "mappings" : { "couchbaseDocument" : { "properties" : { "doc" : { "type" : "object", "properties" : { "location" : { "lat_lon" : 1, "type" : "geo_point" } } } } } } }</pre>

Response: <pre>{ "ok": true, "acknowledged": true }</pre>

After that re-create the replication from Couchbase to make sure the index is up to date.

This maps the “location” attribute to a lat_lon index in Elasticsearch. Your Couchbase document should look something like this:

<pre>{ "type": "location", "location": { "lat": 41.387008, "lon": 2.170036 } }</pre>

To query for objects around Pl. Catalunya in Barcelona, use the following query:

<pre>{ "query": { "filtered": { "query": { "match_all": {} }, "filter": { "geo_distance": { "distance": "5km", "doc.location": { "lat": 41.387008, "lon": 2.170036 } } } } } }</pre>

Hope this helps.

Europe on Two Wheels

![Iron 883](/images/2015/07/IMG_7368.jpg)## Barcelona (Spain) - Le Dramont, Cote d'Azur (France)> 648km![Le Dramont](/images/2015/07/IMG_...… Continue reading


Published on September 10, 2014

HTML5 vs. Native [thoughts]

Published on February 26, 2014