问题描述
我试图通过使用Spring Data Mongo GeoSpatial找到距离以及位置。
遵循此https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.geo-near
GeoResults<VenueWithDisField> = template.query(Venue.class)
.as(VenueWithDisField.class)
.near(NearQuery.near(new GeoJsonPoint(-73.99,40.73),KILOMETERS))
.all();
我尝试过
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RestaurantWithDisField {
private Restaurant restaurant;
private Number dis;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "restaurants")
public class Restaurant {
@Id
private String id;
private String name;
@GeoSpatialIndexed(name = "location",type = GeoSpatialIndexType.GEO_2DSPHERE)
private GeoJsonPoint location;
}
public GeoResults<RestaurantWithDisField> findRestaurantsNear(GeoJsonPoint point,Distance distance) {
final NearQuery nearQuery = NearQuery.near(point)
.maxDistance(distance)
.spherical(true);
return mongoTemplate.query(Restaurant.class)
.as(RestaurantWithDisField.class)
.near(nearQuery)
.all();
}
但是结果是我得到了以下内容。如果我没有设置目标类型,而只是收集域类型,那么我会得到除距离以外的所有其他值。
Restaurant - RestaurantWithDisField(restaurant=null,dis=0.12914248082237584
Restaurant - RestaurantWithDisField(restaurant=null,dis=0.19842138954997746)
Restaurant - RestaurantWithDisField(restaurant=null,dis=0.20019522190348576)
有人可以帮助我为什么我无法获取域类型值,或者应该怎么办? 谢谢
解决方法
由于结果restaurant
中的值与目标实体属性不匹配,因此映射无法解析RestaurantWithDisField
中的Document
。
您可能想在这里使用继承而不是合成,并让RestaurantWithDisField
扩展Restaurant
,提供您自己的转换器或仅使用Restaurant
并依靠GeoResults
持有列表的GeoResult
中已经包含Distance
以及实际的映射域类型-几乎与您使用RestaurantWithDisField
进行建模相同。