minDistance 不适用于二维索引

minDistance doesn't work on 2d index

我正在使用 Spring 数据 Mongodb 并尝试进行一些地理查询。

我的服务代码:

public void addLocation(UserLocation userLocation) {
        if (!mongoTemplate.collectionExists(UserLocation.class)) {
            mongoTemplate.createCollection(UserLocation.class);

        }
        mongoTemplate.indexOps(UserLocation.class).ensureIndex( new GeospatialIndex("location") );
        userLocation.setId(UUID.randomUUID().toString());
        mongoTemplate.insert(userLocation, COLLECTION_LOCATION);
    }

其中位置字段是双 [2] 数组。

当我尝试进行查询时:

public List<UserLocation> getUserNearLocation(Point p, double min, double max){
    NearQuery query = NearQuery.near(p).minDistance(new Distance(min, Metrics.KILOMETERS)).maxDistance(new Distance(max, Metrics.KILOMETERS));
//  NearQuery query = NearQuery.near(p).maxDistance(new Distance(max, Metrics.KILOMETERS));
    GeoResults<UserLocation> results = mongoTemplate.geoNear(query, UserLocation.class);


    List<UserLocation> all = new ArrayList<UserLocation>();
    Iterator<GeoResult<UserLocation>> iter = results.iterator();
    while (iter.hasNext()){
        GeoResult<UserLocation> temp = iter.next();
        all.add(temp.getContent());
    }

    return all;
}

我得到:

WARN : org.springframework.data.mongodb.core.MongoTemplate - Command execution of { "geoNear" : "userLocation" , "maxDistance" : 3.135711885774796E-4 , "minDistance" : 0.0 , "distanceMultiplier" : 6378.137 , "near" : [ 40.348553 , 18.179866] , "spherical" : true} failed: exception: minDistance doesn't work on 2d index

我正在使用 Spring Data Mongo 1.7.0 RELEASE,因为我看到了这个问题 :https://jira.spring.io/browse/DATAMONGO-1110 但它在 1.7.0

版本中得到了解决

$minDistance 运算符仅适用于 2dsphere 索引。 (请参阅:docs.mongodb.org/manual#minDistance)。所以只需更改索引创建以使用 2dsphere 索引。

template.indexOps(UserLocation.class)
  .ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE));