Search code examples
elasticsearchmongoosemongoosastic

Mongoosastic, how can i make an Geo Distance Query


My schema looks something like this for mongoose:

var articleSchema = new Schema({
    Name: {type: String, es_indexed: true},        
    geo_with_lat_lon: {
        geo_point: {
            type: String,
            es_type: 'geo_point',
            es_lat_lon: true
        },
        lat: {type: Number},
        lon: {type: Number}
    },
    ...
});

I add a new doc:

var artikel = new global.DBModel.article({
      Name:"Test",
      geo_with_lat_lon:{lon:-70,lat:40}
});
artikel.save(...);

Now i would like to filter by the distance. My query looks like this:

global.DBModel.article.search({
        "bool": {
            "must": {
                "match_all": {}
            },
            "filter" :{
                "geo_distance": {
                    "distance": "200km",
                    "geo_with_lat_lon": {
                        "lat": 40,
                        "lon": -70
                    }
                }
            }
        }
    }, {...}

But i always get the error

{
    "error": {
      "root_cause": [
        {
          "type": "query_parsing_exception",
          "reason": "failed to find geo_point field [geo_with_lat_lon]",
          "index": "articles",
          "line": 1,
          "col": 127
        }
      ],
      "type": "search_phase_execution_exception",
      "reason": "all shards failed",
      "phase": "query",
      "grouped": true,
      "failed_shards": [
        {
          "shard": 0,
          "index": "articles",
          "node": "YdQHw7nSRc-T0LwItupmmw",
          "reason": {
            "type": "query_parsing_exception",
            "reason": "failed to find geo_point field [geo_with_lat_lon]",
            "index": "articles",
            "line": 1,
            "col": 127
          }
        }
      ]
    },
    "status": 400   }

My question is: How can i filter correctly by the distance ?


Solution

  • Thank you Paradise228, it was the mapping.

    this work:

    ...geo_with_lat_lon: {
            geo_point: {
                es_indexed: true,
                type: String,
                es_type: 'geo_point',
                es_lat_lon: true
            },
            lat: {type: Number},
            lon: {type: Number}
        },...
    

    with this mapping:

    global.DBModel.store.createMapping(function (err, mapping) {
        if (err) {
            console.log('error creating mapping (you can safely ignore this)');
            console.log(err);
        } else {
            console.log('mapping created!');
            console.log(mapping);
        }
    });