【问题标题】:Spring Data Mongodb Near Query not worksSpring Data Mongodb Near Query 不起作用
【发布时间】:2016-01-17 12:31:11
【问题描述】:

我想找到最近的商店。所以我写了这段代码:

public class ShopRepositoryImpl extends GenericRepositoryImpl<ShopEntity, String> implements ShopRepositoryCustom {

    @Autowired
    protected MongoTemplate template;

    @Override
    public GeoResult<ShopEntity> findNearest(Point location) {
        List<GeoResult<ShopEntity>> result = template.geoNear(
                NearQuery.near(location).maxDistance(new Distance(70, Metrics.KILOMETERS))
                        .query(new Query(Criteria.where("location")).limit(1)),
                ShopEntity.class).getContent();
        if (result.isEmpty())  {
            return null;
        } else {
            return result.get(0);
        }
    }
}

在tomcat控制台中有:

2016-01-17 12:13:26.151  WARN 645 --- [nio-8080-exec-2]     o.s.data.mongodb.core.MongoTemplate      : Command execution of 
{ "geoNear" : "shop" , "query" : { "location" : { }} , "maxDistance" : 0.010974991600211786 , "distanceMultiplier" : 6378.137 , "num" : 1 , "near" : [ 48.8703939 , 2.0] , "spherical" : true} 
failed: no geo indices for geoNear

我试过这个:

public interface ShopRepository extends GenericRepository<ShopEntity, String>, ShopRepositoryCustom {
    GeoResults<ShopEntity> findByLocationNear(Point location, Distance distance);
}

没有结果

在我的数据库中,我有一个元素:

  {
    "name": "A shop",
    "street": "149 Rue Montmartre",
    "city": "Paris",
    "zip": "75002",
    "country": "France",
    "location": {
      "x": 48.8703937,
      "y": 2.3422999
    }
  }

【问题讨论】:

  • 我的实体有:@GeoSpatialIndexed private double[] location;

标签: java mongodb spring-data spring-data-mongodb


【解决方案1】:

您可以只使用简单的@Query 注释。 通过在您的 mongod 命令行中运行来索引您的位置属性:db.yourCollection.createIndex( { location : "2dsphere" } )。 然后在 MongoRepository 中使用查询注释:

    @Repository
public interface ShopRepository extends MongoRepository<Shop, String>{

    @Query(value = "{\"location\":\n" +
"       { $near :\n" +
"          {\n" +
"            $geometry : {\n" +
"               type : \"Point\" ,\n" +
"               coordinates : [ ?0, ?1] }\n" +
"          }\n" +
"       }}")
    public List<Shop> nearByShops(double longitude, double latitude);

}

【讨论】:

    【解决方案2】:

    我最近遇到了一个near query的问题,我解决了如下:

    mongoTemplate.indexOps(MyClass.class).ensureIndex(new GeospatialIndex("attribute.holding.coordinates"));
    NearQuery nearQuery = NearQuery.near(x, y);
    final GeoResults<MyClass> geoResults = mongoTemplate.geoNear(nearQuery, MyClass.class);
    return geoResults.getContent().stream().map(GeoResult::getContent).collect(Collectors.toList());
    

    这会显式应用地理空间索引,然后使用它来查找附近的对象。

    【讨论】:

    • 它不起作用 :( 2016-02-01 01:24:42.273 WARN 13601 --- [nio-8080-exec-1] os.data.mongodb.core.MongoTemplate :命令执行 { "geoNear" : "shop" , "near" : [ 48.8865967 , 2.0] , "spherical" : false} 失败:多个二维索引,不确定在哪个上运行 geoNear
    • @Maryo 您的域模型导致此查询不起作用... mongoTemplate.indexOps(Device.class).ensureIndex(new GeospatialIndex("position"));例如..'position' 是我要查询的域中的唯一属性。
    【解决方案3】:

    要使用 near by 首先创建一个索引2dsphere,如下所示:

    db.places.createIndex( { location: "2dsphere" } )
    

    【讨论】:

      【解决方案4】:

      请阅读 MongoDB 文档 https://docs.mongodb.com/manual/geospatial-queries/

      你需要:

      1. 像这样存储位置数据:

        位置:{ 类型:“点”, 坐标:[-73.846077, 40.828447] }

      2. 创建地理索引

        db.collection.createIndex({ location : "2dsphere" })

      你可以让 SpringData 为你工作,在你的实体中使用它:

      @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
      private MongodbLocation location;
      

      并在属性文件中启用索引创建:

      data.mongodb.auto-index-creation: true
      

      位置对象的 POJO 示例:

      public class MongodbLocation {
          List<Double> coordinates;
          String type;
      }
      

      并且不要忘记:点对象和坐标列表需要先经度,然后是纬度。

      然后...你可以使用这样的东西:

      public interface AdRepository extends MongoRepository<AdEntity, String> {
          GeoResults<AdEntity> findByAddressLocationNear(Point p, Distance d);
      
          GeoPage<AdEntity> findByAddressLocationNear(Point p, Distance d, Pageable pageable);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-15
        • 1970-01-01
        • 2018-03-20
        • 2015-01-27
        • 2020-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多