春季数据MongoDB地理空间距离

问题描述

我试图通过使用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进行建模相同。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...