python - 在geodjango中按距离排序效率如何(整张表)

标签 python django postgresql geodjango

假设我有以下数据模型:

Person(models.Model):
    id       = models.BigAutoField(primary_key=True)
    name     = models.CharField(max_length=50)
    location = models.PointField(srid=4326)

还假设我有一个查询 Django 后端的应用程序,该应用程序的唯一功能是返回以分页格式从最近到最远排序的注册用户列表。

目前我有以下查询:

# here we are obtaining all users in ordered form
current_location = me.location
people = Person.objects.distance(current_location).order_by('distance')

# here we are obtaining the first X through pagination
start_index = a
end_index = b

people = people[a:b]

虽然这可行,但速度没有我想要的那么快。

我担心这个查询的速度。如果表很大(超过 100 万),带有 PostGIS 的 Postgres SQL 数据库是否必须先计算数据库中 current_location 和每个 location 之间的距离通过 order_by 操作对后续的 100 万行进行排序?

谁能建议一种更有效的替代方法来根据距离检索和排序附近的用户?

最佳答案

如果您想按距离对该表中的每个条目进行排序,那么它会像预期的那样慢,并且没有什么可以做的(我在这个时间点和我的知识中知道这一点。)!

您可以按照以下步骤并做出一些假设来提高计算效率:

  1. 在您的 table 上启用 spatial indexing。要在 GeoDjango 中做到这一点,请遵循 the doc instructions 并将它们适合您的模型:

    Note

    In PostGIS, ST_Distance_Sphere does not limit the geometry types geographic distance queries are performed with. [4] However, these queries may take a long time, as great-circle distances must be calculated on the fly for every row in the query. This is because the spatial index on traditional geometry fields cannot be used.

    For much better performance on WGS84 distance queries, consider using geography columns in your database instead because they are able to use their spatial index in distance queries. You can tell GeoDjango to use a geography column by setting geography=True in your field definition.

  2. 现在您可以使用一些逻辑约束来缩小查询范围:

    示例:我的用户不会寻找距离他当前位置超过 50 公里的人。

  3. 使用 dwithin 空间查找缩小搜索范围,它利用上述 spatial indexing ,因此速度非常快。

  4. 最后对剩余的行应用距离顺序。

最终的查询看起来像这样:

current_location = me.location
people = People.objects.filter(
    location__dwithin=(current_location, D(km=50))
).annotate(
    distance=Distance('location', current_location)
).order_by('distance')

P.S:与其创建自定义分页尝试,不如利用为 django View 提供的分页方法更有效:

或者您可以使用 Django Rest Framework 并使用它的分页:

关于python - 在geodjango中按距离排序效率如何(整张表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45383792/

相关文章:

python - 传递字典时映射与应用映射

python - 为 Django 获取 JSON 数据的最佳 JSON 库?

python - Django 多个缓存 - 如何选择 session 进入哪个缓存?

Django 内联表单集自定义验证一次只验证一个表单集

Sql 从另一个表的一组结果中以数组形式查询新列

postgresql - 等同于 pg_restore 的 SQL 命令

python - 在 Python 3 中与 3D 对象交互?

python - 关于如何在 tkinter 中制作 gif 动画的问题

python - 如何使用 selenium python 检索元素的所有 css 属性?

node.js - Heroku 部署 - 找不到路径