gpt4 book ai didi

spring - 如何获取距离 - MongoDB Template Near 函数

转载 作者:可可西里 更新时间:2023-11-01 10:03:27 25 4
gpt4 key购买 nike

我正在尝试查找附近的地点。下面的代码工作正常。但是我无法根据给定的纬度、经度获得实际的位置距离。

Criteria criteria = new Criteria("coordinates")
.near(new Point(searchRequest.getLat(),searchRequest.getLng()));

Query query = new Query();
query.addCriteria(criteria);
query.addCriteria(criteriaName);
query.limit(5);
List<Place> ls = (List<Place>) mongoTemplate.find(query, Place.class);

最佳答案

您可以使用 geoNear aggregation 来完成.在 spring-data-mongodb GeoNearOperation代表这个聚合。

扩展或创建继承 Place 类,其中包含您想要距离信息的字段(继承示例):

public class PlaceWithDistance extends Place {
private double distance;

public double getDistance() {
return distance;
}

public void setDistance(final double distance) {
this.distance = distance;
}
}

使用聚合代替 CriteriaQuerygeoNear 的第二个参数是应该设置距离的字段的名称:

final NearQuery nearQuery = NearQuery
.near(new Point(searchRequest.getLat(), searchRequest.getLng()));
nearQuery.num(5);
nearQuery.spherical(true); // if using 2dsphere index, otherwise delete or set false

// "distance" argument is name of field for distance
final Aggregation a = newAggregation(geoNear(nearQuery, "distance"));

final AggregationResults<PlaceWithDistance> results =
mongoTemplate.aggregate(a, Place.class, PlaceWithDistance.class);

// results.forEach(System.out::println);
List<PlaceWithDistance> ls = results.getMappedResults();

只是为了让它更容易 - 关联导入:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.geoNear;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;

import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GeoNearOperation;
import org.springframework.data.mongodb.core.query.NearQuery;

关于spring - 如何获取距离 - MongoDB Template Near 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32795980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com