Spring Data MongoDB: 使用地理空间查询查找附近数据

使用 MongoDB 的地理空间查询功能可以轻松地查询附近的数据。以下是使用 Spring Data MongoDB 进行地理空间查询的步骤:

1. 在实体类中添加经纬度字段

在实体类中添加经纬度字段,并使用 @GeoSpatialIndexed 注解进行索引。

@Document
public class Location {
    @Id
    private String id;
    private String name;
    @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
    private Point location;

    // getter and setter
}

2. 使用 MongoTemplate 进行地理空间查询

使用 MongoTemplate 进行地理空间查询。

@Autowired
private MongoTemplate mongoTemplate;

public List<Location> findNearbyLocations(double longitude, double latitude, double maxDistance) {
    Point location = new Point(longitude, latitude);
    Distance distance = new Distance(maxDistance, Metrics.KILOMETERS);
    Circle circle = new Circle(location, distance);
    Query query = Query.query(Criteria.where('location').withinSphere(circle));
    List<Location> locations = mongoTemplate.find(query, Location.class);
    return locations;
}

其中,Point 表示一个经纬度点,Distance 表示最大距离,Circle 表示以某个点为中心的圆形区域,Criteria.where('location').withinSphere(circle) 表示在 location 字段上执行球面距离查询。

3. 调用 findNearbyLocations 方法进行查询

List<Location> nearbyLocations = findNearbyLocations(121.4768, 31.2362, 10.0);

该方法将返回距离经纬度为 (121.4768, 31.2362) 的点不超过 10 公里的 Location 列表。

Spring Data MongoDB: 使用地理空间查询查找附近数据

原文地址: https://www.cveoy.top/t/topic/l4Mr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录