簡體   English   中英

使用 Postgres/PostGIS 高效更新 200 萬行的表

[英]Performantly update table with 2 million rows with Postgres/PostGIS

我有兩張桌子:

  • properties (geo_point POINT、locality_id INTEGER、neighborhood_id INTEGER、id UUID)
  • places_temp (id INTEGER,poly GEOMETRY,placetype TEXT)

注意: places_temp中的所有列都已編入索引。

properties有大約 200 萬行,我想:

  • 使用places_temp中的id更新properties中每一行的locality_idneighborhood_id ,其中properties.geo_point包含在places_temp.poly中的多邊形中

無論我做什么,它似乎都會掛幾個小時,在此期間我不知道它是否正常工作,連接丟失等。

關於如何高效地執行此操作的任何想法?

我的查詢:

  -- drop indexes on locality_id and neighborhood_id to speed up update
  DROP INDEX IF EXISTS idx_properties_locality_id;
  DROP INDEX IF EXISTS idx_properties_neighborhood_id;
  -- for each property find the locality and neighborhood
  UPDATE
    properties
  SET
    locality_id = (
      SELECT
        id
      FROM
        places_temp
      WHERE
        placetype = 'locality'
        -- check if geo_point is contained by polygon. geo_point is stored as SRID 26910 so must be
        -- transformed first
        AND st_intersects (st_transform (geo_point, 4326), poly)
      LIMIT 1),
  neighborhood_id = (
    SELECT
      id
    FROM
      places_temp
    WHERE
      placetype = 'neighbourhood'
      -- check if geo_point is contained by polygon. geo_point is stored as SRID 26910 so must be
      -- transformed first
      AND st_intersects (st_transform (geo_point, 4326), poly)
    LIMIT 1);
  -- Add indexes back after update
  CREATE INDEX IF NOT EXISTS idx_properties_locality_id ON properties (locality_id);
  CREATE INDEX IF NOT EXISTS idx_properties_neighborhood_id ON properties (neighborhood_id);
CREATE INDEX properties_point_idx ON properties USING gist (geo_point);
CREATE INDEX places_temp_poly_idx ON places_temp USING gist (poly);

UPDATE properties p
SET locality_id = x.id
FROM ( SELECT *
        , row_number() OVER () rn
        FROM places_temp t 
        WHERE t.placetype = 'locality'
        AND st_intersects (st_transform (p.geo_point, 4326), t.poly)
        )x
WHERE x.rn = 1
      ;

與其他字段類似(您可以將它們組合成一個查詢)

嘗試這個

        UPDATE
      properties
   SET
    locality_id =t.id, neighbourhood_id
    =t.id
    From(
    SELECT
    id
    FROM
    places_temp
  WHERE
    placetype in ('locality',  
   'neighbourhood') 
    AND st_intersects (st_transform 
   (geo_point, 4326), poly)
  LIMIT 1)) t

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM