# [postgis-users] update / closest polygon

Fri Mar 3 10:41:46 PST 2006

Hi Josh,

Though you could probably achieve this using nested queries, computing
distance to and from each of your points/polygons could be an expensive
operation.  If this operation will be performed more than once, then I
would be inclined to create a table holding the distances between your
points and polygons, then indexing based on this distance:

CREATE TABLE poly_point_distance AS
SELECT c.centroid_id, p.polygon_id, distance(c.centroids.the_geom,
p.polygons.the_geom) AS pp_distance
FROM polygons AS p
INNER JOIN centroids AS c
ON expand(centroids.the_geom,1000) && polygons.the_geom
AND distance(centroids.the_geom, polygons.the_geom) < 1000

CREATE INDEX distance_idx ON poly_point_distance (pp_distance);

You would probably want to create indices on the foreign keys in this
table as well.

The above query may be able to be optimized, this is just a quick jot.

You can then perform a join against this table during your update to
pull out the minimum distance.

Josh Livni wrote:

>  I have a basic 'update' question.  For a simple example, given a bunch
> of points, I'd like to give them attributes based on the closest polygon.
>
> Let's say I try this:
>
> UPDATE centroids
> SET p_distance = distance(centroids.the_geom, polygons.the_geom),
> FROM polygons
> WHERE expand(centroids.the_geom,1000) && polygons.the_geom
>   and Distance(centroids.the_geom, polygons.the_geom) < 1000
>
>
> This associates any polygon within 1k to the point -- but not
> necessarily the closest.  Is there an easy way to bring in an 'order by
> distance' and 'limit 1' kind of idea to the UPDATE query?  Do I need to
> do that in a separate select, make a temp table, and then join?
>
> Thanks in advance for any pointers.
>
>   -Josh
>
>
> _______________________________________________
> postgis-users mailing list
> postgis-users at postgis.refractions.net
> http://postgis.refractions.net/mailman/listinfo/postgis-users
>

--