【问题标题】:Spring mongoTemplate. Sort is not working in geo query (NearQuery)春天 mongo 模板。排序在地理查询中不起作用(NearQuery)
【发布时间】:2013-06-18 12:59:35
【问题描述】:

当我尝试使用带有排序的 NearQuery 进行查询时,我在 Spring 中遇到了 mongoTemplate 的问题。排序不起作用:

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 会返回第一个匹配项,而不是最后一个匹配项(Sorted DESC)。所以,我假设排序工作不正常。

有什么想法吗?是bug吗?

谢谢!

【问题讨论】:

    标签: mongodb sorting geo spring-data-mongodb


    【解决方案1】:

    不幸的是,无法对 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/

    【讨论】:

      猜你喜欢
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2018-12-25
      • 1970-01-01
      相关资源
      最近更新 更多