春天的mongoTemplate.排序不适用于地理查询(NearQuery) [英] Spring mongoTemplate. Sort is not working in geo query (NearQuery)

查看:826
本文介绍了春天的mongoTemplate.排序不适用于地理查询(NearQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem with mongoTemplate in Spring when I am trying to query using NearQuery with a Sort. The Sort does not work:

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).因此,我认为排序工作不正常.

I do not know what I am doing wrong but the geoResult returns me the first match, not the last one (Sorted DESC). So, I assume that the Sort is not working properly.

有什么主意吗?是虫子吗?

Any idea? Is it a bug?

谢谢!

推荐答案

不幸的是,不可能对geoNear结果进行排序,因为它不会返回游标并且默认排序是带点的距离.您可以做的是用Java代码手动对结果进行排序.请注意,下面的代码将忽略该距离,仅按"timeStamp"进行排序.

Unfortunately, isn't possible sort geoNear results since it doesn't returns a cursor and the default sort is the distance with point. What you could do is sort the results manually in Java code. Note that the code bellow ignores the distance and sorts only by "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.由于您将结果限制为一定的距离(距离变量),因此可行.

An alternative approach is use $geoWithin and $centerSphere. Since you're limiting results with some distance (distance variable), that could work.

    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的更多信息:

You could find more information about $geoWithin and $centerSphere here:

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

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

这篇关于春天的mongoTemplate.排序不适用于地理查询(NearQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆