栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot项目使用MongoDB距离查询

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot项目使用MongoDB距离查询

  • 数据库

  • 实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.mapping.Document;


@Data
@AllArgsConstructor
@NoArgsConstructor
@Document("places")
@CompoundIndex(name = "location_index",def = "{'location'}:{'2dsphere'}")
public class Places {
    private ObjectId id;
    private String title;
    private String address;
    private GeoJsonPoint location;
}

  • 测试
import com.czxy.domain.Places;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.geo.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = MongoDemoApplication.class)
public class Test {
    @Autowired
    private MongoTemplate mongoTemplate;
    
    @org.junit.Test
    public void  test01(){
        //构造坐标点
        GeoJsonPoint point = new GeoJsonPoint(116.40, 39.91); //天安门坐标
        //构造半径
        Distance distanceObj = new Distance(1, Metrics.KILOMETERS);
        // 画了一个圆圈
        Circle circle = new Circle(point, distanceObj);
        // 构造query对象
        Query query = Query.query(Criteria.where("location").withinSphere(circle));
        // 省略其他内容
        List list = mongoTemplate.find(query, Places.class);
        list.forEach(System.out::println);
    }
    
    @org.junit.Test
    public void testGeoNear() {
        //构建中心点
        GeoJsonPoint point = new GeoJsonPoint(116.404, 39.915);
        //创建NearQuery对象
        NearQuery nearQuery = NearQuery.near(point,Metrics.KILOMETERS).maxDistance(1,Metrics.KILOMETERS); //maxDistance 最大距离
        //发送查询
        GeoResults results = mongoTemplate.geoNear(nearQuery, Places.class);
        for (GeoResult result : results) {
            System.out.println(result.getContent());
            System.out.println("距离"+result.getDistance().getValue()+"km");
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/850793.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号