带有限制的 Mongo 边界框查询 [英] Mongo Bounding Box Query with Limit

查看:34
本文介绍了带有限制的 Mongo 边界框查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用 mongo(通过 pymongo)在我们的系统中存储点数据库.这些数据是通过我们的 api 使用 bounding box 查询 ($geoWithin) 返回的.

We are using mongo (via pymongo) to store a database of points in our system. This data is returned via our api using bounding box queries ($geoWithin).

我们希望将返回的结果数量限制为从中心排序的 200 个.我试图找出最好的方法来做到这一点.目前,我们获得所有物品(无限制).然后,我们在python中计算距离和排序.但是,对于大型数据集,这些计算非常缓慢且占用大量内存.

We want to limit the number of results returned to 200 sorted from the center. I'm trying to figure out the best way to do this. Currently, we get all items (no limit). Then, we calculate distance and sort in python. However, that those calculations very slow and memory intensive for large datasets.

大家有更好的建议吗?我在其他 SO 问题中看到不可能对边界框查询进行排序.但是,这些问题中的大多数都是 2 岁以上的问题.

Anyone have better suggestions? I see in other SO questions that it isn't possible to sort bounding box queries. However, most of those questions were 2+ years old.

推荐答案

好吧,我想我想出了一个解决方案.事实证明,您可以在同一个查询中同时使用点/半径和边界框.

Alright, I think I figured out a solution. Turns out that you can use both a point/radius and bounding box in the same query.

    # do both a bounding box and point query
    # point query should conatain the entire bbox
    # this provides sorting and distance calculations
    max_distance = int(haversine(sw_lat, sw_lon, self.centroid.y, self.centroid.x))
    self.new_query = {
        '$and': [
            {'point': {
                '$geoWithin': {"$box": box }
            }},
            {'point': OrderedDict([
                ('$geoNear', {
                    '$geometry':  {
                        'type': 'Point' ,
                        'coordinates': [self.geo.centroid.coords[0], self.geo.centroid.coords[1]]
                    },
                    '$maxDistance': max_distance
                }),

            ])}
        ]
    }

这篇关于带有限制的 Mongo 边界框查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆