Spring Data Mongodb Near Query无效

问题描述 投票:1回答:2

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

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
    }
  }
java mongodb spring-data spring-data-mongodb
2个回答
0
投票

我最近遇到了一些近乎查询的问题,我解决了如下问题:

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());

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


0
投票

你可以使用简单的@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);

}
© www.soinside.com 2019 - 2024. All rights reserved.