2013-06-18 24 views
1

我在春季时遇到了mongoTemplate问题,当我尝试使用SortQuery查询时使用Sort。排序不起作用:春天mongoTemplate。排序不起作用的地理查询(NearQuery)

Query query = new Query(); 
query.with(new Sort(Direction.DESC, "timeStamp")); 
Criteria criteria = new Criteria(); 
criteria.and("type").is("MeasurementPoint"); 
query.addCriteria(criteria); 

NearQuery queryN = NearQuery.near(p).maxDistance(new Distance(distance, Metrics.KILOMETERS)).num(range).query(query); 
GeoResults<MeasurementPoint> geoPoints = mongoTemplate.geoNear(queryN, MeasurementPoint.class); 

我不知道我做错了,但geoResult返回我的第一场比赛,而不是最后一个(排序DESC)。所以,我认为排序工作不正常。

有什么想法?这是一个错误吗?

谢谢!

回答

2

不幸的是,不可能排序geoNear结果,因为它不返回游标,默认排序是与点的距离。你可以做的是用Java代码手动排序结果。请注意,下面的代码忽略了距离并仅通过“timeStamp”排序。

List<GeoResult<Person>> results = geoPoints.getContent(); 
Collections.sort(results, new Comparator<GeoResult<Person>>() { 
    @Override 
    public int compare(GeoResult<Person> o1, GeoResult<Person> o2) { 
     return o1.getContent().getTimeStamp() == 2.getContent().getTimeStamp() ? 0 : 
       (o1.getContent().getTimeStamp() > o2.getContent().getTimeStamp() ? 1 : -1) ; 
     } 
    }); 

另一种方法是使用$ geoWithin和$ centerSphere。既然你限制了一些距离(距离变量)的结果,那可能会奏效。

Query query = Query.query(Criteria.where("coords").withinSphere(new Circle(p, new Distance(distance, Metrics.KILOMETERS).getNormalizedValue()))); 
    query.with(new Sort(Direction.DESC, "timeStamp")); 
    Criteria criteria = new Criteria(); 
    criteria.and("type").is("MeasurementPoint"); 
    query.addCriteria(criteria); 

    List<Person> geoPoints = mongoTemplate.find(query, MeasurementPoint.class); 

你可以找到约$ geoWithin和$ centerSphere这里的更多信息:

http://docs.mongodb.org/manual/reference/operator/geoWithin/

http://docs.mongodb.org/manual/reference/operator/centerSphere/