如何获得geodjango的k个最近邻居? [英] How do I get the k nearest neighbors for geodjango?

查看:39
本文介绍了如何获得geodjango的k个最近邻居?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下模型:

class Person:
     id       = models.BigAutoField(primary_key=True)
     name     = models.CharField(max_length=150)
     location = models.PointField()

如何使用geodjango通过位置获取k个最近邻居(KNN)?
我需要为此编写自定义SQL吗?
我在PostGIS中使用PostgreSQL.

How would I go by obtaining the k nearest neighbors (KNN) by location using geodjango?
Would I have to write custom SQL for that?
I am using PostgreSQL with PostGIS.

推荐答案

您可以使用

  • <-> 使用边界框的中心来计算最近的邻居.

    1. <-> which gets the nearest neighbor using the centers of the bounding boxes to calculate the inter-object distances.

    <#> 最近的邻居使用边界框本身来计算对象之间的距离.

    <#> which gets the nearest neighbor using the bounding boxes themselves to calculate the inter-object distances.

    在您的情况下,您想要的人似乎是<-> 运算符,因此是原始查询:

    In your case the one you want seems to be the <-> operator, thus the raw query:

    knn = Person.objects.raw(
        'SELECT * FROM myapp_person 
        ORDER BY location <-> ST_SetSRID(ST_MakePoint(%s, %s),4326)',
        [location.x, location.y]
    )[:k]
    

    由于自身的疲劳而进行您可以省略 [:k] 在原始SQL查询上添加 LIMIT 1 .(不要像我一样使用两者!)

    EDIT due to own derpiness: You can omit the [:k] to add LIMIT 1 on the raw SQL query. (Don't use both as I did!)

    在回答其他问题的过程中:

    In the process of answering your other question: How efficient is it to order by distance (entire table) in geodjango ,another solution maybe possible:

    通过启用空间索引并通过逻辑约束来缩小查询范围(如

    By enabling spatial indexing and narrowing down your query through logical constrains (as explained in my answer of the above -linked question) you can achieve a pretty fast KNN query as follows:

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

    这篇关于如何获得geodjango的k个最近邻居?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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