Mongo 带限制的边界框查询
Mongo Bounding Box Query with Limit
我们正在使用 mongo(通过 pymongo)在我们的系统中存储点数据库。此数据是通过我们的 api 使用 边界框 查询($geoWithin)返回的。
我们希望将返回的结果数限制为从中心排序的 200 个。我试图找出最好的方法来做到这一点。目前,我们获得所有项目(无限制)。然后,我们计算距离并在 python 中排序。但是,对于大型数据集,这些计算非常缓慢且占用大量内存。
大家有更好的建议吗?我在其他 SO 问题中看到无法对边界框查询进行排序。然而,这些问题中的大多数都是 2 年以上的问题。
好的,我想我找到了解决办法。事实证明,您可以在同一个查询中同时使用 point/radius 和边界框。
# 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(通过 pymongo)在我们的系统中存储点数据库。此数据是通过我们的 api 使用 边界框 查询($geoWithin)返回的。
我们希望将返回的结果数限制为从中心排序的 200 个。我试图找出最好的方法来做到这一点。目前,我们获得所有项目(无限制)。然后,我们计算距离并在 python 中排序。但是,对于大型数据集,这些计算非常缓慢且占用大量内存。
大家有更好的建议吗?我在其他 SO 问题中看到无法对边界框查询进行排序。然而,这些问题中的大多数都是 2 年以上的问题。
好的,我想我找到了解决办法。事实证明,您可以在同一个查询中同时使用 point/radius 和边界框。
# 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
}),
])}
]
}