1
1

More than 5 years have passed since last update.

クエリを利用してPostGISの座標データをカラムにつっこむ

Last updated at Posted at 2018-02-14

結論

文字列連結すれば何とかなった.
これが本当に普通のやり方なのか,他にもっといい方法がないのか,よく分からん.

背景

DBに入っているxy座標から,2次元のgeometry('point')型に変換したい.
webで検索しても,ST_GeomFromTextに生でデータを手書きしているサンプルしか見付からなくて絶望感にうちひしがれた.

できればpythonからつっこみたかったが,executemanyでは難しそうだったし,データ数が多くてexecuteをforで回すのはヤバそうなので,諦めた.

参考:
python - Unable to execute ST_GEOMFROMTEXT using executemany - Stack Overflow

なので,とりあえずxy座標をDBにカラムとして入れた状態からスタートする.

準備

CREATE EXTENSIONS postgis;
CREATE TABLE _point (
    x integer,
    y integer,
    geom geometry('Point')
);
INSERT INTO _point VALUES (10,15), (15,20);

更新

UPDATE _point SET geom = ST_GeomFromText('Point(' || x || ' ' || y || ')');

※コメントで指摘いただいたPostGISの型を生成する関数についてドキュメントを読んでみたところ,geometry('point')型の生成にはST_GeomFromTextの他に,ST_PointST_MakePointST_PointFromTextなどがあり,OpenGISとの互換性や内部処理の有無による実行速度及び精度に差があるらしい.格納されているデータのオリジンや今後予定している移植の可能性などを踏まえ適切な関数を選択するのが良さそう.

結果

SELECT * FROM _point;
 x  | y  |                    geom                    
----+----+--------------------------------------------
 10 | 15 | 010100000000000000000024400000000000002E40
 15 | 20 | 01010000000000000000002E400000000000003440
(2 rows)

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1