假設我有以下模型:
from django.db import models
from django.contrib.gis.db import models as gis_models
class Place(models.Model):
location = gis_models.PointField(geography=True, srid=4326)
后來我在這些地方進行搜索;我的查詢是“獲取距離我不遠 N 米的所有地方”:
from django.contrib.gis.db.models.functions import Distance
from django.contrib.gis.geos import Point
location = Point(1.0, 2.0)
distance = 20.0
queryset = queryset.annotate(distance=Distance("location", location)).filter(
distance__lte=distance
)
有沒有辦法使用 PostGIS 來優化這些查詢?例如,使用索引或相關的東西。
uj5u.com熱心網友回復:
你的代碼看起來不像 SQL,而且你沒有標記編程語言、框架或 ORM,所以我會給你一個 SQL 答案。
要搜索geometry從某個點開始小于 30 的所有 s,您可以使用
... WHERE ST_DWithin(geom, 'POINT(1 2)', 30)
支持它的索引是
CREATE INDEX ON tab USING gist (geom);
uj5u.com熱心網友回復:
Postgis 函式ST_DWithin應該使用相關的邊界框索引(如果存在)。
要創建這樣的空間索引,您可以執行以下操作:
CREATE INDEX unique_index_name ON table_name USING gist (geometry_column);
uj5u.com熱心網友回復:
正如@fresser 和@laurenz-albe 所建議的那樣,正確的索引是 GIST 索引:
from django.contrib.postgres.indexes import GistIndex
class Place:
...
class Meta:
indexes = [
GistIndex(fields=["location"]),
]
uj5u.com熱心網友回復:
您的問題是您的資料以度為單位(EPSG:4326),并且您要求以 20 為單位的所有內容。那 30 是度數,可能包括你的資料的一大塊(如果不是全部的話),所以 PostGIS 太聰明了,無法使用你的索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/526533.html
上一篇:SQL:如何僅提取與條件“WHEREcolumn1INcolumn2”匹配的行(其中column2是一個陣列)?
