【问题标题】:How can I replicate this js Geospatial query in morphia?如何在 morphia 中复制这个 js 地理空间查询?
【发布时间】:2012-03-16 13:45:49
【问题描述】:

通过 shell 脚本在 mongodb 中查询地理空间数据看起来很简单,但是,我正在尝试在 morphia (playmorphia) 中复制一些代码。

获取一定半径内的所有点,文档说:

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

这是我的 Peak 模型中的代码:

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().find() 是否做错了什么?有没有更优雅的方式使用模型来做到这一点,例如峰.找到..?谢谢!

【问题讨论】:

    标签: mongodb playframework morphia


    【解决方案1】:

    您需要在地理字段上放置索引。

    我的项目中的示例代码:

    @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

    【讨论】:

    • 谢谢。我没有意识到它在 utils import com.google.code.morphia.utils.IndexDirection;
    • 以前,我确实通过 mongodb shell 手动索引该字段,这就是它首先起作用的原因。将您的答案标记为正确,因为它可以帮助他人。
    【解决方案2】:

    **@Indexed(IndexDirection.GEO2D) public Double[] geo = new Double[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());
        }**
    

    【讨论】:

      猜你喜欢
      • 2011-06-01
      • 2015-10-25
      • 2015-06-07
      • 2013-09-25
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多