2012-03-16 54 views
0

查询mongodb中的地理空间数据通过shell脚本看起来很直观,但是,我试图在morphia(playmorphia)中复制一些代码。如何在morphia中复制这个js地理空间查询?

得到一定半径内的所有点,文件说:

> center = [50, 50] 
> radius = 10 
> db.places.find({"loc" : {"$within" : {"$center" : [center, radius]}}}) 

这是我在我的巅峰型号代码:

Double[] loc = new Double(2); 
// it's set to my [Longitude, Latitude] 

List<Peak> peaks = play.modules.morphia.Model.ds().find(Peak.class).field("loc").near(loc[0], loc[1], 10/111.12).limit(50).asList(); 

它的工作原理,但我在使用DS(做错事)。找()?有没有一种更优雅的方式来使用模型来做到这一点? Peak.find ..?谢谢!

回答

0

您需要在地理区域上放置索引。从我的项目

示例代码:

@Indexed(IndexDirection.GEO2D) 
public Double[] geo = new Double[2]; 


List<User> pharmacist = MorphiaQuery.ds() 
.createQuery(User.class) 
.filter("isPharmacist",true) 
.field("geo") 
.within(nelat, nelng, swlat, swlng) 
.field("geo") 
.near(u.geo[0], u.geo[1]) 
.limit(limit) 
.asList(); 

检查手册: http://code.google.com/p/morphia/wiki/Query#Geo-spatial

+0

谢谢你。我没有意识到它在utils import com.google.code.morphia.utils.IndexDirection; – zenoexo 2012-03-31 01:34:05

+0

此前,我通过mongodb shell手动为该字段编制索引,这就是为什么它首先运行的原因。标记你的答案是正确的,因为它可以帮助他人。 – zenoexo 2012-03-31 13:51:08

+0

[手册现在位于此处](https://github.com/mongodb/morphia/wiki/Query#geo-spatial) – nostromo 2013-09-19 01:23:43

0

** @索引(IndexDirection.GEO2D) 公共双[] =地理新双[2];

public static string getResult`enter code here`() { 
     DB datastore = ConnectionFactory.getInstance().getDatabaseMongo(); 
     double[] near = { 20.593684, 78.96288 }; 
     BasicDBObject basicDBObject = new BasicDBObject(); 
     basicDBObject.put("type", "Point"); 
     basicDBObject.put("coordinates", near); 
     BasicDBObject geoNearParams = new BasicDBObject(); 
     geoNearParams.append("geoNear", <collection name>); 
     geoNearParams.append("near", basicDBObject); 
     geoNearParams.append("spherical", true); 
     geoNearParams.append("maxDistance", 100); 
     geoNearParams.append("limit", 10); 
     CommandResult commandResult = datastore.command(geoNearParams); 
     commandResult.getErrorMessage(); 
     Object data = commandResult.get("results"); 
     System.out.println(data.toString()); 
    }**