我一直在尝试使用地理空间查询将数据提取到pojo中但没有成功。
以下是我的monogdb集合中的示例数据
{
"_id" : ObjectId("597b8c9a21871eeabd5a1cf5"),
"amb_id" : 10,
"amb_number" : "KL25 8945",
"driver_name" : "Amal Shaji",
"driver_licence_id" : "12/4562/2017",
"ownership" : "Amrita Institute of Medical Science",
"ownership_address" : "Peeliyadu Road, Ponekkara, Edappally, Ernakulam",
"location" : {
"type" : "Point",
"coordinates" : [
76.293485,
10.032871
]
}
}
下面的mongo查询在mongoshell
中运行得非常好 db.trial.find(
{ location :
{ $near :{
$geometry :{
type : "Point" ,
coordinates : [ 76.2 , 9.9 ] } ,
$maxDistance : 20000 }
}
}
)
.pretty();
这是我一直试图将数据提取到
中的pojo@Document(collection = "trial")
public class Ambulance {
@Id
String id;
@Field("amb_id")
String ambulanceId;
@Field("amb_number")
String licensePlateNumber;
@Field("driver_name")
String driverName;
@Field("driver_licence_id")
String driverLicenseNumber;
@Field("ownership")
String ownerShip;
@Field("ownership_address")
String ownerShipAddress;
@GeoSpatialIndexed(name="Location")
Double[] location;
//setters and getters
}
这是我一直在使用的存储库
@ComponentScan
@Repository
public interface AmbulanceRepo extends MongoRepository<Ambulance, String> {
GeoResults<Ambulance> findByLocationNear(Point p, Distance d);
}
和控制器
@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/")
public class NearbyAmbulanceController {
private AmbulanceRepo ambulanceRepo;
@Autowired
public NearbyAmbulanceController(AmbulanceRepo repo){
this.ambulanceRepo = repo;
}
@RequestMapping(value="/nearbyAmbulance",method = RequestMethod.POST)
@ResponseBody
public GeoResults<Ambulance> getAmbulanceDetails(
@RequestBody LocationRequest locationRequest){
System.out.println("lati "+locationRequest.getLatitude()+ " long "+locationRequest.getLongitude()+" d "+locationRequest.getDistance());
// List<Ambulance> ambulanceList=this.ambulanceRepo.findByLocationNear(new Point(Double.valueOf(locationRequest.getLongitude()),Double.valueOf(locationRequest.getLatitude())),new Distance(locationRequest.getDistance(), Metrics.KILOMETERS));
Point point = new Point(locationRequest.getLatitude(), locationRequest.getLongitude());
Distance distance = new Distance(locationRequest.getDistance(), Metrics.KILOMETERS);
GeoResults<Ambulance> ambulanceList=this.ambulanceRepo.findByLocationNear(point,distance);
System.out.println(ambulanceList);
return ambulanceList;
}
}
每次尝试时都没有结果。我确信我在给定的点和附近的位置有数据,我甚至可以使用mongoshell来获取它们。我觉得问题在于我在实体中注释了位置字段的方式。有什么我想念的吗?任何帮助都是有用的。
答案 0 :(得分:0)
似乎mongodb中有多个数据库,其名称为'trial'。我尝试删除所有这些,现在它工作正常。 Spring数据无法确定要查询的集合,因为在不同的数据库中存在多个具有相同名称的集合。希望这对某人有所帮助,因为我已经浪费了几天时间。
答案 1 :(得分:0)
Spring MongoDb地理空间查询:经过了很好的测试。
public List<MachineDetails> searchbylocation(String lat, String longt, String maxDistance) {
BasicQuery query1 = new BasicQuery("{geoLocation:{ $near: { $geometry: { type: 'Point',coordinates: ["+ lat+","+ longt+" ] }, $minDistance: 10, $maxDistance: "+maxDistance+"}}}");
List<MachineDetails> venues1 = mtemplate.find(query1, MachineDetails.class);
return venues1;
}