如何获得geodjango的k个最近邻居? [英] How do I get the k nearest neighbors for geodjango?
问题描述
假设我具有以下模型:
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.
推荐答案
您可以使用 在您的情况下,您想要的人似乎是 In your case the one you want seems to be the 由于自身的疲劳而进行您可以省略 EDIT due to own derpiness: You can omit the 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 这篇关于如何获得geodjango的k个最近邻居?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!<->
使用边界框的中心来计算最近的邻居.
<->
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.<->
运算符,因此是原始查询:<->
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
.(不要像我一样使用两者!)[:k]
to add LIMIT 1
on the raw SQL query. (Don't use both as I did!)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]