我尝试使用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)有没有人能告诉我为什么我不能获取域类型值,或者我该怎么做?谢谢
发布于 2020-08-20 15:33:42
映射无法解析RestaurantWithDisField中的restaurant,因为结果Document中的值与目标实体属性不匹配。
在这里,您可能希望使用继承而不是组合,并让RestaurantWithDisField扩展Restaurant,提供您自己的转换器,或者只使用Restaurant,并依靠GeoResults保存一个GeoResult列表,该列表已经包含了Distance以及实际的映射域类型-与您使用RestaurantWithDisField建模的情况几乎相同。
发布于 2021-10-01 06:32:59
如果您正确命名Spring Data Mongo存储库并将数据放入域POJO中,Spring data Mongo存储库可以为您生成正确的查询。我找到了here - blocking或here - reactive的例子。
interface RestaurantRepository extends MongoRepository<Restaurant, String> {
Collection<GeoResult<Restaurant>> findByName(String name, Point location);
}在我看来,(反应式)MongoTemplate使用GeoNearResultDocumentCallback将restaurant包装在GeoResult中。你可能想去那里看看。
https://stackoverflow.com/questions/63437179
复制相似问题