Queenside
Queenside

Reputation: 55

How to use ElasticSearch geo_distance on ExpressJS

Hits

{
    "_index" : "users",
    "_type" : "user",
    "_id" : "001",
    "_score" : 1,
    "_source" : {
      "utype" : "user",
      "username" : "test",
      "location" : {
          "lat" : 0.1,
          "lon" : 0.0
      },
      "uid" : "001"
    }
}

Node.js - app.js

client.search({
    index: 'users',
    type: 'user',
    body: {
        query: {
            filtered: {
                query: {
                    match_all: {}
                },
                filter: {
                    geo_distance: {
                        distance: '2km',
                        location: {
                            lat: 0.0,
                            lon: 0.1
                        }
                    }
                }
            }
        }
    }
}).then(function (response) {
    var hits = response.hits.hits;
    console.log(hits);
}, function (error, response) {
    // ...
});

Error

"error": "SearchPhaseExecutionException[Failed to execute phase [query_fetch], all shards failed; shardFailures

... I'm not sure if i'm using the geo_distance correctly but i did use the same format used at elasticsearch documentation. I'm using ExpressJS installed elasticsearch npm and used the client.search code above for geo_distance filtering. And also the hits returns not just one object. Can anyone help me how to make this work? Thanks!

Upvotes: 2

Views: 334

Answers (1)

Sapikelio
Sapikelio

Reputation: 2604

You have to remove the first query and replace "location" by "user.location" because ElasticSearch interprete it like a type not like a attribute.

 client.search({
    index: 'users',
    body: {
          filter: {
              geo_distance: {
                   distance: '2km',
                   location: {
                       lat: 0.0,
                       lon: 0.1
                   }
              }
         }
   }               
}).then(function (response) {
    var hits = response.hits.hits;
    console.log(hits);
}, function (error, response) {
    // ...
});

I hope it helps you.

Upvotes: 1

Related Questions