【问题标题】:minDistance doesn't work on 2d indexminDistance 不适用于 2d 索引
【发布时间】:2015-04-09 10:34:05
【问题描述】:

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

其中位置字段是一个双 [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 版本中得到了解决

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 是的,我知道,但是如何在 spring data mongodb 中创建 2dsphere 索引?
    • template.indexOps(UserLocation.class).ensureIndex( new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE) ); 应该可以解决问题
    • 是的,成功了!如果您将此信息放在答案中,我会接受,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 2020-08-07
    • 2020-02-03
    • 2017-10-20
    • 1970-01-01
    • 2011-08-21
    相关资源
    最近更新 更多