Mongoosastic,我如何进行地理距离查询

时间:2016-04-08 08:59:40

标签: elasticsearch mongoose mongoosastic

对于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}
    },
    ...
});

我添加了一个新文档:

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

现在我想按距离过滤。我的查询如下:

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

但我总是得到错误

{
    "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   }

我的问题是:如何按距离正确过滤?

1 个答案:

答案 0 :(得分:1)

谢谢Paradise228,这是映射。

这项工作:

...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}
    },...

使用此映射:

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);
    }
});