Spring Data Mongodb Near Query无效

时间:2016-01-17 12:31:12

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

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

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
    }
  }

3 个答案:

答案 0 :(得分:0)

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

try {   
    PreparedStatement stmt  = so.getPreparedStatementWithKey("SELECT * FROM et_elderly WHERE room = ?");
    stmt.setString(1, roomNum);
    stmt.executeQuery();
    rs = stmt.getResultSet();

    while(rs.next()){
        if(dosageTime.equalsIgnoreCase("morning")){
            if(rs.getInt("morningtaken")==0){
                // calculate the age
                java.sql.Date reportDate=rs.getDate("dob");
                DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                String text = df.format(reportDate);
                String year=text.substring(0, 4);
                String month=text.substring(5,7);
                String day=text.substring(8,10);

                // setting the information
                data.setElderBed(rs.getInt("bed"));
                data.setElderName(rs.getString("name"));
                data.setElderAge(ElderData.getAge(year,month,day));
                data.setElderGender(rs.getString("gender"));
                DosageList.add(data);   
                numofElder++;
            }
        }

        else if (dosageTime.equalsIgnoreCase("afternoon")){
            if(rs.getInt("afternoontaken")==0){
                // calculate the age
                java.sql.Date reportDate=rs.getDate("dob");
                DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                String text = df.format(reportDate);
                String year=text.substring(0, 4);
                String month=text.substring(5,7);
                String day=text.substring(8,10);

                // setting the information
                data.setElderBed(rs.getInt("bed"));
                data.setElderName(rs.getString("name"));
                data.setElderAge(ElderData.getAge(year,month,day));
                data.setElderGender(rs.getString("gender"));
                DosageList.add(data);   
                numofElder++;
            }
        }
        else if (dosageTime.equalsIgnoreCase("noon")){
            if(rs.getInt("noontaken")==0){
                // calculate the age
                java.sql.Date reportDate=rs.getDate("dob");
                DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                String text = df.format(reportDate);
                String year=text.substring(0, 4);
                String month=text.substring(5,7);
                String day=text.substring(8,10);

                // setting the information
                data.setElderBed(rs.getInt("bed"));
                data.setElderName(rs.getString("name"));
                data.setElderAge(ElderData.getAge(year,month,day));
                data.setElderGender(rs.getString("gender"));
                DosageList.add(data);   
                numofElder++;
            }
        }



    }

} catch (SQLException e1) {

    e1.printStackTrace();
}

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

答案 1 :(得分: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);

}

答案 2 :(得分:0)

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

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