minDistance对2d索引不起作用

时间:2015-04-09 10:34:06

标签: spring mongodb spring-data spring-data-mongodb

我正在使用Spring Data 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);
    }

其中location字段是double [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版本中得到解决

1 个答案:

答案 0 :(得分:1)

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

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