PostGISは、オブジェクトRDBであるPostgreSQLの拡張で、GIS (地理情報システム)オブジェクトを格納することができます。PostGISは、GiSTベースのR木空間インデクスをサポートし、GISオブジェクトの解析および処理を行う機能を持ちます。
本マニュアルは、3.2.0rc1版のマニュアルです。
この作品はクリエイティブ・コモンズ 表示 - 継承 3.0 非移植 ライセンスの下に提供されています。好きなようにこの材料を使うことができますが、PostGIS Project のクレジット提示を求めます。また可能な限りhttp://postgis.netへのリンクを求めます。
PostGISは、PostgreSQLリレーショナルデータベースの空間拡張です。Refractions Research Incが、空間データベース技術の研究プロジェクトとして作成しました。Refractionsはカナダ・ブリティッシュコロンビア州・ビクトリアにある、データインテグレーションとカスタムソフトウェア開発に特化した、GISとデータベースのコンサルティング会社です。
PostGISは、現在ではOSGeo財団のプロジェクトです。多数のFOSS4G開発者とPostGISの機能と多彩さから大きな利益を得る世界中の企業が、PostGISの開発と資金提供を行っています。
PostGISプロジェクトの開発グループは、PostGISが、OpenGISとSQL/MM空間標準の領域における重要なGIS機能、高度なトポロジ構築 (カバレッジ、サーフェス、ネットワーク)、GISデータの表示と編集を行うデスクトップユーザインタフェースツール、およびウェブベースのアクセスツールのためのデータソースに、より良く対応するよう、サポートと機能強化を行う予定です。
PostGISプロジェクト運営委員会 (PostGIS Project Steering Committee, PSC)は、総合的な指示、リリースサイクル、ドキュメンテーション、支援活動に関する調整を行っています。また、委員会は、全体的なユーザサポート、PostGISコミュニティからのパッチの受け付けと適用、 開発者のコミットのアクセス、新しい委員、APIの重要な変更といった、PostGISを含む雑多な問題に関する投票を行っています。
MVT機能、誤り修正、パフォーマンスと安定性の向上、GitHubキュレーション、PostGISとPostgreSQLのリリースの調整
Buildbotのメンテナンス、Windows版と試験版のビルド、ドキュメンテーション、PostgreSQLとの調整、X3D対応、Tiger Geocoder機能、関数管理。
ラスタ開発、GDALとの統合、ラスタローダ、ユーザサポート、一般的なバグフィクス、様々なOS (Slackware, Mac, Windows他)での試験。
インデックス改善、誤り修正とジオメトリ/ジオグラフィ関数の改善、SFCGAL、ラスタ、GitHubキュレーション、Travis Botのメンテナンス。
PostGISプロジェクトの副創始者。総合的なバグフィクス、ジオグラフィ機能、ジオグラフィとジオメトリのインデックス機能 (2次元,、3次元、n次元インデクスとあらゆる空間インデクス)、ジオメトリ内部構造、GEOS機能の統合とGEOSリリースとの調整、PostgreSQLのリリースとの調整、ローダ/ダンパ、シェープファイルGUIローダ。
誤り修正とメンテナンス、ビルドボットのメンテナンス、gitミラーの管理、関数管理、GEOSの新機能の統合、GEOSリリースとの調整、トポロジ機能、ラスタフレームワークと低水準API関数。
ラスタ開発、GDALドライバ機能、ローダ。
距離関数の強化 (3次元距離、関係関数を含む)と追加、Tiny WKB出力書式(TWKB)と一般的なユーザサポート。
ジオメトリクラスタリング関数の追加、他のジオメトリアルゴリズムの強化、GEOSの強化、および全体のユーザ対応
XML (KML, GML)/GeoJSON入出力関数と3次元対応と誤り修正。
GEOS機能強化と文書
MapBox Vector Tile関数とGeoBuf関数、Gogsの試験とGitLabの実験。
CMakeのPostGISへの対応、Python版のオリジナルのラスタローダと低級ラスタAPI関数の構築。
ラスタ全体のアーキテクチャ、プロトタイピング、プログラミング支援。
以前のPSCメンバ。誤り修正とメンテナンスの活動、空間インデックス選択性とバインディング、ローダ/ダンパ、およびシェープファイルGUIローダの調整、新機能の統合と強化。
以前のPSCメンバ。一般的な開発、サイトとBuildbotのメンテナンス、OSGeoインキュベーション管理。
以前のPSCメンバ。文書と文書補助ツール、Buildbotのメンテナンス、PostGISニュースグループでの高度なユーザサポート、PostGISメンテナンス機能の強化。
PostGISのオリジナルの開発/副創始者。サーバサイドのオブジェクト、インデクスのバインディングや多数のサーバサイドの解析機能を記述。
シェープファイルのローダ/ダンパのオリジナル開発者
中核機能の、継続的なメンテナンスと開発。曲線機能の強化。シェープファイルGUIローダ。
ラスタ開発 (ほとんど地図代数解析関数)。
Alex Bodnaru | Gerald Fenoy | Maxime Guillaud |
Alex Mayrhofer | Gino Lucrezi | Maxime van Noppen |
Andrea Peri | Greg Troxel | Michael Fuhr |
Andreas Forř Tollefsen | Guillaume Lelarge | Mike Toews |
Andreas Neumann | Haribabu Kommi | Nathan Wagner |
Anne Ghisla | Havard Tveite | Nathaniel Clay |
Antoine Bajolet | IIDA Tetsushi | Nikita Shulga |
Artur Zakirov | Ingvild Nystuen | Norman Vine |
Barbara Phillipot | Jackie Leng | Patricia Tozer |
Ben Jubb | James Marca | Rafal Magda |
Bernhard Reiter | Jason Smith | Ralph Mason |
Björn Esser | Jeff Adams | Rémi Cura |
Brian Hamlin | Jonne Savolainen | Richard Greenwood |
Bruce Rindahl | Jose Carlos Martinez Llari | Roger Crew |
Bruno Wolff III | Jörg Habenicht | Ron Mayer |
Bryce L. Nordgren | Julien Rouhaud | Sebastiaan Couwenberg |
Carl Anderson | Kashif Rasul | Sergey Fedoseev |
Charlie Savage | Klaus Foerster | Shinichi Sugiyama |
Christoph Berg | Kris Jurka | Shoaib Burq |
Christoph Moench-Tegeder | Laurenz Albe | Silvio Grosso |
Dane Springmeyer | Lars Roessiger | Steffen Macke |
Dave Fuhry | Leo Hsu | Stepan Kuzmin |
David Garnier | Loic Dachary | Stephen Frost |
David Skea | Luca S. Percich | Talha Rizwan |
David Techer | Maria Arias de Reyna | Tom Glancy |
Dmitry Vasilyev | Marc Ducobu | Tom van Tilburg |
Eduin Carrillo | Mark Sondheim | Vincent Mora |
Eugene Antimirov | Markus Schaber | Vincent Picavet |
Even Rouault | Markus Wanner | Volf Tomáš |
Frank Warmerdam | Matt Amos | |
George Silva | Matthias Bay |
これらは、PostGISプロジェクトに開発者の時間、ホスティング、または直接の資金提供のいずれかの貢献をした企業です。アルファベット順:
クラウドファンディングキャンペーンは、PostGIS開発チームが走らせているキャンペーンです。欲しくて仕方ない機能に資金を与えて、多数の人々にサービスを提供できるようにするためのものです。それぞれのキャンペーンでは、特定の機能または機能の集合に焦点があてられます。それぞれのスポンサーは、必要な資金提供のうち少しだけを提供し、十分な人/組織の寄付で、たくさんの助けになる作業に支払う基金を持ちます。他の多くの人が寄付に協力してくれそうな機能に関するアイデアがありましたら、PostGIS newsgroupに、その考えを投稿して下さい。一緒に実現できます。
PostGIS 2.0.0はこの戦略を実施する最初のリリースです。PledgeBankを使い、2件のキャンペーンが成功しました。
postgistopology - 10以上のスポンサーがTopoGeometry機能の構築と2.0.0でのトポロジ対応強化とのために、それぞれ250米ドルを寄付しました。
postgis64windows - 20のスポンサーが、Windows上でのPostGIS 64ビット版に必要な作業のために、それぞれ100米ドルを寄付しました。
ジオメトリ演算ライブラリGEOS
地理空間データ抽象化ライブラリGDALは、PostGIS 2で導入されたラスタ機能の多くに使われています。また、GDALのPostGIS対応に必要な改善はGDALプロジェクトに貢献しています。
地図投影ライブラリPROJ
最後ですがおろそかにできないのがPostgreSQLです。PostGISはこの巨人に立っています。PostGISの速度と柔軟性は、PostgreSQLが提供する拡張性、優れたクエリプランナ、GiSTインデックス、多数のSQL機能があって初めて成り立ちます。
本章では、PostGISのインストールに必要な手順について説明します。
全ての依存がパスに入っているとする場合、次のようにコンパイルします。
tar xvfz postgis-3.2.0rc1.tar.gz cd postgis-3.2.0rc1 ./configure make make install
PostGISをインストールした後は、利用したいデータベース個々内で利用可能にする必要があります。
![]() | |
多くのOSで、ビルドされたPostgreSQL/PostGISパッケージがあります。多くの場合、コンパイルが必要なのは、最もひどい最先端の版が欲しい場合やパッケージメンテナンスを行う人ぐらいです。 本節では、一般的なコンパイル手順を示します。Windows用や他のOS用等にコンパイルするなら、PostGIS User contributed compile guidesやPostGIS Dev Wikiで、より詳細な助けが見つかるかも知れません。 多くのOS用のビルド済みパッケージの一覧はPostGIS Pre-built Packagesにあります。 Windowsユーザの場合は、スタックビルダか、PostGIS Windows download siteから安定版を得ることができます。また、週に1回か2回、刺激的なことがあれば随時ビルドを行っているvery bleeding-edge windows experimental buildsもあります。これらはPostGISの進行中のリリースでの試験に使用します。 |
PostGISモジュールは、PostgreSQLバックエンドサーバの拡張です。PostGIS 3.2.0rc1では、コンパイルのために、完全なPostgreSQLサーバヘッダが必要です。PostgreSQL 3.2.0rc1以上でビルドできます。古い版のPostgreSQLはサポートされません。
PostgreSQLをインストールしていないならPostgreSQLインストールガイドを参照して下さい。http://www.postgresql.org/にあります。
![]() | |
GEOS機能を有効にするために、PostgreSQLをインストール時に明示的に標準C++ライブラリに対する明示的なリンクが必要になる場合があります。 LDFLAGS=-lstdc++ ./configure [コンフィギュアオプション] これは、古い開発ツールとインチキC++例外との対話のための応急処置です。怪しい問題 (望んでいないのにバックエンドが閉じたりそれに近い挙動を起こす)を経験したなら、このトリックを試してみて下さい。もちろん、これを行うにはPostgreSQLをはじめからコンパイルし直す必要があります。 |
次のステップでは、PostGISソースのコンフィギュレーションとコンパイルに概要を記述します。これらは、Linuxユーザ用に書いてありますので、WindowsやMacでは動作しません。
ダウンロードサイトhttp://download.osgeo.org/postgis/source/postgis-3.2.0rc1.tar.gzからソースのアーカイブを入手します。
wget http://download.osgeo.org/postgis/source/postgis-3.2.0rc1.tar.gz tar -xvzf postgis-3.2.0rc1.tar.gz
これで、カレントディレクトリの下にpostgis-3.2.0rc1
ができます。
もしくはsvnレポジトリhttp://svn.osgeo.org/postgis/trunk/からチェックアウトします。
git clone https://git.osgeo.org/gitea/postgis/postgis.git postgis
新しく作られたpostgis-3.2.0rc1
ディレクトトリに移動して、インストールを続けます。
PostGISのビルドと利用のために、次のものが必要です。
必須
PostgreSQL 9.6以上。PostgreSQLの完全なインストール (サーバヘッダを含む)が必要です。PostgreSQLは http://www.postgresql.org/にあります。
完全なPosgreSQL/PostGIS対応表とPostGIS/GEOS対応表についてはhttp://trac.osgeo.org/postgis/wiki/UsersWikiPostgreSQLPostGISをご覧ください。
GNU Cコンパイラ (gcc
)。ANSI Cコンパイラの中には、PostGISをコンパイルできるものもありますが、gcc
でコンパイルするのが最も問題が少ないと見ています。
GNU Make (gmake
またはmake
)。多くのシステムで、GNU makeがデフォルトのmakeになっています。make -v
を実行して版を確認して下さい。他版のmake
では、PostGISのMakefile
を完全に処理しきれないかもしれません。
投影変換ライブラリ Proj4 の 4.9.0版以上。地理座標系の改善の利点を得るには、Proj4 4.9以上が必要です。Proj4ライブラリは、PostGISの座標系投影変換機能に使われます。Proj4は、http://trac.osgeo.org/proj/からダウンロードできます。
投影変換ライブラリ Proj4 の 4.9.0版以上。地理座標系の改善の利点を得るには、Proj4 4.9以上が必要です。Proj4ライブラリは、PostGISの座標系投影変換機能に使われます。Proj4は、http://trac.osgeo.org/proj/からダウンロードできます。
LibXML2の2.5.x以上。LibXML2は現在取り込み関数 (ST_GeomFromGMLとST_GeomFromKML)で使っています。LibXML2はhttp://xmlsoft.org/downloads.htmlからダウンロード可能です。
JSON-C 0.9以上。JSON-Cは現在、ST_GeomFromGeoJsonによるGeoJSONの取り込みに使われます。JSON-Cはhttps://github.com/json-c/json-c/releases/からダウンロード可能です。
GDAL 1.8以上 (古い版では一部機能が働かなかったり挙動が異なるので1.9以上を強く推奨します)。ラスタ機能に必要で、CREATE EXTENSION postgis
でのインストールに必要となります。このため、PostgreSQL 9.1以上での使用では非常に推奨されますhttp://trac.osgeo.org/gdal/wiki/DownloadSource/からダウンロード可能です。
このパラメータは現在のところ壊れていて、PostgreSQLのインストール先にしかインストールされません。このバグのトラックについてはhttp://trac.osgeo.org/postgis/ticket/635をご覧ください。
オプション
ドライバを有効にするにはSection 2.1, “簡略版”を参照してください。
GTK (GTK+2.0, 2.8+が必要)。シェープファイルのローダであるshp2pgsql-guiのコンパイル用です。http://www.gtk.org/にあります。
SFCGAL 1.1版以上。追加的な2次元や3次元の高度な解析関数をPostGISで使うために使用するものです。Section 8.10, “SFCGAL関数”をご覧下さい。また、GEOSを使う2次元関数のうちいくつか (たとえばST_IntersectionやST_Area)は、GEOSでなくSFCGALを使用することができます。PostgreSQLコンフィギュレーション変数postgis.backend
によって、SFCGALがインストールされている場合にはエンドユーザがバックエンドを制御することができます (デフォルトではGEOS)。SFCGAL 1.2は少なくともCGAL 4.3とBoost 1.54 (http://oslandia.github.io/SFCGAL/installation.htmlをご覧下さい)が必要ですのでご注意下さい。https://github.com/Oslandia/SFCGALにあります。
Section 14.1, “住所標準化”をビルドするには、PCRE http://www.pcre.org (Unix系システムには通常はインストール済みです)も必要です。parseaddress-stcities.h
内のエンコードしたデータを再構築したい場合には、Perl CPANのRegex::Assemble
パッケージのみ必要です。Section 14.1, “住所標準化”は、PCREライブラリを検出するか、コンフィギュレーションで適切に--with-pcre-dir=/path/to/pcre
を指定すると、自動的にビルドされます。
ST_AsMVTを有効にするには、protobuf-cライブラリ (実行時)とprotoc-cコンパイラ (ビルド時)が必要です。protobuf-cの正しい最小版を確認するには、pkg-configが必要です。protobuf-cをご覧下さい。
CUnit (CUnit
)。レグレッションテストに必要です。http://cunit.sourceforge.net/にあります。
DocBook (xsltproc
)。文書のビルドに必要です。http://www.docbook.org/にあります。
DBLatex (dblatex
)。文書をPDFでビルドするのに必要です。http://dblatex.sourcforge.net/にあります。
ImageMagick (convert
)。文書で使う画像を生成するのに必要です。http://www.imagemagick.org/にあります。
ほとんどのLinuxのインストールと同様に、最初のステップでは、ソースコードのビルドに使われるMakefileを生成します。これは、シェルスクリプトが行います。
./configure
パラメータを付けない場合には、このコマンドは自動で、PostGISのソースコードのビルドを行うのに必要なコンポーネントやライブラリをシステム上で探します。./configureとするのが一般的な使い方ですが、標準的でない位置に必要なライブラリやプログラムを置いてある場合のために、いくつかのパラメータを受け付けます。
次のリストで、共通して使われるパラメータを示します。 完全なリストについては、--helpまたは--help=shortパラメータを使って下さい。
Starting with PostGIS 3.0, the library files generated by default will no longer have the minor version as part of the file name. This means all PostGIS 3 libs will end in postgis-3
. This was done to make pg_upgrade easier, with downside that you can only install one version PostGIS 3 series in your server. To get the old behavior of file including the minor version: e.g. postgis-3.0
add this switch to your configure statement.
PostGISライブラリとSQLスクリプトのインストール先を指定します。デフォルトでは、検出されたPostgreSQLのインストール先と同じになります。
![]() | |
このパラメータは現在のところ壊れていて、PostgreSQLのインストール先にしかインストールされません。このバグのトラックについてはhttp://trac.osgeo.org/postgis/ticket/635をご覧ください。 |
PostgreSQLは、PostGISなどの拡張に対してPostgreSQLのインストール先ディレクトリを伝えるpg_configというユーティリティを持っています。PostGISの対象とする特定のPostgreSQLのインストール先を手動で指定する場合に、このパラメータ(--with-pgconfig=/path/to/pg_config)を使います。
必須ライブラリであるGDALは、ラスタ機能に必要な機能を提供します。GDALには、インストール先ディレクトリをインストールスクリプトに伝えるgdal-configがあります。PostGISのビルドに使う特定のGDALを手動で指定する場合に、このパラメータ (--with-gdalconfig=/path/to/gdal-config)を使います。
必須のジオメトリライブラリであるGEOSには、ソフトウェアのインストール時にGEOSのインストール先ディレクトリを伝えるgeos-configというユーティリティがあります。PostGISのビルドに使う特定のGEOSを手動で指定する場合に、このパラメータ (--with-geosconfig=/path/to/geos-config)を使います。
LibXMLはGeomFromKML/GML処理を行うのに必須のライブラリです。通常はlibxmlをインストールしているなら発見されますが、発見できない場合や特定の版を使用したい場合は、xml2-config
を指定してインストールスクリプトにLibXMLのインストール先ディレクトリを伝えます。PostGISのビルドに使う特定のLibXMLを手動で指定する場合に、このパラメータ (
>--with-xml2config=/path/to/xml2-config)を使います。
Proj4はPostGISに必須の投影変換ライブラリです。PostGISのビルドに使う特定のProj4のディレクトリを手動で指定する場合は、このパラメータ (--with-projdir=/path/to/projdir)を使います。
iconvのインストール先ディレクトリを指定します。
JSON-Cは、MITライセンスのJSONライブラリで、PostGISのST_GeomFromJSONに必須です。PostGISのビルドに使う特定のJSON-Cを手動で指定する場合に、このパラメータ (--with-jsondir=/path/to/jsondir)を使います。
PCREは、BSDライセンスのPerl互換正規表現ライブラリです。住所標準化エクステンションに必須です。PostGISのビルド対象としている特定のPCREを手動で指定する場合に、このパラメータ (--with-pcredir=/path/to/pcredir)を使います。
データインポートGUI (GTK+2.0が必要)をコンパイルします。このパラメータによって、shp2pgsql-guiという、shp2pgsqlのグラフィカルユーザインタフェースが作成されます。
ラスタ機能をインストールします。
トポロジ対応を無くしてコンパイルします。トポロジに必要なロジックは全てpostgis-3.2.0rc1ライブラリ内に作られるので、関連ライブラリはありません。
デフォルトでは、gettextの検出とこれを用いたコンパイルを試みますが、ローダ破損を引き起こす非互換性問題のもとで実行する場合には、このコマンドで無効にできます。これを使ったコンフィギュレーションによって解決する問題の例はhttp://trac.osgeo.org/postgis/ticket/748にあります。ご注意: これを切ることで多くの機能がなくなるわけではありません。まだ文書化されていなくて試験段階であるGUIローダにおける内部のヘルプ/ラベル機能に使われています。
デフォルトでは、このスイッチなしではSFCGAL対応でインストールされません。PATH
は、sfcgal-configへのパスを指定することができる追加的な引数です。
Disable updating postgis_revision.h to match current HEAD of the git repository.
![]() | |
PostGISをSVNレポジトリから得る場合には、はじめに次のスクリプトを実行します。 ./autogen.sh このスクリプトによってconfigureスクリプトが生成されます。これはPostGISのインストールに関するカスタマイズに使われます。 PostGISをアーカイブファイルで入手する場合には、configureが既に生成されているので./autogen.shは不要です。 |
Makefileが生成されたら、PostGISのビルドは、次のコマンドを実行するだけです。
make
出力の最後の行に"PostGIS was built successfully. Ready to install.
"と出れば終わりです。
PostGIS 1.4.0版からは、全ての関数に文書から生成されるコメントが付きます。これらのコメントを後からインストールするには、次のコマンドを実行しますが、docbookが必要です。アーカイブファイルからインストールする場合は、postgis_comments.sql, raster_comments.sql, topology_comments.sqlは、docフォルダにあるので、コメントを作成する必要はありません。コメントはCREATE EXTENSIONによるインストールの一部として取り込まれます。
make comments
PostGIS 2.0で導入されました。早見表に、または学習中の方のハンドアウトに適しているHTMLチートシートを生成します。xsltprocが必要で、topology_cheatsheet.html
, tiger_geocoder_cheatsheet.html
, raster_cheatsheet.html
, postgis_cheatsheet.html
の4ファイルが生成されます。
HTMLとPDFのビルド済みのものはPostGIS / PostgreSQL Study Guidesにあります。
make cheatsheets
PostgreSQL 9.1以上を使用している場合は、PostGISエクステンションが自動的にビルド、インストールされます。
ソースレポジトリからビルドしている場合は、関数の記述を最初にビルドする必要があります。これらは、docbookがインストールされている時にビルドされます。手動でインストールするには次のようにします。
make comments
アーカイブファイルからのビルドの場合は、ビルド済みのものがあるので、コメントのビルドは必須ではありません。
PostgreSQL 9.1を対象にビルドしている場合は、extensionsは自動的にmake install処理の一部としてビルドするべきです。必要ならextensionsフォルダからビルドできますし、他のサーバで必要ならファイルの複製ができます。
cd extensions cd postgis make clean make export PGUSER=postgres #overwrite psql variables make check #to test before install make install # to test extensions make check RUNTESTFLAGS=--extension
![]() | |
|
エクステンションファイルは、OSに関係なく、常に同じ版のPostGISと同じです。PostGISバイナリを既にインストールしている限りは、エクステンションファイルをあるOSから別のものに複写して大丈夫です。
開発用と異なる別のサーバでエクステンションを手動でインストールしたい場合は、サーバにない時に必要となる通常のPostGISのバイナリだけでなく、次のファイルをextensionsフォルダからPostgreSQLインストール先のPostgreSQL / share / extension
フォルダに複写します。
指定されていない場合のインストールするエクステンションの版等の情報を示す制御ファイpostgis.control, postgis_topology.control
。
エクステンションごとの/sqlフォルダにあるファイル全て。extensions/postgis/sql/*.sql
, extensions/postgis_topology/sql/*.sql
はPostgreSQL share/extensionフォルダの最上位に複写する必要があることに注意して下さい。
以上を実行すると、PgAdmin -> extensionでpostgis
, postgis_topology
が有効なエクステンションとして見えます。
psqlを使う場合は、次のクエリを実行してエクステンションがインストールされていることを確認できます。
SELECT name, default_version,installed_version FROM pg_available_extensions WHERE name LIKE 'postgis%' or name LIKE 'address%'; name | default_version | installed_version ------------------------------+-----------------+------------------- address_standardizer | 3.2.0rc1 | 3.2.0rc1 address_standardizer_data_us | 3.2.0rc1 | 3.2.0rc1 postgis | 3.2.0rc1 | 3.2.0rc1 postgis_sfcgal | 3.2.0rc1 | postgis_tiger_geocoder | 3.2.0rc1 | 3.2.0rc1 postgis_topology | 3.2.0rc1 | (6 rows)
クエリを行ったデータベースにエクステンションがインストールされている場合は、installed_version
カラムに記載が見えます。レコードが返ってこない場合は、PostGIS EXTENSIONがインストールされていないことになります。PgAdmin III 1.14以上では、データベースブラウザツリーのextensions
セクションで提供されていて、右クリックでアップグレードまたアンインストールできます。
有効なエクステンションがある場合、pgAdminエクステンションインタフェースまたは次のSQLの実行によって、選択したデータベースにPostGISエクステンションをインストールできます。
CREATE EXTENSION postgis; CREATE EXTENSION postgis_sfcgal; CREATE EXTENSION fuzzystrmatch; -- postgis_tiger_geocoderに必要 -- postgis_tiger_geocoderで使用されるか単独で使われます CREATE EXTENSION address_standardizer; CREATE EXTENSION address_standardizer_data_us; CREATE EXTENSION postgis_tiger_geocoder; CREATE EXTENSION postgis_topology;
psqlでは、どの版が、どのスキーマにインストールされているかを見ることができます。
\connect mygisdb \x \dx postgis*
List of installed extensions -[ RECORD 1 ]------------------------------------------------- - Name | postgis Version | 3.2.0rc1 Schema | public Description | PostGIS geometry, geography, and raster spat.. -[ RECORD 2 ]------------------------------------------------- - Name | postgis_tiger_geocoder Version | 3.2.0rc1 Schema | tiger Description | PostGIS tiger geocoder and reverse geocoder -[ RECORD 3 ]------------------------------------------------- - Name | postgis_topology Version | 3.2.0rc1 Schema | topology Description | PostGIS topology spatial types and functions
![]() | |
エクステンションのテーブル |
この素晴らしいエクステンション機能を使わずに3.2.0rc1をインストールした場合でもエクステンションベースに変更することができます。まずpostgis_upgrade_22_minor.sql
,raster_upgrade_22_minor.sql
,topology_upgrade_22_minor.sql
のアップグレードスクリプトを実行して最新版にアップグレードします
CREATE EXTENSION postgis FROM unpackaged; CREATE EXTENSION postgis_topology FROM unpackaged; CREATE EXTENSION postgis_tiger_geocoder FROM unpackaged;
PostGISのテストを行うには、次のコマンドを実行します。
make check
このコマンドで、実際のPostgreSQLデータベースに対して生成したライブラリを使用した、様々なチェックとレグレッションテストを行います。
![]() | |
PostgreSQL, GEOS または Proj4 を標準の位置にインストールしていない場合には、環境変数LD_LIBRARY_PATHに、ライブラリの位置を追加する必要があるかも知れません。 |
![]() | |
現在のところmake checkは、チェックを行う際に 環境変数 |
If successful, make check will produce the output of almost 500 tests. The results will look similar to the following (numerous lines omitted below):
CUnit - A unit testing framework for C - Version 2.1-3 http://cunit.sourceforge.net/ . . . Run Summary: Type Total Ran Passed Failed Inactive suites 44 44 n/a 0 0 tests 300 300 300 0 0 asserts 4215 4215 4215 0 n/a Elapsed time = 0.229 seconds . . . Running tests . . . Run tests: 134 Failed: 0 -- if you build with SFCGAL . . . Running tests . . . Run tests: 13 Failed: 0 -- if you built with raster support . . . Run Summary: Type Total Ran Passed Failed Inactive suites 12 12 n/a 0 0 tests 65 65 65 0 0 asserts 45896 45896 45896 0 n/a . . . Running tests . . . Run tests: 101 Failed: 0 -- topology regress . . . Running tests . . . Run tests: 51 Failed: 0 -- if you built --with-gui, you should see this too CUnit - A unit testing framework for C - Version 2.1-2 http://cunit.sourceforge.net/ . . . Run Summary: Type Total Ran Passed Failed Inactive suites 2 2 n/a 0 0 tests 4 4 4 0 0 asserts 4 4 4 0 n/a
postgis_tiger_geocoder
とaddress_standardizer
は、現在は、標準的なPostgreSQLインストールチェックにのみ対応しています。これらをテストするには、次のようにします。ご注意: PostGISコードフォルダのルートでmake installを既に行っている場合には、make installは重要ではありません。
address_standardizer用:
cd extensions/address_standardizer make install make installcheck
出力は次のようなかんじになります。
============== dropping database "contrib_regression" ============== DROP DATABASE ============== creating database "contrib_regression" ============== CREATE DATABASE ALTER DATABASE ============== running regression test queries ============== test test-init-extensions ... ok test test-parseaddress ... ok test test-standardize_address_1 ... ok test test-standardize_address_2 ... ok ===================== All 4 tests passed. =====================
Tiger Geocodeを使う場合には、使用するPostgreSQLインスタンス内にPostGISとfuzzystrmatchのエクステンションが必要です。PostGISをaddress_standardizer機能付きでビルドした場合は、address_standardizerのテストも行います。
cd extensions/postgis_tiger_geocoder make install make installcheck
出力は次のようなかんじになります。
============== dropping database "contrib_regression" ============== DROP DATABASE ============== creating database "contrib_regression" ============== CREATE DATABASE ALTER DATABASE ============== installing fuzzystrmatch ============== CREATE EXTENSION ============== installing postgis ============== CREATE EXTENSION ============== installing postgis_tiger_geocoder ============== CREATE EXTENSION ============== installing address_standardizer ============== CREATE EXTENSION ============== running regression test queries ============== test test-normalize_address ... ok test test-pagc_normalize_address ... ok ===================== All 2 tests passed. =====================
PostGISをインストールするには、次のコマンドを実行します。
make install
これにより、PostGISのインストールファイルが、--prefixパラメータで指定した、適切なサブディレクトリに複写されます。次に特筆すべきサブディレクトリを示します。
ローダとダンパのバイナリのインストール先は[prefix]/bin
です。
postgis.sql
などのSQLファイルのインストール先は[prefix]/share/contrib
です。
PostGISライブラリのインストール先は[prefix]/lib
です。
先にmake commentsを実行してpostgis_comments.sql
, raster_comments.sql
を生成していた場合は、次のコマンドを実行すると、これらのSQLファイルがインストールされます。
make comments-install
![]() | |
|
address_standardizer
エクステンションは、別途ダウンロードする必要がある別パッケージとしていました。PostGIS 2.2からは同梱されています。address_standardizeの追加情報、できること、および、コンフィギュレーション方法については、Section 14.1, “住所標準化”をご覧下さい。
標準化エクステンションは、Normalize_Addressの後継で、PostGISに入っているTigerジオコーダエクステンションに使うことができます。この場合の使い方についてはSection 2.4.3, “TigerジオコーダをPostGISデータベースで有効にする: エクステンションを使用”を参照して下さい。また、ユーザ自身がつくるジオコーダの要素として使用したり、住所の比較を簡単にするために住所を標準化するために使うことができます。
住所標準化エクステンションはPCREに依存しています。PCREは多くのUNIX系システムにインストールされていますが、http://www.pcre.orgから最新版をダウンロードできます。Section 2.2.3, “コンフィギュレーション”の際にPCREを発見すると、住所標準化エクステンションが自動的にビルドされます。使用したいPCREのインストールが独自なものである場合は、configureに--with-pcredir=/path/to/pcre
を渡します。/path/to/pcre
は、PCREのincludeとlibのあるルートフォルダです。
Windowsでは、PostGIS 2.1以上に住所標準化エクステンションが同梱されているので、コンパイルを行わずに、すぐにCREATE EXTENSION
に行くことができます。
インストールしたら、対象データベースに接続して次のSQLが実行できます。
CREATE EXTENSION address_standardizer;
次のテストでは、rules, gaz, lexテーブルは必要ありません。
SELECT num, street, city, state, zip FROM parse_address('1 Devonshire Place PH301, Boston, MA 02109');
出力は次のようになります。
num | street | city | state | zip -----+------------------------+--------+-------+------- 1 | Devonshire Place PH301 | Boston | MA | 02109
PerlのRegex::Assembleは、ソースツリーの一部がこれで作られていますが、住所標準化エクステンションではもはや不要です。ただし、usps-st-city-orig.txt
またはusps-st-city-orig.txt usps-st-city-adds.tx
を編集する必要がある場合は、parseaddress-stcities.h
のリビルドでRegex:Assembleが必要です。
cpan Regexp::Assemble
Ubuntu / Degianの場合には、次のようにしなければならないかも知れません。
sudo perl -MCPAN -e "install Regexp::Assemble"
Tigerジオコーダのような拡張機能はPostGISディストリビューションに同梱されていません。Tigerジオコーダエクステンションが無かったり、インストールしているものより新しい版のものが欲しい場合には、Windows Unreleased Versions節でPostgreSQLの版に合ったパッケージにあるshare/extension/postgis_tiger_geocoder.*
ファイルを使います。これらのパッケージはWindows用ですが、postgis_tige_geocoderエクステンションファイルは、SQLとPL/pgSQLだけですので、他のOSでも動作します。
PostgreSQL 9.1以上とPostGIS 2.1.0を使用している場合は、Tigerジオコーダのインストールで、新しいエクステンションモデルの利点を得ることができます。次のようにします。
まず、通常の方法で、PostGIS 2.1.0のバイナリを取得するか、コンパイルしてインストールします。これにより重要なエクステンションファイルとTigerジオコーダのファイルがインストールされます。
psql、pgAdminまたは他のツールでデータベースに接続して、次のSQLコマンドを実行します。既にPostGISを持っているデータベースにインストールする場合は、一つ目の手順は不要です。fuzzystrmatch
エクステンションが既にインストールされている場合は、二つ目の手順は不要です。
CREATE EXTENSION postgis; CREATE EXTENSION fuzzystrmatch; CREATE EXTENSION postgis_tiger_geocoder; -- 規則を基にした住所標準化 (pagc_normalize_address)を使いたい場合の任意実行 CREATE EXTENSION address_standardizer;
既にpostgis_tiger_geocoderエクステンションをインストールしていて、最新版に更新するだけの場合には、次を実行します。
ALTER EXTENSION postgis UPDATE; ALTER EXTENSION postgis_tiger_geocoder UPDATE;
独自のエントリを生成した場合や、tiger.loader_platform
とtiger.loader_variables
に変更を加えた場合には、これらをアップデートしなければならないことがあります。
正しくインストールされたかを確認するために、インストール対象データベース内で次のSQLを実行します。
SELECT na.address, na.streetname,na.streettypeabbrev, na.zip FROM normalize_address('1 Devonshire Place, Boston, MA 02109') AS na;
出力は次のようになります。
address | streetname | streettypeabbrev | zip ---------+------------+------------------+------- 1 | Devonshire | Pl | 02109
tiger.loader_platform
テーブルの、実行ファイルやサーバのパスを持つ新しいレコードを生成します。
sh
コンベンションのあとにdebbieというプロファイルを生成する例として、次のコマンドを実行します。
INSERT INTO tiger.loader_platform(os, declare_sect, pgbin, wget, unzip_command, psql, path_sep, loader, environ_set_command, county_process_command) SELECT 'debbie', declare_sect, pgbin, wget, unzip_command, psql, path_sep, loader, environ_set_command, county_process_command FROM tiger.loader_platform WHERE os = 'sh';
それから、declare_sectカラム内のパスを編集して、Debbieのpg, unzip, shp2pgsql, psql他のパス位置に適応するようにします。
loader_platform
テーブルを編集しない場合は、一般的なアイテムの位置を持っているので、スクリプトが生成された後で、スクリプトを編集しなければなりません。
PostGIS 2.4.1からは、ZTCA5
(Zip Code 5 digit Tabulation Area)のロード手順が変更され、有効になった時にLoader_Generate_Nation_Scriptの一部として現在のZCTA5データをロードするようになりました。デフォルトでは切られています。ロードにかなりの時間 (20から60分)が取られ、かなりのディスクスペースを占有するのに、そんなに頻繁には使わないためです。
有効にするには、次のようにします。
UPDATE tiger.loader_lookuptables SET load = true WHERE table_name = 'zcta510';
境界のフィルタが追加され、ちょうど境界内のZIPに制限された場合に、Geocode関数は、ZCTA5が存在するなら使います。Reverse_Geocode関数は、返された住所にZIPコードが無い場合に (しばしば高速道路での逆ジオコーディングで発生します)、これを使います。
サーバまたはローカル (サーバへのネットワーク接続が早い場合)のルートにgisdata
というフォルダを作成します。このフォルダはTigerファイルがダウンロードされ、処理される場所です。サーバのルートにフォルダを作ると不幸になる場合や、単に他のフォルダに移したい場合には、tiger.loader_variables
テーブルのstaging_fold
フィールドを編集します。
gisdata
フォルダ内にtempというフォルダを作成します。もしくは、staging_fold
で示されたフォルダを作成します。ローダがダウンロードしたTigerデータを展開する場所です。
そして、SQL関数Loader_Generate_Nation_Scriptを実行して、独自のプロファイルの名前を使うか確認し、.shまたは.batファイルにスクリプトを複写します。たとえば、新しいプロファイルで国のロードを行う場合には、次のようにします。
psql -c "SELECT Loader_Generate_Nation_Script('debbie')" -d geocoder -tA > /gisdata/nation_script_load.sh
生成された国データをロードするコマンドラインスクリプトを実行します。
cd /gisdata sh nation_script_load.sh
国スクリプトを実行した後、tiger_data
スキーマに三つのテーブルが作られ、データが格納されています。次のクエリをpsqlかpgAdminから実行して、確認します。
SELECT count(*) FROM tiger_data.county_all;
count ------- 3233 (1 row)
SELECT count(*) FROM tiger_data.state_all;
count ------- 56 (1 row)
デフォルトではbg
, tract
, tabblock
に対応するテーブルはロードされません。ジオコーダはこれらのテーブルを使いませんが、一般に、人口統計に使います。州データのロードの一部としてロードするには、次の手続きを実行して有効にします。
UPDATE tiger.loader_lookuptables SET load = true WHERE load = false AND lookup_name IN('tract', 'bg', 'tabblock');
もしくは、Loader_Generate_Census_Scriptを使って州のデータをロードした後に、これらのテーブルだけをロードできます。
データをロードしたい州ごとに、Loader_Generate_Scriptで州スクリプトを作ります。
![]() | |
国データのロードを完了する前に*州スクリプトを作ってはなりません*。州スクリプトは国スクリプトでロードされる国リストを利用するためです。 |
psql -c "SELECT Loader_Generate_Script(ARRAY['MA'], 'debbie')" -d geocoder -tA > /gisdata/ma_load.sh
生成されたコマンドラインスクリプトを実行します。
cd /gisdata sh ma_load.sh
全てのデータのロードが完了するか中断ポイントに達した後に、全てのtigerテーブルに対してanalyzeを実行して、(継承されたものも含めて)状態を更新するのは良いことです。
SELECT install_missing_indexes(); vacuum analyze verbose tiger.addr; vacuum analyze verbose tiger.edges; vacuum analyze verbose tiger.faces; vacuum analyze verbose tiger.featnames; vacuum analyze verbose tiger.place; vacuum analyze verbose tiger.cousub; vacuum analyze verbose tiger.county; vacuum analyze verbose tiger.state; vacuum analyze verbose tiger.zip_lookup_base; vacuum analyze verbose tiger.zip_state; vacuum analyze verbose tiger.zip_state_loc;
エクステンションモデルを使わずにTigerジオコーダをインストールしている場合に、次のようにして、エクステンションモデルに変換できます。
Section 2.4.5, “Tigerジオコーダのアップグレード”の指示に従って非エクステンションモデルのアップグレードを行います。
psqlまたはpgAdminでデータベースに接続して、次のコマンドを実行します。
CREATE EXTENSION postgis_tiger_geocoder FROM unpackaged;
まず、上述の手順でPostGISをインストールします。
extrasフォルダが無い場合、http://download.osgeo.org/postgis/source/postgis-3.2.0rc1.tar.gzをダウンロードします。
tar xvfz postgis-3.2.0rc1.tar.gz
cd postgis-3.2.0rc1/extras/tiger_geocoder
tiger_loader_2015.sql
(違う年のものをロードしたくないならば最新のローダファイル)をあなたの実行サーバ等のパスに編集します。もしくはloader_platform
がインストールされた後に一度これを更新します。このファイルもloader_platform
も編集しない場合には、一般的なアイテムの位置を持っているだけなので、Loader_Generate_Nation_ScriptとLoader_Generate_Scriptを実行した後に、生成されたスクリプトを編集しなければなりません。
初めてTigerジオコーダをインストールする場合は、Windowsではcreate_geocode.bat
を、またLinux/Unix/Mac OSXではcreate_geocode.sh
を、使用するPostgreSQLにとって独自の設定に変更したうえで、コマンドラインから対応するスクリプトを実行します。
データベースにtiger
スキーマがあることを確認します。もし無い場合は、次の行を参考に、コマンドを実行します。
ALTER DATABASE geocoder SET search_path=public, tiger;
住所正規化機能は、トリッキーな住所を除いて、大体データなしで動作します。テストを実行して次のように見えることを確認して下さい。
SELECT pprint_addy(normalize_address('202 East Fremont Street, Las Vegas, Nevada 89101')) As pretty_address; pretty_address --------------------------------------- 202 E Fremont St, Las Vegas, NV 89101
皆さんが問題と思われるの多くのことのひとつに、ジオコーディング前の準備に住所を正規化する関数Normalize_Addressがあります。住所正規化は万全と言うにはほど遠く、パッチをあてようとすると膨大な資源を費やします。よって、より良い住所標準化エンジンを持つ他のプロジェクトに統合しました。この新しい住所標準化を使うには、Section 2.3, “PAGC住所標準化ツールのインストールと使用”で記述するようにエクステンションをコンパイルし、使用するデータベースにインストールします。
このエクステンションをpostgis_tiger_geocoder
をインストールしているデータベースにインストールすると、Pagc_Normalize_Address文字列のストリート住所を与えると、道路後置辞、前置辞、標準タイプ、番地、ストリート名等を複数フィールドに分解して持つnorm_addy
複合型を返します。この関数は、tiger_geocoder同梱のルックアップテーブルだけを使います (Tigerデータは不要です)。住所標準化エクステンションが必要です。を、Normalize_Addressの代わりに使うことができます。このエクステンションはTigerジオコーダからは見えないので、国際的な住所といった他のデータソースでも使えます。Tigerジオコーダエクステンションは、その版の規則テーブル (tiger.pagc_rules
), gaz table (tiger.pagc_gaz
), lexテーブル (tiger.pagc_lex
)を同梱しています。これらは、必要に応じて標準化の改善のために追加や更新ができます。
データロードの説明の詳細はextras/tiger_geocoder/tiger_2011/README
にあります。これは一般的な手順を示しています。
ロードプロセスによって、米センサスウェブサイトから個々の国ファイル、リクエストされた州のデータをダウンロードし、ファイルを展開し、個別の州をそれぞれの州テーブルの集合にロードします。各州のテーブルは、tiger
スキーマで定義されたテーブルを継承しているので、これらのテーブルに対して全てのデータにアクセスするためのクエリを出すことができますし、州の再読み込みが必要となったり、州が必要ない場合には、Drop_State_Tables_Generate_Scriptで、いつでも州テーブルの集合を削除するクエリを出すことができます。
データのロードを可能にするためには次のツールが必要です。
センサスウェブサイトから取得するZIPファイルを展開するツール。
Unix系システムでは、unzip
実行ファイルです。通常は、ほとんどのUnix系プラットフォームで既にインストールされています。
Windowsでは7-zipです。http://www.7-zip.org/からダウンロードできる無償の圧縮解答ツールです。
shp2pgsql
コマンド。PostGISインストール時にデフォルトでインストールされます。
wget
コマンド。通常はほとんどのUnix/Linuxシステムにインストールされている、ウェブ取得ツールです。
Windows用については、コンパイル済みのバイナリをhttp://gnuwin32.sourceforge.net/packages/wget.htmから取得できます。
tiger_2010からアップグレードする場合には、最初にDrop_Nation_Tables_Generate_Scriptを生成、実行する必要があります。州データをロードする前に、Loader_Generate_Nation_Scriptで国データをロードする必要があります。これによって、環境に合ったローダスクリプトが生成されます。Loader_Generate_Nation_Scriptは、一度の操作で、(2010からの)アップグレードと、新しいインストールが行われます。
州データをロードするには、Loader_Generate_Scriptを参照して、手持ちのプラットフォームで動作する、求める州データをロードするデータロードスクリプトを生成します。州データはひとつずつダウンロードできることに注意して下さい。一度に必要な州の全てについてデータをロードする必要はありません。必要なだけダウンロードできます。
求める州データをロードした後は、Install_Missing_Indexesに示すように、
SELECT install_missing_indexes();
を実行するようにして下さい。
行うべきことができたかをテストするために、Geocodeを使用する州の中の住所についてジオコーダを実行してみます。
2.0以上に含まれるTigerジオコーダがインストールされている場合には、どうしても必要な訂正があるときは、いつでも臨時のアーカイブファイルからでも機能のアップグレードができます。 これは、エクステンションでインストールされていないTigerジオコーダで動作します。
extrasフォルダが無い場合、http://download.osgeo.org/postgis/source/postgis-3.2.0rc1.tar.gzをダウンロードします。
tar xvfz postgis-3.2.0rc1.tar.gz
cd postgis-3.2.0rc1/extras/tiger_geocoder/tiger_2011
Windowsの場合はupgrade_geocoder.bat
スクリプト、Linux/Unix/MacOS Xの場合はupgrade_geocoder.sh
スクリプトの位置を特定します。 PostGISデータベースの資格情報を持つように編集します。
2010または2011からアップグレードする場合には、確実にローダスクリプトのコメントアウトを消すと、2012データのロードのための最新のスクリプトを得ます。
対応するスクリプトをコマンドラインから実行します。
次に、全ての国テーブルを削除し、新しい国テーブルをロードします。Drop_Nation_Tables_Generate_Scriptに詳細がある通り、このSQLステートメントを使った削除スクリプトを生成します。
SELECT drop_nation_tables_generate_script();
生成した削除SQLステートメントを実行します。
Loader_Generate_Nation_Scriptに詳細がある通り、このSELECTステートメントを使った削除スクリプトを生成します。
Windows向け
SELECT loader_generate_nation_script('windows');
Unix/Linux向け
SELECT loader_generate_nation_script('sh');
生成したスクリプトの実行方法に関する説明は、Section 2.4.4, “Tigerデータのロード”を参照して下さい。これは一度だけ実行する必要があります。
![]() | |
2010/2011州テーブルを混在させることができ、それぞれの州について個別にアップグレードできます。2011にアップグレードする前に、まず、Drop_State_Tables_Generate_Scriptを使って、2010州テーブルを削除します。 |
インストールやアップグレードが思うようにいかない時にチェックすることがいくつかあります。
PostgreSQL 9.6以上をインストールしているか、実行中のPostgreSQLと同じ版のソースでコンパイルしているか、をチェックします。(Linuxの)ディストリビューションによって既にPostgreSQLがインストールされている時や、 PostgreSQLを以前にインストールして忘れた場合に、 混乱が発生することがあります。PostGISはPostgreSQL 9.6以上で動作します。古い版のものを使った場合には、おかしな予想外のエラーメッセージが表示されます。実行中のPostgreSQLの版をチェックするには、psqlを使ってデータベースを接続して、次のクエリを実行して下さい。
SELECT version();
RPMベースのディストリビューションを実行している場合、 プリインストールされたパッケージが存在するかのチェックは、rpm コマンドを使ってrpm -qa | grep postgresqlでチェックできます。
アップグレードに失敗する場合、既にPostGISがインストールされているデータベースにリストアしているか確認して下さい。
SELECT postgis_full_version();
また、コンフィギュアが正しくPostgreSQL、Proj4ライブラリ、GEOSライブラリのインストール先を検出したかチェックして下さい。
コンフィギュアからの出力でpostgis_config.h
ファイルが作られます。POSTGIS_PGSQL_VERSION
、POSTGIS_PROJ_VERSION
およびPOSTGIS_GEOS_VERSION
変数が正しくセットされたかをチェックして下さい。
Tuning for PostGIS performance is much like tuning for any PostgreSQL workload. The only additional consideration is that geometries and rasters are usually large, so memory-related optimizations generally have more of an impact on PostGIS than other types of PostgreSQL queries.
For general details about optimizing PostgreSQL, refer to Tuning your PostgreSQL Server.
For PostgreSQL 9.4+ configuration can be set at the server level without touching postgresql.conf
or postgresql.auto.conf
by using the ALTER SYSTEM
command.
ALTER SYSTEM SET work_mem = '256MB'; -- this forces non-startup configs to take effect for new connections SELECT pg_reload_conf(); -- show current setting value -- use SHOW ALL to see all settings SHOW work_mem;
In addition to the Postgres settings, PostGIS has some custom settings which are listed in Section 8.2, “PostGIS GUC (Grand Unified Custom)変数”.
These settings are configured in postgresql.conf
:
Default: partition
This is generally used for table partitioning. The default for this is set to "partition" which is ideal for PostgreSQL 8.4 and above since it will force the planner to only analyze tables for constraint consideration if they are in an inherited hierarchy and not pay the planner penalty otherwise.
Default: ~128MB in PostgreSQL 9.6
Set to about 25% to 40% of available RAM. On windows you may not be able to set as high.
max_worker_processes This setting is only available for PostgreSQL 9.4+. For PostgreSQL 9.6+ this setting has additional importance in that it controls the max number of processes you can have for parallel queries.
Default: 8
Sets the maximum number of background processes that the system can support. This parameter can only be set at server start.
work_mem - sets the size of memory used for sort operations and complex queries
Default: 1-4MB
Adjust up for large dbs, complex queries, lots of RAM
Adjust down for many concurrent users or low RAM.
If you have lots of RAM and few developers:
SET work_mem TO '256MB';
maintenance_work_mem - the memory size used for VACUUM, CREATE INDEX, etc.
Default: 16-64MB
Generally too low - ties up I/O, locks objects while swapping memory
Recommend 32MB to 1GB on production servers w/lots of RAM, but depends on the # of concurrent users. If you have lots of RAM and few developers:
SET maintenance_work_mem TO '1GB';
max_parallel_workers_per_gather
This setting is only available for PostgreSQL 9.6+ and will only affect PostGIS 2.3+, since only PostGIS 2.3+ supports parallel queries. If set to higher than 0, then some queries such as those involving relation functions like ST_Intersects
can use multiple processes and can run more than twice as fast when doing so. If you have a lot of processors to spare, you should change the value of this to as many processors as you have. Also make sure to bump up max_worker_processes
to at least as high as this number.
Default: 0
Sets the maximum number of workers that can be started by a single Gather
node. Parallel workers are taken from the pool of processes established by max_worker_processes
. Note that the requested number of workers may not actually be available at run time. If this occurs, the plan will run with fewer workers than expected, which may be inefficient. Setting this value to 0, which is the default, disables parallel query execution.
If you enabled raster support you may want to read below how to properly configure it.
As of PostGIS 2.1.3, out-of-db rasters and all raster drivers are disabled by default. In order to re-enable these, you need to set the following environment variables POSTGIS_GDAL_ENABLED_DRIVERS
and POSTGIS_ENABLE_OUTDB_RASTERS
in the server environment. For PostGIS 2.2, you can use the more cross-platform approach of setting the corresponding Section 8.2, “PostGIS GUC (Grand Unified Custom)変数”.
If you want to enable offline raster:
POSTGIS_ENABLE_OUTDB_RASTERS=1
Any other setting or no setting at all will disable out of db rasters.
In order to enable all GDAL drivers available in your GDAL install, set this environment variable as follows
POSTGIS_GDAL_ENABLED_DRIVERS=ENABLE_ALL
If you want to only enable specific drivers, set your environment variable as follows:
POSTGIS_GDAL_ENABLED_DRIVERS="GTiff PNG JPEG GIF XYZ"
![]() | |
If you are on windows, do not quote the driver list |
Setting environment variables varies depending on OS. For PostgreSQL installed on Ubuntu or Debian via apt-postgresql, the preferred way is to edit /etc/postgresql/
where 10 refers to version of PostgreSQL and main refers to the cluster.10
/main
/environment
On windows, if you are running as a service, you can set via System variables which for Windows 7 you can get to by right-clicking on Computer->Properties Advanced System Settings or in explorer navigating to Control Panel\All Control Panel Items\System
. Then clicking Advanced System Settings ->Advanced->Environment Variables and adding new system variables.
After you set the environment variables, you'll need to restart your PostgreSQL service for the changes to take effect.
If you are using PostgreSQL 9.1+ and have compiled and installed the extensions/postgis modules, you can turn a database into a spatial one using the EXTENSION mechanism.
Core postgis extension includes geometry, geography, spatial_ref_sys and all the functions and comments. Raster and topology are packaged as a separate extension.
Run the following SQL snippet in the database you want to enable spatially:
CREATE EXTENSION IF NOT EXISTS plpgsql; CREATE EXTENSION postgis; CREATE EXTENSION postgis_raster; -- OPTIONAL CREATE EXTENSION postgis_topology; -- OPTIONAL
![]() | |
This is generally only needed if you cannot or don't want to get PostGIS installed in the PostgreSQL extension directory (for example during testing, development or in a restricted environment). |
Adding PostGIS objects and function definitions into your database is done by loading the various sql files located in [prefix]/share/contrib
as specified during the build phase.
The core PostGIS objects (geometry and geography types, and their support functions) are in the postgis.sql
script. Raster objects are in the rtpostgis.sql
script. Topology objects are in the topology.sql
script.
For a complete set of EPSG coordinate system definition identifiers, you can also load the spatial_ref_sys.sql
definitions file and populate the spatial_ref_sys
table. This will permit you to perform ST_Transform() operations on geometries.
If you wish to add comments to the PostGIS functions, you can find them in the postgis_comments.sql
script. Comments can be viewed by simply typing \dd [function_name] from a psql terminal window.
Run the following Shell commands in your terminal:
DB=[yourdatabase] SCRIPTSDIR=`pg_config --sharedir`/contrib/postgis-3.1/ # Core objects psql -d ${DB} -f ${SCRIPTSDIR}/postgis.sql psql -d ${DB} -f ${SCRIPTSDIR}/spatial_ref_sys.sql psql -d ${DB} -f ${SCRIPTSDIR}/postgis_comments.sql # OPTIONAL # Raster support (OPTIONAL) psql -d ${DB} -f ${SCRIPTSDIR}/rtpostgis.sql psql -d ${DB} -f ${SCRIPTSDIR}/raster_comments.sql # OPTIONAL # Topology support (OPTIONAL) psql -d ${DB} -f ${SCRIPTSDIR}/topology.sql psql -d ${DB} -f ${SCRIPTSDIR}/topology_comments.sql # OPTIONAL
Some packaged distributions of PostGIS (in particular the Win32 installers for PostGIS >= 1.1.5) load the PostGIS functions into a template database called template_postgis
. If the template_postgis
database exists in your PostgreSQL installation then it is possible for users and/or applications to create spatially-enabled databases using a single command. Note that in both cases, the database user must have been granted the privilege to create new databases.
From the shell:
# createdb -T template_postgis my_spatial_db
From SQL:
postgres=# CREATE DATABASE my_spatial_db TEMPLATE=template_postgis
Upgrading existing spatial databases can be tricky as it requires replacement or introduction of new PostGIS object definitions.
Unfortunately not all definitions can be easily replaced in a live database, so sometimes your best bet is a dump/reload process.
PostGIS provides a SOFT UPGRADE procedure for minor or bugfix releases, and a HARD UPGRADE procedure for major releases.
Before attempting to upgrade PostGIS, it is always worth to backup your data. If you use the -Fc flag to pg_dump you will always be able to restore the dump with a HARD UPGRADE.
If you installed your database using extensions, you'll need to upgrade using the extension model as well. If you installed using the old sql script way, then you should upgrade using the sql script way. Please refer to the appropriate.
This section applies only to those who installed PostGIS not using extensions. If you have extensions and try to upgrade with this approach you'll get messages like:
can't drop ... because postgis extension depends on it
NOTE: if you are moving from PostGIS 1.* to PostGIS 2.* or from PostGIS 2.* prior to r7409, you cannot use this procedure but would rather need to do a HARD UPGRADE.
After compiling and installing (make install) you should find a set of *_upgrade.sql
files in the installation folders. You can list them all with:
ls `pg_config --sharedir`/contrib/postgis-3.2.0rc1/*_upgrade.sql
Load them all in turn, starting from postgis_upgrade.sql
.
psql -f postgis_upgrade.sql -d your_spatial_database
The same procedure applies to raster, topology and sfcgal extensions, with upgrade files named rtpostgis_upgrade.sql
, topology_upgrade.sql
and sfcgal_upgrade.sql
respectively. If you need them:
psql -f rtpostgis_upgrade.sql -d your_spatial_database
psql -f topology_upgrade.sql -d your_spatial_database
psql -f sfcgal_upgrade.sql -d your_spatial_database
![]() | |
If you can't find the |
The ??? function should inform you about the need to run this kind of upgrade using a "procs need upgrade" message.
If you originally installed PostGIS with extensions, then you need to upgrade using extensions as well. Doing a minor upgrade with extensions, is fairly painless.
ALTER EXTENSION postgis UPDATE TO "3.2.0rc1"; ALTER EXTENSION postgis_topology UPDATE TO "3.2.0rc1";
If you get an error notice something like:
No migration path defined for ... to 3.2.0rc1
Then you'll need to backup your database, create a fresh one as described in Section 3.3.1, “Spatially enable database using EXTENSION” and then restore your backup on top of this new database.
If you get a notice message like:
Version "3.2.0rc1" of extension "postgis" is already installed
Then everything is already up to date and you can safely ignore it. UNLESS you're attempting to upgrade from an development version to the next (which doesn't get a new version number); in that case you can append "next" to the version string, and next time you'll need to drop the "next" suffix again:
ALTER EXTENSION postgis UPDATE TO "3.2.0rc1next"; ALTER EXTENSION postgis_topology UPDATE TO "3.2.0rc1next";
![]() | |
If you installed PostGIS originally without a version specified, you can often skip the reinstallation of postgis extension before restoring since the backup just has |
![]() | |
If you are upgrading PostGIS extension from a version prior to 3.0.0 you'll end up with an unpackaged PostGIS Raster support. You can repackage the raster support using: CREATE EXTENSION postgis_raster FROM unpackaged; And then, if you don't need it, drop it with: DROP EXTENSION postgis_raster;
|
By HARD UPGRADE we mean full dump/reload of postgis-enabled databases. You need a HARD UPGRADE when PostGIS objects' internal storage changes or when SOFT UPGRADE is not possible. The Release Notes appendix reports for each version whether you need a dump/reload (HARD UPGRADE) to upgrade.
The dump/reload process is assisted by the postgis_restore.pl script which takes care of skipping from the dump all definitions which belong to PostGIS (including old ones), allowing you to restore your schemas and data into a database with PostGIS installed without getting duplicate symbol errors or bringing forward deprecated objects.
Supplementary instructions for windows users are available at Windows Hard upgrade.
The Procedure is as follows:
Create a "custom-format" dump of the database you want to upgrade (let's call it olddb
) include binary blobs (-b) and verbose (-v) output. The user can be the owner of the db, need not be postgres super account.
pg_dump -h localhost -p 5432 -U postgres -Fc -b -v -f "/somepath/olddb.backup" olddb
Do a fresh install of PostGIS in a new database -- we'll refer to this database as newdb
. Please refer to Section 3.3.2, “Spatially enable database without using EXTENSION (discouraged)” and Section 3.3.1, “Spatially enable database using EXTENSION” for instructions on how to do this.
The spatial_ref_sys entries found in your dump will be restored, but they will not override existing ones in spatial_ref_sys. This is to ensure that fixes in the official set will be properly propagated to restored databases. If for any reason you really want your own overrides of standard entries just don't load the spatial_ref_sys.sql file when creating the new db.
If your database is really old or you know you've been using long deprecated functions in your views and functions, you might need to load legacy.sql
for all your functions and views etc. to properly come back. Only do this if _really_ needed. Consider upgrading your views and functions before dumping instead, if possible. The deprecated functions can be later removed by loading uninstall_legacy.sql
.
Restore your backup into your fresh newdb
database using postgis_restore.pl. Unexpected errors, if any, will be printed to the standard error stream by psql. Keep a log of those.
perl utils/postgis_restore.pl "/somepath/olddb.backup" | psql -h localhost -p 5432 -U postgres newdb 2> errors.txt
Errors may arise in the following cases:
Some of your views or functions make use of deprecated PostGIS objects. In order to fix this you may try loading legacy.sql
script prior to restore or you'll have to restore to a version of PostGIS which still contains those objects and try a migration again after porting your code. If the legacy.sql
way works for you, don't forget to fix your code to stop using deprecated functions and drop them loading uninstall_legacy.sql
.
Some custom records of spatial_ref_sys in dump file have an invalid SRID value. Valid SRID values are bigger than 0 and smaller than 999000. Values in the 999000.999999 range are reserved for internal use while values > 999999 can't be used at all. All your custom records with invalid SRIDs will be retained, with those > 999999 moved into the reserved range, but the spatial_ref_sys table would lose a check constraint guarding for that invariant to hold and possibly also its primary key ( when multiple invalid SRIDS get converted to the same reserved SRID value ).
In order to fix this you should copy your custom SRS to a SRID with a valid value (maybe in the 910000..910999 range), convert all your tables to the new srid (see UpdateGeometrySRID), delete the invalid entry from spatial_ref_sys and re-construct the check(s) with:
ALTER TABLE spatial_ref_sys ADD CONSTRAINT spatial_ref_sys_srid_check check (srid > 0 AND srid < 999000 );
ALTER TABLE spatial_ref_sys ADD PRIMARY KEY(srid));
If you are upgrading an old database containing french IGN cartography, you will have probably SRIDs out of range and you will see, when importing your database, issues like this :
WARNING: SRID 310642222 converted to 999175 (in reserved zone)
In this case, you can try following steps : first throw out completely the IGN from the sql which is resulting from postgis_restore.pl. So, after having run :
perl utils/postgis_restore.pl "/somepath/olddb.backup" > olddb.sql
run this command :
grep -v IGNF olddb.sql > olddb-without-IGN.sql
Create then your newdb, activate the required Postgis extensions, and insert properly the french system IGN with : this script After these operations, import your data :
psql -h localhost -p 5432 -U postgres -d newdb -f olddb-without-IGN.sql 2> errors.txt
The Open Geospatial Consortium (OGC) developed the Simple Features Access standard (SFA) to provide a model for geospatial data. It defines the fundamental spatial type of Geometry, along with operations which manipulate and transform geometry values to perform spatial analysis tasks. PostGIS implements the OGC Geometry model as the PostgreSQL data types geometry and geography.
Geometry is an abstract type. Geometry values belong to one of its concrete subtypes which represent various kinds and dimensions of geometric shapes. These include the atomic types Point, LineString, LinearRing and Polygon, and the collection types MultiPoint, MultiLineString, MultiPolygon and GeometryCollection. The Simple Features Access - Part 1: Common architecture v1.2.1 adds subtypes for the structures PolyhedralSurface, Triangle and TIN.
Geometry models shapes in the 2-dimensional Cartesian plane. The PolyhedralSurface, Triangle, and TIN types can also represent shapes in 3-dimensional space. The size and location of shapes are specified by their coordinates. Each coordinate has a X and Y ordinate value determining its location in the plane. Shapes are constructed from points or line segments, with points specified by a single coordinate, and line segments by two coordinates.
Coordinates may contain optional Z and M ordinate values. The Z ordinate is often used to represent elevation. The M ordinate contains a measure value, which may represent time or distance. If Z or M values are present in a geometry value, they must be defined for each point in the geometry. If a geometry has Z or M ordinates the coordinate dimension is 3D; if it has both Z and M the coordinate dimension is 4D.
Geometry values are associated with a spatial reference system indicating the coordinate system in which it is embedded. The spatial reference system is identified by the geometry SRID number. The units of the X and Y axes are determined by the spatial reference system. In planar reference systems the X and Y coordinates typically represent easting and northing, while in geodetic systems they represent longitude and latitude. SRID 0 represents an infinite Cartesian plane with no units assigned to its axes. See Section 4.5, “空間参照系”.
The geometry dimension is a property of geometry types. Point types have dimension 0, linear types have dimension 1, and polygonal types have dimension 2. Collections have the dimension of the maximum element dimension.
A geometry value may be empty. Empty values contain no vertices (for atomic geometry types) or no elements (for collections).
An important property of geometry values is their spatial extent or bounding box, which the OGC model calls envelope. This is the 2 or 3-dimensional box which encloses the coordinates of a geometry. It is an efficient way to represent a geometry's extent in coordinate space and to check whether two geometries interact.
The geometry model allows evaluating topological spatial relationships as described in Section 5.1.1, “Dimensionally Extended 9-Intersection Model”. To support this the concepts of interior, boundary and exterior are defined for each geometry type. Geometries are topologically closed, so they always contain their boundary. The boundary is a geometry of dimension one less than that of the geometry itself.
The OGC geometry model defines validity rules for each geometry type. These rules ensure that geometry values represents realistic situations (e.g. it is possible to specify a polygon with a hole lying outside the shell, but this makes no sense geometrically and is thus invalid). PostGIS also allows storing and manipulating invalid geometry values. This allows detecting and fixing them if needed. See Section 4.6, “ジオメトリ検証”
A Point is a 0-dimensional geometry that represents a single location in coordinate space.
POINT (1 2) POINT Z (1 2 3) POINT ZM (1 2 3 4)
A LineString is a 1-dimensional line formed by a contiguous sequence of line segments. Each line segment is defined by two points, with the end point of one segment forming the start point of the next segment. An OGC-valid LineString has either zero or two or more points, but PostGIS also allows single-point LineStrings. LineStrings may cross themselves (self-intersect). A LineString is closed if the start and end points are the same. A LineString is simple if it does not self-intersect.
LINESTRING (1 2, 3 4, 5 6)
A LinearRing is a LineString which is both closed and simple. The first and last points must be equal, and the line must not self-intersect.
LINEARRING (0 0 0, 4 0 0, 4 4 0, 0 4 0, 0 0 0)
A Polygon is a 2-dimensional planar region, delimited by an exterior boundary (the shell) and zero or more interior boundaries (holes). Each boundary is a LinearRing.
POLYGON ((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))
A MultiLineString is a collection of LineStrings. A MultiLineString is closed if each of its elements is closed.
MULTILINESTRING ( (0 0,1 1,1 2), (2 3,3 2,5 4) )
A MultiPolygon is a collection of non-overlapping, non-adjacent Polygons. Polygons in the collection may touch only at a finite number of points.
MULTIPOLYGON (((1 5, 5 5, 5 1, 1 1, 1 5)), ((6 5, 9 1, 6 1, 6 5)))
A GeometryCollection is a heterogeneous (mixed) collection of geometries.
GEOMETRYCOLLECTION ( POINT(2 3), LINESTRING(2 3, 3 4))
A PolyhedralSurface is a contiguous collection of patches or facets which share some edges. Each patch is a planar Polygon. If the Polygon coordinates have Z ordinates then the surface is 3-dimensional.
POLYHEDRALSURFACE Z ( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
A Triangle is a polygon defined by three distinct non-collinear vertices. Because a Triangle is a polygon it is specified by four coordinates, with the first and fourth being equal.
TRIANGLE ((0 0, 0 9, 9 0, 0 0))
A TIN is a collection of non-overlapping Triangles representing a Triangulated Irregular Network.
TIN Z ( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )
The ISO/IEC 13249-3 SQL Multimedia - Spatial standard (SQL/MM) extends the OGC SFA to define Geometry subtypes containing curves with circular arcs. The SQL/MM types support 3DM, 3DZ and 4D coordinates.
![]() | |
SQL-MM実装での全ての浮動小数点数の比較では、所定の丸め誤差があります。現在は1E-8です。 |
CircularString is the basic curve type, similar to a LineString in the linear world. A single arc segment is specified by three points: the start and end points (first and third) and some other point on the arc. To specify a closed circle the start and end points are the same and the middle point is the opposite point on the circle diameter (which is the center of the arc). In a sequence of arcs the end point of the previous arc is the start point of the next arc, just like the segments of a LineString. This means that a CircularString must have an odd number of points greater than 1.
CIRCULARSTRING(0 0, 1 1, 1 0) CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0)
A CompoundCurve is a single continuous curve that may contain both circular arc segments and linear segments. That means that in addition to having well-formed components, the end point of every component (except the last) must be coincident with the start point of the following component.
COMPOUNDCURVE( CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))
A CurvePolygon is like a polygon, with an outer ring and zero or more inner rings. The difference is that a ring can be a CircularString or CompoundCurve as well as a LineString.
PostGIS 1.4から、PostGISで曲線ポリゴンで複合曲線をサポートするようになりました。
CURVEPOLYGON( CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0), (1 1, 3 3, 3 1, 1 1) )
Example: A CurvePolygon with the shell defined by a CompoundCurve containing a CircularString and a LineString, and a hole defined by a CircularString
CURVEPOLYGON( COMPOUNDCURVE( CIRCULARSTRING(0 0,2 0, 2 1, 2 3, 4 3), (4 3, 4 5, 1 4, 0 0)), CIRCULARSTRING(1.7 1, 1.4 0.4, 1.6 0.4, 1.6 0.5, 1.7 1) )
A MultiCurve is a collection of curves which can include LineStrings, CircularStrings or CompoundCurves.
MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4))
The OGC SFA specification defines two formats for representing geometry values for external use: Well-Known Text (WKT) and Well-Known Binary (WKB). Both WKT and WKB include information about the type of the object and the coordinates which define it.
Well-Known Text (WKT) provides a standard textual representation of spatial data. Examples of WKT representations of spatial objects are:
POINT(0 0)
POINT Z (0 0 0)
POINT ZM (0 0 0 0)
POINT EMPTY
LINESTRING(0 0,1 1,1 2)
LINESTRING EMPTY
POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1))
MULTIPOINT((0 0),(1 2))
MULTIPOINT Z ((0 0 0),(1 2 3))
MULTIPOINT EMPTY
MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4))
MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)), ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1)))
GEOMETRYCOLLECTION(POINT(2 3),LINESTRING(2 3,3 4))
GEOMETRYCOLLECTION EMPTY
Input and output of WKT is provided by the functions ST_AsText and ???:
text WKT = ST_AsText(geometry); geometry = ST_GeomFromText(text WKT, SRID);
For example, a statement to create and insert a spatial object from WKT and a SRID is:
INSERT INTO geotable ( geom, name ) VALUES ( ST_GeomFromText('POINT(-126.4 45.32)', 312), 'A Place');
Well-Known Binary (WKB) provides a portable, full-precision representation of spatial data as binary data (arrays of bytes). Examples of the WKB representations of spatial objects are:
WKT: POINT(1 1)
WKB: 0101000000000000000000F03F000000000000F03
WKT: LINESTRING (2 2, 9 9)
WKB: 0102000000020000000000000000000040000000000000004000000000000022400000000000002240
Input and output of WKB is provided by the functions ST_AsBinary and ???:
bytea WKB = ST_AsBinary(geometry); geometry = ST_GeomFromWKB(bytea WKB, SRID);
For example, a statement to create and insert a spatial object from WKB is:
INSERT INTO geotable ( geom, name ) VALUES ( ST_GeomFromWKB('\x0101000000000000000000f03f000000000000f03f', 312), 'A Place');
PostGIS implements the OGC Simple Features model by defining a PostgreSQL data type called geometry
. It represents all of the geometry subtypes by using an internal type code (see GeometryType and ST_GeometryType). This allows modelling spatial features as rows of tables defined with a column of type geometry
.
The geometry
data type is opaque, which means that all access is done via invoking functions on geometry values. Functions allow creating geometry objects, accessing or updating all internal fields, and compute new geometry values. PostGIS supports all the functions specified in the OGC Simple feature access - Part 2: SQL option (SFS) specification, as well many others. See Chapter 8, PostGISリファレンス for the full list of functions.
![]() | |
PostGIS follows the SFA standard by prefixing spatial functions with "ST_". This was intended to stand for "Spatial and Temporal", but the temporal part of the standard was never developed. Instead it can be interpreted as "Spatial Type". |
The SFA standard specifies that spatial objects include a Spatial Reference System identifier (SRID). The SRID is required when creating spatial objects for insertion into the database (it may be defaulted to 0). See ??? and Section 4.5, “空間参照系”
To make querying geometry efficient PostGIS defines various kinds of spatial indexes, and spatial operators to use them. See Section 4.9, “Spatial Indexes” and Section 5.2, “Using Spatial Indexes” for details.
OGC SFA specifications initially supported only 2D geometries, and the geometry SRID is not included in the input/output representations. The OGC SFA specification 1.2.1 (which aligns with the ISO 19125 standard) adds support for 3D (ZYZ) and measured (XYM and XYZM) coordinates, but still does not include the SRID value.
Because of these limitations PostGIS defined extended EWKB and EWKT formats. They provide 3D (XYZ and XYM) and 4D (XYZM) coordinate support and include SRID information. Including all geometry information allows PostGIS to use EWKB as the format of record (e.g. in DUMP files).
EWKB and EWKT are used for the "canonical forms" of PostGIS data objects. For input, the canonical form for binary data is EWKB, and for text data either EWKB or EWKT is accepted. This allows geometry values to be created by casting a text value in either HEXEWKB or EWKT to a geometry value using ::geometry
. For output, the canonical form for binary is EWKB, and for text it is HEXEWKB (hex-encoded EWKB).
For example this statement creates a geometry by casting from an EWKT text value, and outputs it using the canonical form of HEXEWKB:
SELECT 'SRID=4;POINT(0 0)'::geometry; geometry ---------------------------------------------------- 01010000200400000000000000000000000000000000000000
PostGIS EWKT output has a few differences to OGC WKT:
For 3DZ geometries the Z qualifier is omitted:
OGC: POINT Z (1 2 3)
EWKT: POINT (1 2 3)
For 3DM geometries the M qualifier is included:
OGC: POINT M (1 2 3)
EWKT: POINTM (1 2 3)
For 4D geometries the ZM qualifier is omitted:
OGC: POINT ZM (1 2 3 4)
EWKT: POINT (1 2 3 4)
EWKT avoids over-specifying dimensionality and the inconsistencies that can occur with the OGC/ISO format, such as:
POINT ZM (1 1)
POINT ZM (1 1 1)
POINT (1 1 1 1)
![]() | |
PostGIS extended formats are currently a superset of the OGC ones, so that every valid OGC WKB/WKT is also valid EWKB/EWKT. However, this might vary in the future, if the OGC extends a format in a way that conflicts with the PosGIS definition. Thus you SHOULD NOT rely on this compatibility! |
Examples of the EWKT text representation of spatial objects are:
POINT(0 0 0) -- XYZ
SRID=32632;POINT(0 0) -- SRID付きXY
POINTM(0 0 0) -- XYM
POINT(0 0 0 0) -- XYZM
SRID=4326;MULTIPOINTM(0 0 0,1 2 1) -- SRID付きXYM
MULTILINESTRING((0 0 0,1 1 0,1 2 1),(2 3 1,3 2 1,5 4 1))
POLYGON((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))
MULTIPOLYGON(((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0)),((-1 -1 0,-1 -2 0,-2 -2 0,-2 -1 0,-1 -1 0)))
GEOMETRYCOLLECTIONM( POINTM(2 3 9), LINESTRINGM(2 3 4, 3 4 5) )
MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )
POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
TRIANGLE ((0 0, 0 9, 9 0, 0 0))
TIN( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )
Input and output using these formats is available using the following functions:
バイト配列 EWKB = ST_AsEWKB(geometry); テキスト EWKT = ST_AsEWKT(geometry); ジオメトリ = ST_GeomFromEWKB(bytea EWKB); ジオメトリ = ST_GeomFromEWKT(text EWKT);
For example, a statement to create and insert a PostGIS spatial object using EWKT is:
INSERT INTO geotable ( geom, name ) VALUES ( ST_GeomFromEWKT('SRID=312;POINTM(-126.4 45.32 15)'), 'A Place' )
The PostGIS geography
data type provides native support for spatial features represented on "geographic" coordinates (sometimes called "geodetic" coordinates, or "lat/lon", or "lon/lat"). Geographic coordinates are spherical coordinates expressed in angular units (degrees).
The basis for the PostGIS geometry data type is a plane. The shortest path between two points on the plane is a straight line. That means functions on geometries (areas, distances, lengths, intersections, etc) are calculated using straight line vectors and cartesian mathematics. This makes them simpler to implement and faster to execute, but also makes them inaccurate for data on the spheroidal surface of the earth.
The PostGIS geography data type is based on a spherical model. The shortest path between two points on the sphere is a great circle arc. Functions on geographies (areas, distances, lengths, intersections, etc) are calculated using arcs on the sphere. By taking the spheroidal shape of the world into account, the functions provide more accurate results.
Because the underlying mathematics is more complicated, there are fewer functions defined for the geography type than for the geometry type. Over time, as new algorithms are added the capabilities of the geography type will expand. As a workaround one can convert back and forth between geometry and geography types.
Like the geometry data type, geography data is associated with a spatial reference system via a spatial reference system identifier (SRID). Any geodetic (long/lat based) spatial reference system defined in the spatial_ref_sys
table can be used. (Prior to PostGIS 2.2, the geography type supported only WGS 84 geodetic (SRID:4326)). You can add your own custom geodetic spatial reference system as described in Section 4.5.2, “ユーザ定義空間参照系”.
For all spatial reference systems the units returned by measurement functions (e.g. ST_Distance, ST_Length, ST_Perimeter, ST_Area) and for the distance argument of ??? are in meters.
You can create a table to store geography data using the CREATE TABLE SQL statement with a column of type geography
. The following example creates a table with a geography column storing 2D LineStrings in the WGS84 geodetic coordinate system (SRID 4326):
CREATE TABLE global_points ( id SERIAL PRIMARY KEY, name VARCHAR(64), location geography(POINT,4326) );
The geography type supports two optional type modifiers:
the spatial type modifier restricts the kind of shapes and dimensions allowed in the column. Values allowed for the spatial type are: POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION. The geography type does not support curves, TINS, or POLYHEDRALSURFACEs. The modifier supports coordinate dimensionality restrictions by adding suffixes: Z, M and ZM. For example, a modifier of 'LINESTRINGM' only allows linestrings with three dimensions, and treats the third dimension as a measure. Similarly, 'POINTZM' requires four dimensional (XYZM) data.
the SRID modifier restricts the spatial reference system SRID to a particular number. If omitted, the SRID defaults to 4326 (WGS84 geodetic), and all calculations are performed using WGS84.
Examples of creating tables with geography columns:
Create a table with 2D POINT geography with the default SRID 4326 (WGS84 long/lat):
CREATE TABLE ptgeogwgs(gid serial PRIMARY KEY, geog geography(POINT) );
Create a table with 2D POINT geography in NAD83 longlat:
CREATE TABLE ptgeognad83(gid serial PRIMARY KEY, geog geography(POINT,4269) );
Create a table with 3D (XYZ) POINTs and an explicit SRID of 4326:
CREATE TABLE ptzgeogwgs84(gid serial PRIMARY KEY, geog geography(POINTZ,4326) );
Create a table with 2D LINESTRING geography with the default SRID 4326:
CREATE TABLE lgeog(gid serial PRIMARY KEY, geog geography(LINESTRING) );
Create a table with 2D POLYGON geography with the SRID 4267 (NAD 1927 long lat):
CREATE TABLE lgeognad27(gid serial PRIMARY KEY, geog geography(POLYGON,4267) );
Geography fields are registered in the geography_columns
system view. You can query the geography_columns
view and see that the table is listed:
SELECT * FROM geography_columns;
Creating a spatial index works the same as for geometry columns. PostGIS will note that the column type is GEOGRAPHY and create an appropriate sphere-based index instead of the usual planar index used for GEOMETRY.
-- Index the test table with a spherical index CREATE INDEX global_points_gix ON global_points USING GIST ( location );
You can insert data into geography tables in the same way as geometry. Geometry data will autocast to the geography type if it has SRID 4326. The EWKT and EWKB formats can also be used to specify geography values.
-- testテーブルにデータを追加する INSERT INTO global_points (name, location) VALUES ('Town', 'SRID=4326;POINT(-110 30)'); INSERT INTO global_points (name, location) VALUES ('Forest', 'SRID=4326;POINT(-109 29)'); INSERT INTO global_points (name, location) VALUES ('London', 'SRID=4326;POINT(0 49)');
Any geodetic (long/lat) spatial reference system listed in spatial_ref_sys
table may be specified as a geography SRID. Non-geodetic coordinate systems raise an error if used.
-- NAD 83 lon/lat SELECT 'SRID=4269;POINT(-123 34)'::geography; geography ---------------------------------------------------- 0101000020AD1000000000000000C05EC00000000000004140
-- NAD27 lon/lat SELECT 'SRID=4267;POINT(-123 34)'::geography; geography ---------------------------------------------------- 0101000020AB1000000000000000C05EC00000000000004140
-- NAD83 UTM zone meters - gives an error since it is a meter-based planar projection SELECT 'SRID=26910;POINT(-123 34)'::geography; ERROR: Only lon/lat coordinate systems are supported in geography.
クエリと計測関数はメートル単位となります。そのため距離パラメータはメートル (面積の場合は平方メートル)単位となります。
-- A distance query using a 1000km tolerance SELECT name FROM global_points WHERE ST_DWithin(location, 'SRID=4326;POINT(-110 29)'::geography, 1000000);
You can see the power of geography in action by calculating how close a plane flying a great circle route from Seattle to London (LINESTRING(-122.33 47.606, 0.0 51.5)) comes to Reykjavik (POINT(-21.96 64.15)) (map the route).
The geography type calculates the true shortest distance of 122.235 km over the sphere between Reykjavik and the great circle flight path between Seattle and London.
-- Distance calculation using GEOGRAPHY SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geography, 'POINT(-21.96 64.15)'::geography); st_distance ----------------- 122235.23815667
The geometry type calculates a meaningless cartesian distance between Reykjavik and the straight line path from Seattle to London plotted on a flat map of the world. The nominal units of the result is "degrees", but the result doesn't correspond to any true angular difference between the points, so even calling them "degrees" is inaccurate.
-- Distance calculation using GEOMETRY SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geometry, 'POINT(-21.96 64.15)'::geometry); st_distance -------------------- 13.342271221453624
The geography data type allows you to store data in longitude/latitude coordinates, but at a cost: there are fewer functions defined on GEOGRAPHY than there are on GEOMETRY; those functions that are defined take more CPU time to execute.
The data type you choose should be determined by the expected working area of the application you are building. Will your data span the globe or a large continental area, or is it local to a state, county or municipality?
データが小さいエリア内におさまるなら、適切な投影を選択してジオメトリを使うのが、効率面でも機能面でも最も良い方法です。
データが地球全体か大陸なら、ジオグラフィで投影法の細かい問題を気にせずにシステムを構築できるでしょう。経度/緯度のデータを保存して、ジオグラフィで定義された関数使います。
投影法を理解していなくて、学習したくもなくて、かつ、ジオグラフィで使える関数が限られていることを受け入れるのなら、ジオグラフィを使った方が簡単です。単純にデータを経度/緯度でロードして、そこから進めて下さい。
ジオグラフィとジオメトリ間のサポート状況の比較についてはSection 15.11, “PostGIS Function Support Matrix”をご覧下さい。ジオグラフィ関数の簡潔なリストと説明についてはSection 15.4, “PostGIS Geography Support Functions”をご覧下さい。
4.3.4.1. | 球または回転楕円体のどちらで計算するのでしょうか? |
デフォルトでは、全ての距離と面積の計算は回転楕円体で行います。局所的なエリアでの計算結果と良好な投影を施した平面での結果と比較して下さい。大きなエリアの場合は、回転楕円体計算は、投影平面上でのどの計算よりも精度が高くなります。 全てのジオグラフィ関数には、最後の真偽パラメータを'FALSE'にすると球面を使った計算を行うというオプションがあります。これは、特にジオメトリが非常に単純である場合に計算を速くするためのものです。 | |
4.3.4.2. | 日付変更線や極に関してはどうなっていますか? |
全ての計算に日付変更線や極の概念がありません。座標は球 (経度/緯度)であるので、日付変更線とクロスする形状は、計算の観点からは、他のものと変わりありません。 | |
4.3.4.3. | 処理できる最も長い弧はどうなりますか? |
大圏の弧を2点の「補完線」として使用しています。任意の2点は、実際には2方向につながっていて、どちらの方向に行くかに依存します。PostGISの全てのコードは、大圏コースの2コースのうち*短い*方でつながっていると仮定しています。結果として、180度以上の弧を持つ形状は正しくモデル化されません。 | |
4.3.4.4. | なぜヨーロッパやロシアといった大きな範囲の面積計算はとても遅いのですか? |
ポリゴンがとんでもなく大きいからです。二つの理由から、大きなエリアは悪いです。一つは、バウンダリボックスが大きいため、どのようなクエリを走らせても、インデックスがフィーチャーを引っ張ってくる傾向にあるためです。もう一つは、頂点数が巨大で、テスト (距離、包含)関数では、少なくとも1回、通常はN (Nは、もう一方のフィーチャーの頂点数)回、頂点を横断しなければならないためです。 ジオメトリでは、大きなポリゴンを持っているけれども小さな範囲のクエリを実行する時、ジオメトリデータ情報を小片に「非正規化」します。これにより、インデックスが効果的にオブジェクトの一部を問い合わせるようになり、またクエリが常にオブジェクト全体を引っ張りこむようなことがないようになります。???を参照して下さい。ヨーロッパ全体を一つのポリゴンに*格納できる*からといって、*そうすべき*だというわけではありません。 |
You can create a table to store geometry data using the CREATE TABLE SQL statement with a column of type geometry
. The following example creates a table with a geometry column storing 2D (XY) LineStrings in the BC-Albers coordinate system (SRID 3005):
CREATE TABLE roads ( id SERIAL PRIMARY KEY, name VARCHAR(64), geom geometry(LINESTRING,3005) );
The geometry
type supports two optional type modifiers:
the spatial type modifier restricts the kind of shapes and dimensions allowed in the column. The value can be any of the supported geometry subtypes (e.g. POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION, etc). The modifier supports coordinate dimensionality restrictions by adding suffixes: Z, M and ZM. For example, a modifier of 'LINESTRINGM' allows only linestrings with three dimensions, and treats the third dimension as a measure. Similarly, 'POINTZM' requires four dimensional (XYZM) data.
the SRID modifier restricts the spatial reference system SRID to a particular number. If omitted, the SRID defaults to 0.
Examples of creating tables with geometry columns:
Create a table holding any kind of geometry with the default SRID:
CREATE TABLE geoms(gid serial PRIMARY KEY, geom geometry );
Create a table with 2D POINT geometry with the default SRID:
CREATE TABLE pts(gid serial PRIMARY KEY, geom geometry(POINT) );
Create a table with 3D (XYZ) POINTs and an explicit SRID of 3005:
CREATE TABLE pts(gid serial PRIMARY KEY, geom geometry(POINTZ,3005) );
Create a table with 4D (XYZM) LINESTRING geometry with the default SRID:
CREATE TABLE lines(gid serial PRIMARY KEY, geom geometry(LINESTRINGZM) );
Create a table with 2D POLYGON geometry with the SRID 4267 (NAD 1927 long lat):
CREATE TABLE polys(gid serial PRIMARY KEY, geom geometry(POLYGON,4267) );
It is possible to have more than one geometry column in a table. This can be specified when the table is created, or a column can be added using the ALTER TABLE SQL statement. This example adds a column that can hold 3D LineStrings:
ALTER TABLE roads ADD COLUMN geom2 geometry(LINESTRINGZ,4326);
The OGC Simple Features Specification for SQL defines the GEOMETRY_COLUMNS
metadata table to describe geometry table structure. In PostGIS geometry_columns
is a view reading from database system catalog tables. This ensures that the spatial metadata information is always consistent with the currently defined tables and views. The view structure is:
\d geometry_columns
View "public.geometry_columns" Column | Type | Modifiers -------------------+------------------------+----------- f_table_catalog | character varying(256) | f_table_schema | character varying(256) | f_table_name | character varying(256) | f_geometry_column | character varying(256) | coord_dimension | integer | srid | integer | type | character varying(30) |
カラムは次の通りです。
The fully qualified name of the feature table containing the geometry column. There is no PostgreSQL analogue of "catalog" so that column is left blank. For "schema" the PostgreSQL schema name is used (public
is the default).
フィーチャーテーブル内のジオメトリカラムの名前。
The coordinate dimension (2, 3 or 4) of the column.
このテーブルのジオメトリの座標系として使用される座標系空間参照系のIDです。spatial_ref_sys
テーブルを参照する外部キーです (Section 4.5.1, “SPATIAL_REF_SYSテーブル”を参照して下さい)。
空間オブジェクトの型。空間カラムを単一型に制限するには、POINT、LINESTRING、POLYGON、MULTIPOINT、MULTILINESTRING、MULTIPOLYGON、GEOMETRYCOLLECTIONのうちのいずれかを、また、XYMで使う場合には、LINESTRINGM、POLYGONM、MULTIPOINTM、MULTILINESTRINGM、MULTIPOLYGONM、GEOMETRYCOLLECTIONMのうちのいずれかを使います。複数の型が混合するコレクションの場合は"GEOMETRY"を型とすることができます。
これが必要になる事例に、SQLビューとバルクインサートの二つがあります。バルクインサートの場合には、カラムに制約を与えるか、ALTER TABLEを実行することで、geometry_columnsテーブル内の登録を訂正することができます。ビューの場合には、CAST演算を使用します。カラムが型修飾子に基づく場合には、生成処理によって正しく登録されるので、何も行う必要がありません。ジオメトリに適用する空間関数を持たないビューも、基礎となるテーブルのジオメトリカラムと同じように登録されます。
-- 次のようなビューがあるとします CREATE VIEW public.vwmytablemercator AS SELECT gid, ST_Transform(geom, 3395) As geom, f_name FROM public.mytable; -- 正しく登録するには、 -- ジオメトリをキャストします。 -- DROP VIEW public.vwmytablemercator; CREATE VIEW public.vwmytablemercator AS SELECT gid, ST_Transform(geom, 3395)::geometry(Geometry, 3395) As geom, f_name FROM public.mytable; -- ジオメトリタイプが確実に2次元ポリゴンだと知っているなら -- 次のようにできます。 DROP VIEW public.vwmytablemercator; CREATE VIEW public.vwmytablemercator AS SELECT gid, ST_Transform(geom,3395)::geometry(Polygon, 3395) As geom, f_name FROM public.mytable;
-- 次のように、バルクインサートで派生テーブルを生成したとしましょう SELECT poi.gid, poi.geom, citybounds.city_name INTO myschema.my_special_pois FROM poi INNER JOIN citybounds ON ST_Intersects(citybounds.geom, poi.geom); -- 新しいテーブルに2次元インデックスを作ります CREATE INDEX idx_myschema_myspecialpois_geom_gist ON myschema.my_special_pois USING gist(geom); -- ポイントが3次元ポイントであったり、XYMポイントであったりした場合には、 -- 次のように、2次元インデックスでなくN次元インデックスを作ることになるかも -- 知れません。 CREATE INDEX my_special_pois_geom_gist_nd ON my_special_pois USING gist(geom gist_geometry_ops_nd); -- 新しいテーブルのジオメトリカラムをgeometry_columnsに手動登録するには、 -- 次のようにします。 -- カラムを型修飾子ベースにするために、基礎となるテーブル構造も変更することに -- 注意して下さい。 SELECT populate_geometry_columns('myschema.my_special_pois'::regclass); -- PostGIS 2.0を使っていて、何らかの理由で古い制約をもとにした定義を行う -- (派生テーブルが同じタイプやSRIDを持たないといった場合)ことが必要な場合には、 -- 新しい任意変数use_typemodをfalseにします。 SELECT populate_geometry_columns('myschema.my_special_pois'::regclass, false);
古い制約を基にした手法は現在も対応していますが、制約を基にしたジオメトリカラムで直接的にビューで使われている場合は、型修飾子のようには正しくgeometry_columnsに登録されません。次の例では、型修飾子を使ったカラム定義と、制約に基づくカラムの定義とを行っています。
CREATE TABLE pois_ny(gid SERIAL PRIMARY KEY, poi_name text, cat text, geom geometry(POINT,4326)); SELECT AddGeometryColumn('pois_ny', 'geom_2160', 2160, 'POINT', 2, false);
psqlで次を実行します。
\d pois_ny;
型修飾子と制約に基づくのとでは異なった定義になっているのが見えます。
Table "public.pois_ny" Column | Type | Modifiers -----------+-----------------------+------------------------------------------------------ gid | integer | not null default nextval('pois_ny_gid_seq'::regclass) poi_name | text | cat | character varying(20) | geom | geometry(Point,4326) | geom_2160 | geometry | Indexes: "pois_ny_pkey" PRIMARY KEY, btree (gid) Check constraints: "enforce_dims_geom_2160" CHECK (st_ndims(geom_2160) = 2) "enforce_geotype_geom_2160" CHECK (geometrytype(geom_2160) = 'POINT'::text OR geom_2160 IS NULL) "enforce_srid_geom_2160" CHECK (st_srid(geom_2160) = 2160)
geometry_columnsでは、両方とも正しく登録されています。
SELECT f_table_name, f_geometry_column, srid, type FROM geometry_columns WHERE f_table_name = 'pois_ny';
f_table_name | f_geometry_column | srid | type -------------+-------------------+------+------- pois_ny | geom | 4326 | POINT pois_ny | geom_2160 | 2160 | POINT
しかし、次のようにビューを作ろうとします。
CREATE VIEW vw_pois_ny_parks AS SELECT * FROM pois_ny WHERE cat='park'; SELECT f_table_name, f_geometry_column, srid, type FROM geometry_columns WHERE f_table_name = 'vw_pois_ny_parks';
型修飾子によるgeomのビューカラムは正しく登録されますが、制約に基づくものは正しく登録されません。
f_table_name | f_geometry_column | srid | type ------------------+-------------------+------+---------- vw_pois_ny_parks | geom | 4326 | POINT vw_pois_ny_parks | geom_2160 | 0 | GEOMETRY
これは、将来的にPostGISの版で変更されるかもしれませんが、今のところは、制約に基づくビューカラムを正しく登録させるには、次のようにします。
DROP VIEW vw_pois_ny_parks; CREATE VIEW vw_pois_ny_parks AS SELECT gid, poi_name, cat, geom, geom_2160::geometry(POINT,2160) As geom_2160 FROM pois_ny WHERE cat = 'park'; SELECT f_table_name, f_geometry_column, srid, type FROM geometry_columns WHERE f_table_name = 'vw_pois_ny_parks';
f_table_name | f_geometry_column | srid | type ------------------+-------------------+------+------- vw_pois_ny_parks | geom | 4326 | POINT vw_pois_ny_parks | geom_2160 | 2160 | POINT
Spatial Reference Systems (SRS, 空間参照系)は、どのようにジオメトリが地表位置に参照されるかを定義しています。
PostGISで使用されるSPATIAL_REF_SYS
テーブルは、有効な空間参照系を定義するOGC準拠のデータベーステーブルです。数字の識別子と文字列の空間参照系の説明を持ちます。主に???を用いた空間参照系間の変換 (投影変換)に対応するために使用されています。
spatial_ref_sys
の定義は次の通りです。
CREATE TABLE spatial_ref_sys ( srid INTEGER NOT NULL PRIMARY KEY, auth_name VARCHAR(256), auth_srid INTEGER, srtext VARCHAR(2048), proj4text VARCHAR(2048) )
カラムは次の通りです。
データベース内のSpatial Reference System (SRS, 空間参照系)で一意に識別される整数コードです。
この参照系に引用されている標準の名前もしくは標準そのものです。たとえば「EPSG」は妥当なauth_name
です。
auth_name
で引用されている団体によって定義された空間参照系のIDです。EPSGの場合、EPSG投影コードが入ります。
空間参照系のWell-Knownテキスト表現です。たとえば、WKT SRSの表現は、次のようになります。
PROJCS["NAD83 / UTM Zone 10N", GEOGCS["NAD83", DATUM["North_American_Datum_1983", SPHEROID["GRS 1980",6378137,298.257222101] ], PRIMEM["Greenwich",0], UNIT["degree",0.0174532925199433] ], PROJECTION["Transverse_Mercator"], PARAMETER["latitude_of_origin",0], PARAMETER["central_meridian",-123], PARAMETER["scale_factor",0.9996], PARAMETER["false_easting",500000], PARAMETER["false_northing",0], UNIT["metre",1] ]
EPSG投影コードと対応するWKT表現の一覧については、http://www.opengeospatial.org/をご覧下さい。SRSのWKTについての一般的な議論については、OpenGISのhttp://www.opengeospatial.org/standardsにある「座標変換サービス実装仕様」をご覧下さい。欧州石油調査グループ(European Petroleum Survey Group, EPSG)とEPSG空間参照系のデータベースに関する情報は、http://www.epsg.org/をご覧下さい。
PostGISは座標変換機能を提供するためにProj4ライブラリを用いています。 proj4text
カラムには、特定のSRIDを示すProj4座標定義文字列が入ります。たとえば次のようになります。
+proj=utm +zone=10 +ellps=clrk66 +datum=NAD27 +units=m
詳細情報についてはPROJウェブサイトをご覧下さい。spatial_ref_sys.sql
ファイルには、全てのEPSG投影について、srtext
とproj4text
の定義があります。
投影変換で空間参照系の定義を使用する場合には、次の戦略を取ります。
auth_name
とauth_srid
がある (NULLでない)場合には、これに基づいてPROJSRSを使います (存在する場合)。
srtext
がある場合には、可能ならそれを使用してSRSを生成します。
proj4text
がある場合には、可能ならこれを使用してSRSを生成します。
PostGISspatial_ref_sys
テーブルにはPROJ投影ライブラリで処理される最も一般的な空間参照系定義3000件以上があります。しかし、そこに無い多くの座標系があります。空間参照系に関する必要な情報がある場合は、SRS定義をテーブルに追加できます。PROJに詳しいなら独自の空間参照系を定義することもできます。ほとんどの空間参照系は地域的なものであり、目的の範囲外で使用する場合は意味を持たない点に注意してください。
PostGISのコアセットに入っていない空間参照系を探すための素晴らしい資料がhttp://spatialreference.org/にあります。
一般的に使用される空間参照系には4326 - WGS 84経度緯度、4269 - NAD 83 経度緯度、3395 - WGS 84 メルカトル、2163 - 米国ナショナルアトラス正積図法、60個のWGS84 UTMゾーンがあります。UTMゾーンは計測に最適ですが、6度 (訳注: 経度)の領域のみをカバーします (対象地域に使用するUTMゾーンを決定するにはutmzone PostGIS plpgsql helper functionを参照してください)。
米国の州では、州平面空間参照系 (メートルまたはフィート単位)を使用します。この空間参照系は州ごとに一つか二つ存在します。ほとんどのメートル単位のものはコアのセットに存在しますが、フィート単位の多数のものやESRIが作成したものはspatialreference.orgからロードする必要があります。
地球外の座標系でさえも定義することができます。たとえばMars 2000です。この火星の座標系は非平面 (回転楕円体の度)ですが、geography
型で、度でなくメートル単位で長さや近接測定値を取得することができます。
割当外のSRIDとPROJ定義を使って米国中央のランベルト正角円錐図法の独自座標系をロードする例を次に示します。
INSERT INTO spatial_ref_sys (srid, proj4text) VALUES ( 990000, '+proj=lcc +lon_0=-95 +lat_0=25 +lat_1=25 +lat_2=25 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs' );
PostGISはOpen Geospatial Consortium (OGC)のOpenGIS仕様に準拠しています。多くのPostGISメソッドは、操作対象のジオメトリが単純かつ妥当であることが求められます (正確に言うとそう仮定します)。たとえば、ポリゴンの外に穴があるようなものの面積を計算したり、単純でない境界線を持つポリゴンを作ったりするのは、意味がありません。
OGS仕様に沿うと、単純なジオメトリとは、自己インタセクトや自己接触のような、異常な幾何点を持たないことです。主に0次元または1次元のジオメトリ ([MULTI]POINT, [MULTI]LINESTRING
))に適用します。 他方、ジオメトリの妥当性は、主に2次元ジオメトリ ([MULTI]POLYGON
)に適用し、妥当なポリゴンを特徴づける位置指定子の集合を定義します。個々のジオメトリクラスには、単純性と妥当性をさらに詳細に述べる特定の条件があります。
POINT
は0次元ジオメトリオブジェクトとして常に単純です。
MULTIPOINT
は、二つの座標値 (POINT
)が同じでないなら単純です。
LINESTRING
は、2度同じPOINT
を通らない (終点は除きます。この場合は線型環と呼ばれ、さらに言うと閉じていると思われます)なら単純です。
![]() (a) | ![]() (b) |
![]() (c) | ![]() (d) |
(a)と(c)は単純な |
MULTILINESTRING
は、 全ての要素が単純で、かつ任意の2要素のインタセクトが要素の境界であるPOINT
でだけ発生する場合に限って単純です。
![]() (e) | ![]() (f) | ![]() (g) |
(e)と(f)は単純な |
定義からPOLYGON
は常に単純です。バウンダリ内の環 (外環と内環からなる)のうち二つがクロスしていないなら妥当です。POLYGON
の境界は、POINT
とインタセクトするかも知れませんが、接点にしかなりません (すなわち線上にない)。POLYGON
はカットラインまたはスパイクを持たなくても良く、内環は外環の中に完全に含まれていなければなりません。
![]() (h) | ![]() (i) | ![]() (j) |
![]() (k) | ![]() (l) | ![]() (m) |
(h)と(i)は妥当な |
MULTIPOLYGON
は、全ての要素が妥当で、二つのポリゴン要素について内側がインタセクトしていない場合は妥当です。ポリゴン要素の任意の二つの境界は接触してもよいですが、有限な数のPOINT
でなければなりません。
![]() (n) | ![]() (o) | ![]() (p) |
(n)と(o)は妥当でない |
GEOSライブラリを使って実装されている関数のほとんどは、ジオメトリがOpenGISシンプルフィーチャー仕様で定義されているように妥当であると仮定しています。ジオメトリが単純であるか、また妥当であるか、のチェックとしてST_IsSimple()とST_IsValid()が使えます。
-- 一般的に、線フィーチャーの妥当性のチェックは -- 常にTRUEを返すので意味がありません -- しかし、この例では、PostGISがOGCのIsValidの定義を拡張して -- *一意な頂点*が2より少ないラインストリングについてFALSEを -- 返すようにしています gisdb=# SELECT ST_IsValid('LINESTRING(0 0, 1 1)'), ST_IsValid('LINESTRING(0 0, 0 0, 0 0)'); st_isvalid | st_isvalid ------------+----------- t | f
デフォルトでは、PostGISはジオメトリ入力に関するこの妥当性チェックを適用しません。複雑なジオメトリの妥当性のチェックはCPU時間を多く必要とするためです。データソースが信用できない場合は、手動でこのチェックを強制するための制約を付けることができます。
ALTER TABLE mytable ADD CONSTRAINT geometry_valid_check CHECK (ST_IsValid(geom));
妥当な入力ジオメトリでPostGIS関数を呼んだのに「GEOS Intersection()がエラーを投げました!」というようなエラーメッセージに遭遇したなら、PostGISまたは使用しているライブラリの中のエラーを発見しました。PostGIS開発者に連絡するべきです。PostGIS関数が妥当である入力ジオメトリから妥当でないジオメトリが返る場合も同じです。
![]() | |
The ST_IsValid() function does not check the Z and M dimensions. |
空間テーブルを作成したら、これでGISデータをデータベースにアップロードする準備ができたことになります。現在、PostGIS/PostgreSQLデータベースにデータをロードするには、SQLステートメントを使う、またはシェープファイルのローダ/ダンパを使う、という二つの方法があります。
空間データを文字表現 (WKTかWKB)に変換できたら、SQLを使うのがPostGISにデータを持たせる最も簡単です。SQLユーティリティのpsql
を使用して、SQLのINSERT
ステートメントのテキストファイルをロードすると、データをPostGIS/PostgreSQLに一括読み込みできます。
データアップロードファイル (たとえばroads.sql
)は次のようになるでしょう。
BEGIN; INSERT INTO roads (road_id, roads_geom, road_name) VALUES (1,'LINESTRING(191232 243118,191108 243242)','Jeff Rd'); INSERT INTO roads (road_id, roads_geom, road_name) VALUES (2,'LINESTRING(189141 244158,189265 244817)','Geordie Rd'); INSERT INTO roads (road_id, roads_geom, road_name) VALUES (3,'LINESTRING(192783 228138,192612 229814)','Paul St'); INSERT INTO roads (road_id, roads_geom, road_name) VALUES (4,'LINESTRING(189412 252431,189631 259122)','Graeme Ave'); INSERT INTO roads (road_id, roads_geom, road_name) VALUES (5,'LINESTRING(190131 224148,190871 228134)','Phil Tce'); INSERT INTO roads (road_id, roads_geom, road_name) VALUES (6,'LINESTRING(198231 263418,198213 268322)','Dave Cres'); COMMIT;
SQLファイルのPostgreSQLへのロードはpsql
を使います。次のようにします。
psql -d [データベース名] -f roads.sql
shp2pgsql
データローダは、ESRIシェープファイルをPostGIS/PostgreSQLデータベースに、ジオメトリまたはジオグラフィとして挿入するための適切なSQLに変換します。ローダには、次に示すコマンドラインフラグによって区別される、いくつかの操作モードがあります。
グラフィカルユーザインタフェースを持つshp2pgsql-gui
もあります。コマンドラインローダのオプションのほとんどが使えます。これは、スクリプト化されていない1回限りのロードの場合や、PostGIS初心者がロードする場合に、簡単に使用できます。PgAdminIIIのプラグインとすることもできます。
新しいテーブルの作成とシェープファイルからのデータの読み込みを行います。これがデフォルトモードです。
シェープファイルからデータベーステーブルにデータを追加します。複数のファイルをロードするためにこのオプションを使う場合は、これらのファイルは同じ属性と同じデータ型を持つ必要があります。
シェープファイルにあるデータを持つ新しいテーブルを作成する前にデータベーステーブルを削除します。
テーブル作成のSQLコードを生成するだけで、実際のデータは追加しません。このモードは、テーブル作成とデータロードとを完全に分けたい場合に使用します。
ヘルプ画面を表示します。
出力データにPostgreSQLのダンプ書式を用います。このモードは-a, -c, -dと組み合わせて利用します。デフォルトの"insert"によるSQL書式よりも、大変早くロードできます。大きなデータセットではこちらを使用して下さい。
指定したSRIDを持つジオメトリテーブルの生成や追加を行います。FROM_SRIDが与えられた場合には、入力シェープファイルに、これを使います 。この場合には、ジオメトリは変更先SRIDに投影変換します。
識別子 (カラム、スキーマおよび属性)の大文字小文字を保持します。シェープファイルの属性は全て大文字であることに注意して下さい。
全ての整数を標準の32ビット整数に強制します。DBFヘッダではそれが正当であったとしても、64ビットのbigintを生成しません。
ジオメトリカラムにGiSTインデックスを生成します。
-m a_file_name
で、長いカラム名を10文字のDBFカラム名に対応付けるファイルを指定します。ファイルは、1以上の行を持ちます。各行は空白区切りで二つの名前を持ち、行頭行末に空白を入れません。例を次に示します。
COLUMNNAME DBFFIELD1 AVERYLONGCOLUMNNAME DBFFIELD2
マルチ系ジオメトリの替りに単一ジオメトリを生成します。全てのジオメトリが実際に単一である (たとえば単一の外環でなるMULTIPOLYGONや単一の頂点でなるMULTIPOINT)場合にのみ成功します。
出力ジオメトリが特定の次元を持つよう強制します。次元は、2D, 3DZ, 3DM, 4Dの文字列を使います。
入力の次元が出力より小さい場合には、出力では0が入ります。入力の次元が大きい場合には、外されます。
出力書式をWKBでなくWKTにします。精度が低下して、座標変動が発生しうることに注意が必要です。
トランザクションを使わずに、ステートメントごとに実行するようにします。エラーの元となる不良なジオメトリがいくつか含んでいる時に、大半の良好なデータのロードが可能にするものです。ダンプ書式ではトランザクションを常に使うので、-Dフラグを指定している場合には使えません。
入力データ (dbfファイル)のエンコーディングを指定します。全てのdbfの属性は指定されたエンコーディングからUTF8に変換されます。SQL出力結果には SET CLIENT_ENCODING to UTF8
が含まれるようになり、バックエンドはUTF-8からデータベースが内部利用のために設定したエンコーディングに再変換できます。
NULLジオメトリ操作方針(insert*=挿入, skip=スキップ, abort=強制終了)を選択します。
DBFファイルのみインポートします。対応するシェープファイルを持っていない場合、 自動的にこのモードになり、DBFファイルのみロードします。 このフラグは、完全なシェープファイル群を持っていて、属性データだけが欲しくてジオメトリが欲しくない時のみ使用します。
ジオメトリ型のかわりに、ジオグラフィ型で、WGS84経度緯度 (SRID=4326)を使用します (経度緯度データが必要です)。
新しいテーブルのテーブル空間を指定します。 -Xパラメータが使われない場合には、インデックスはデフォルトのテーブル空間を使用します。PostgreSQL文書には、テーブル空間を用いるべき時に関する良い文書があります。
新しいテーブルのインデックスで使われるテーブル空間を指定します。 主キーインデックスに適用され、-Iが合わせて使われている場合にはGiST空間インデックスにも適用されます。
When used, this flag will prevent the generation of ANALYZE
statements. Without the -Z flag (default behavior), the ANALYZE
statements will be generated.
ローダを使って入力ファイルを生成してアップロードするセッション例は次の通りです。
# shp2pgsql -c -D -s 4269 -i -I shaperoads.shp myschema.roadstable > roads.sql # psql -d roadsdb -f roads.sql
変換とアップロードはUNIXのパイプを使うと一回で実行できます。
# shp2pgsql shaperoads.shp myschema.roadstable | psql -d roadsdb
空間データはSQLかシェープファイルダンパを使うと抽出できます。SQLの節では空間テーブルで比較とクエリに使用できる関数を示します。
データベース外へのデータ抽出の最も簡単な方法は、抽出するデータセットを定義し、SELECT
問い合わせを使って、結果カラムを解析可能なテキストファイルにダンプすることです。
db=# SELECT road_id, ST_AsText(road_geom) AS geom, road_name FROM roads; road_id | geom | road_name --------+-----------------------------------------+----------- 1 | LINESTRING(191232 243118,191108 243242) | Jeff Rd 2 | LINESTRING(189141 244158,189265 244817) | Geordie Rd 3 | LINESTRING(192783 228138,192612 229814) | Paul St 4 | LINESTRING(189412 252431,189631 259122) | Graeme Ave 5 | LINESTRING(190131 224148,190871 228134) | Phil Tce 6 | LINESTRING(198231 263418,198213 268322) | Dave Cres 7 | LINESTRING(218421 284121,224123 241231) | Chris Way (6 rows)
返されるレコードの数を減らすためにある種の制限が必要になる場合があります。属性ベースで制限をかける場合には、非空間テーブルで使うのと同じSQL文を使います。空間に制限をかけるには次の関数を使います。
この関数は、二つのジオメトリが空間を共有しているかどうかをテストします。
この関数で、二つのジオメトリが幾何的に同一であるかを見ることができます。たとえば、'POLYGON((0 0,1 1,1 0,0 0))' は 'POLYGON((0 0,1 1,1 0,0 0))' と同じかを見ることができます (これは同じとなります)。
次に、これらの演算子をクエリで使うことができます。SQLコマンドラインからジオメトリとボックスの指定を行うときは、明示的に文字列表現をジオメトリに変換しなければならないことに注意して下さい。たとえば、次のようになります。ただし312は架空の空間参照系番号で、ここでのデータに合致しています。
SELECT road_id, road_name FROM roads WHERE roads_geom='SRID=312;LINESTRING(191232 243118,191108 243242)'::geometry;
上のクエリは"ROADS_GEOM"テーブルから、その値と等価である単一のレコードを返します。
道路がポリゴンで定義した面を通過するかどうかをチェックするには次のようにします。
SELECT road_id, road_name FROM roads WHERE ST_Intersects(roads_geom, 'SRID=312;POLYGON((...))');
最も一般的な空間クエリは「フレームベース」のクエリでしょう。これは、表示するためのデータの価値のある「マップフレーム」を取得するために、データブラウザやウェブマッパのようなクライアントソフトウェアに使われます。
"&&"演算子を使うとき、比較フィーチャーをBOX3DかGEOMETRYかに指定することができます。ただし、GEOMETRYを指定すると、それのバウンディングボックスが比較に使われます。
次に示すクエリのように、フレームにBOX3Dオブジェクトを使います。
SELECT ST_AsText(roads_geom) AS geom FROM roads WHERE roads_geom && ST_MakeEnvelope(191232, 243117,191232, 243119,312);
エンベロープの投影を指定するためにSRID 312を使っていることに注意して下さい。
pgsql2shp
テーブルダンパは、データベースに直接接続して、テーブル (あるいはクエリによって定義されたもの)をシェープファイルに変換するものです。基本的な文は次の通りです。
pgsql2shp [<オプション>] <database> [<スキーマ>.]<table>
pgsql2shp [<オプション>] <データベース> <クエリ>
コマンドラインオプションは次の通りです。
特定のファイル名に出力を書きこみます。
接続先データベースのホスト名。
接続先データベースのポート。
データベースに接続するためのパスワード。
データベースに接続する際のユーザ名。
複数のジオメトリカラムを持つテーブルの場合の、シェープファイルの出力に使用するジオメトリカラム。
バイナリカーソルを使います。これは、実行時間を短くしますが、テーブルの非ジオメトリ属性がテキストへのキャストを持っていない場合には、動作しません。
Rawモード。gid
フィールドを落としたり、カラム名をエスケープしてはいけません。
ファイル名
識別名を10文字名に再割り当てします。 ファイルの中身は、一つの空白で区切られ、前と後に空白が無い二つのシンボルの行からなります。VERYLONGSYMBOL SHORTONE ANOTHERVERYLONGSYMBOL SHORTER等となります。
Spatial indexes make using a spatial database for large data sets possible. Without indexing, a search for features requires a sequential scan of every record in the database. Indexing speeds up searching by organizing the data into a structure which can be quickly traversed to find matching records.
The B-tree index method commonly used for attribute data is not very useful for spatial data, since it only supports storing and querying data in a single dimension. Data such as geometry (which has 2 or more dimensions) requires an index method that supports range query across all the data dimensions. One of the key advantages of PostgreSQL for spatial data handling is that it offers several kinds of index methods which work well for multi-dimensional data: GiST, BRIN and SP-GiST indexes.
GiST (Generalized Search Tree)インデックスは、データを「一方にあるもの」「オーバラップするもの」「内部にあるもの」に分解するもので、GISデータを含む幅広い範囲で使えます。PostGISはGiSTインデックス空間データをR木インデックス実装のベースにています。GiSTは最も一般的に使われ、多目的なインデックス手法で、非常に良好な問い合わせ効率を提供しています。
BRIN (Block Range Index)インデックスは、空間範囲を集計することで動作します。探索は範囲のスキャンを通して行われます。BRINは一部の種類 (空間的にソートされ、更新がほぼ無いか全く無い)のデータだけに適切です。しかし、インデックス生成時間は非所に早く、インデックスサイズは非常に小さくなります。
SP-GiST (Space-Partitioned Generalized Search Tree)は4分木、kd木、基数木 (トライ木)のような部分木探索に対応する一般的なインデックス手法です。
Spatial indexes store only the bounding box of geometries. Spatial queries use the index as a primary filter to quickly determine a set of geometries potentially matching the query condition. Most spatial queries require a secondary filter that uses a spatial predicate function to test a more specific spatial condition. For more information on queying with spatial predicates see Section 5.2, “Using Spatial Indexes”.
See also the PostGIS Workshop section on spatial indexes, and the PostgreSQL manual.
GiST stands for "Generalized Search Tree" and is a generic form of indexing for multi-dimensional data. PostGIS uses an R-Tree index implemented on top of GiST to index spatial data. GiST is the most commonly-used and versatile spatial index method, and offers very good query performance. Other implementations of GiST are used to speed up searches on all kinds of irregular data structures (integer arrays, spectral data, etc) which are not amenable to normal B-Tree indexing. For more information see the PostgreSQL manual.
Once a spatial data table exceeds a few thousand rows, you will want to build an index to speed up spatial searches of the data (unless all your searches are based on attributes, in which case you'll want to build a normal index on the attribute fields).
GiSTインデックスをジオメトリカラムに追加するための文は次の通りです。
CREATE INDEX [インデックス名] ON [テーブル名] USING GIST ( [ジオメトリカラム名] );
上の文では常に2次元インデックスを構築します。n次元インデックスをジオメトリ型で使うには、次の文でインデックスを生成できます。
CREATE INDEX [インデックス名] ON [テーブル名] USING GIST ( [ジオメトリカラム名] gist_geometry_ops_nd);
空間インデックスの構築は、計算量を集中させて行われます。また、この時には、テーブルへの書き込みアクセスがブロックされます。そのため、本番システムではより遅いCONCURRENTLYを選択するかも知れません。次のようにします。
CREATE INDEX CONCURRENTLY [インデックス名] ON [テーブル名] USING GIST ( [ジオメトリカラム名] );
インデックス構築後に、時々PostgreSQLにテーブルの統計情報を集めさせると助かります。クエリプランの最適化に使われます。
VACUUM ANALYZE [テーブル名] [(カラム名)];
BRIN stands for "Block Range Index". It is a general-purpose index method introduced in PostgreSQL 9.5. BRIN is a lossy index method, meaning that a secondary check is required to confirm that a record matches a given search condition (which is the case for all provided spatial indexes). It provides much faster index creation and much smaller index size, with reasonable read performance. Its primary purpose is to support indexing very large tables on columns which have a correlation with their physical location within the table. In addition to spatial indexing, BRIN can speed up searches on various kinds of attribute data structures (integer, arrays etc). For more information see the PostgreSQL manual.
空間テーブルが、ひとたび数千行を超えると、データの空間検索の速度向上にインデックスが必要と感じることになります。GiSTインデックスは、サイズがデータベースで使えるRAM容量を超えず、インデックスのストレージサイズに余裕があり、書き込み時のインデックス更新コストにも余裕があるなら、非常に高いパフォーマンスを発揮します。そうでない場合には、非常に大きなテーブルにおいては、BRINインデックスを代替に考えることができます。
BRINインデックスは、連続するテーブルブロックの集合 (ブロック範囲と言います)の全てのジオメトリを囲むバウンディングボックスを格納します。インデックスを使用した問い合わせを実行する時に、問い合わせ範囲とインタセクトするブロック範囲を見つけるためにスキャンします。これは、データが物理的に整列していて、ブロック範囲のバウンディングボックスのオーバラップが最小である (理想的には相互に排他的である)場合に限って効率的です。結果インデックスは非常に小さいサイズですが、通常、読み込み効率は、同じデータにおけるGiSTインデックスより悪くなります。
BRINインデックスの構築は、はGiSTインデックスと比べて、CPU集中を非常に減らします。BRINインデックスはGiSTインデックスよりも、同じデータに対して10倍速く構築するのが普通です。BRINインデックスはテーブルブロックの範囲ごとに一つのバウンディングボックスしか格納しないので、GiSTインデックスと比べて、ディスクスペースを1000倍少なくできます。
レンジ内で要約するブロック数を選択できます。この数字を減らすと、インデックスは大きくなりますが、効率向上の助けになる可能性があります。
BRINを効果的にするには、テーブルデータをブロック範囲のオーバラップの量を最小にするような物理的オーダーで格納します。データが既に適切に並び替えられているかも知れません (たとえば、既に空間オーダーで並び替えられているデータセットを他のデータベースからロードする場合)。そうでない場合には、一つの空間キーによるデータの並べ替えで実現できます。一つの方法として、ジオメトリ値で並べ替えた新しいテーブルを生成することです (最近のPostGISのバージョンで効果的なヒルベルト曲線オーダーが使われています)。
CREATE TABLE table_sorted AS SELECT * FROM table ORDER BY geom;
もしくは、データは、ジオハッシュを (一時的な)インデックスに使い、そのインデックスでクラスタリングを行うことによって適切に並べ替えることができます。
CREATE INDEX idx_temp_geohash ON table USING btree (ST_GeoHash( ST_Transform( geom, 4326 ), 20)); CLUSTER table USING idx_temp_geohash;
BRINインデックスをジオメトリ
カラムに追加するための文は次の通りです。
CREATE INDEX [インデックス名] ON [テーブル名] USING BRIN ( [ジオメトリカラム名] );
上の文で2次元インデックスを構築します。3次元インデックスをビルドするには、この文を使います。
CREATE INDEX [インデックス名] ON [テーブル名] USING BRIN ( [ジオメトリカラム名] brin_geometry_inclusion_ops_3d);
また、4次元演算子クラスを使う4次元インデックスを使うこともできます。
CREATE INDEX [インデックス名] ON [テーブル名] USING BRIN ( [ジオメトリカラム名] brin_geometry_inclusion_ops_4d);
上記のコマンドでは、範囲のブロック数はデフォルトの128を使用しています。集計で範囲のブロック数を指定するには、この文を使います。
CREATE INDEX [インデックス名] ON [テーブル名] USING BRIN ( [ジオメトリカラム名] ) WITH (pages_per_range = [数字]);
また、BRINインデックスは、多数の行で一つのインデックス値を格納することを心に留めておいて下さい。テーブルに違う次元のジオメトリを格納する場合には、インデックスの効率が悪くなります。この効率欠落を回避するには、格納したジオメトリの次元数の最小値となる演算子クラスを選択します。
「ジオグラフィ」型もまたBRINインデックスに対応しています。BRINインデックスを「ジオグラフィ」カラムに構築するための文は次の通りです。
CREATE INDEX [インデックス名] ON [テーブル名] USING BRIN ( [ジオメトリカラム名] );
上の文では常に回転楕円体面上の地理空間オブジェクトの2次元インデックスを構築します。
現在のところは「包括対応」だけをここで考えています。これは、&&
, ~
, @
の演算子だけが2次元で使われることを意味します (ジオメトリ
とジオグラフィ
の両方)。 &&&
演算子は3次元ジオメトリで使えます。しばらくはKNN検索に対応しません。
BRINと他のインデックスとの重要な違いは、データベースがインデックスを動的に保守しないことです。テーブルの空間データを変更すると、単純にインデックスの末尾に追加しています。このためインデックス探索の能率が時間とともに低下します。インデックスはVACUUM
か空間関数brin_summarize_new_values(regclass)
を実行することで更新できます。このため、BRINは読み込み専用か、書き込みがほとんど発生しないよなデータでの利用では最も適切になりえます。詳細情報については、manualをご覧下さい。
空間データにBRINを使用して集計するには:
インデックス構築時間は非常に速く、インデックスサイズは非常に小さいです。
インデックスのクエリ時間はGiSTより遅いですが、十分許容できます。
テーブルデータを空間順序で並べ替える必要があります。
手動でインデックスの保守をする必要があります。
Most appropriate for very large tables, with low or no overlap (e.g. points), which are static or change infrequently.
More effective for queries which return relatively large numbers of data records.
SP-GiST stands for "Space-Partitioned Generalized Search Tree" and is a generic form of indexing for multi-dimensional data types that supports partitioned search trees, such as quad-trees, k-d trees, and radix trees (tries). The common feature of these data structures is that they repeatedly divide the search space into partitions that need not be of equal size. In addition to spatial indexing, SP-GiST is used to speed up searches on many kinds of data, such as phone routing, ip routing, substring search, etc. For more information see the PostgreSQL manual.
As it is the case for GiST indexes, SP-GiST indexes are lossy, in the sense that they store the bounding box enclosing spatial objects. SP-GiST indexes can be considered as an alternative to GiST indexes.
一度GISデータテーブルが数千行を超えると、データの空間探索の速度向上にSP-GiSTインデックスを使うと良いかも知れません。「ジオメトリ」カラムにSP-GiSTインデックスを構築するための文は次の通りです。
CREATE INDEX [インデックス名] ON [テーブル名] USING SPGIST ( [ジオメトリカラム] );
上の文では、2次元インデックスを構築します。ジオメトリ型の3次元インデックスは、次のように、3次元演算子クラスを使用して生成します。
CREATE INDEX [インデックス名] ON [テーブル名] USING SPGIST ([ジオメトリカラム] spgist_geometry_ops_3d);
空間インデックスの構築は、計算量を集中させて行われます。また、この時には、テーブルへの書き込みアクセスがブロックされます。そのため、本番システムでは、より遅いCONCURRENTLYを選択するかも知れません。次のようにします。
CREATE INDEX CONCURRENTLY [インデックス名] ON [テーブル名] USING SPGIST ( [ジオメトリカラム] );
インデックス構築後に、時々PostgreSQLにテーブルの統計情報を集めさせると助かります。クエリプランの最適化に使われます。
VACUUM ANALYZE [テーブル名] [(カラム名)];
SP-GiSTインデックスは次の演算子を含むクエリの実行速度を向上させられます。
2次元インデックスについては <<, &<, &>, >>, <<|, &<|, |&>, |>>, &&, @>, <@, and ~= 。
3次元インデックスについては &/&, ~==, @>>, and <<@ 。
現時点ではkNN探索に対応していません。
通常、インデックスは知らないうちにデータアクセスの速度を向上します。ひとたびインデックスを構築すれば、PostgreSQLクエリプランナは自動的にクエリの能率を向上させるために使うべきかどうかを決定します。しかし、プランナが既存のインデックスを選択せず、遅いシーケンシャルスキャンを使い続ける場合があります。
空間インデックスが使われていないのが分かった場合には、少しの行えることがあります。
クエリプランの試験とクエリの確認で、必要なものを計算できます。誤ったJOINや忘れ去られたテーブルや間違ったテーブルでは、予期しないテーブルレコード検索が複数回行われることがありえます。クエリプランを得るにはクエリの先頭にEXPLAIN
を付けて実行します。
テーブル内の値の数量と分布に関する統計情報を収集するとともに、クエリプランナにインデックス使用にかかる意思決定のための、より良い情報を与えるようにします。VACUUM ANALYZEは両方を計算します。
データベースに対する定期的なvacuumは常に実行するべきです。多くのPostgreSQLデータベースエージェントは、閑散時のcronジョブとして定期的にVACUUMを実行します。
VACUUMが役に立たない場合には、SET ENABLE_SEQSCAN TO OFF;コマンドを使用して、一時的にプランナにインデックス情報の使用を強制することができます。この方法で、プランナがインデックス使用を多くしたクエリプランを生成できるかどうかを確認できます。このコマンドはデバッグにのみ使用してください。一般的に言えば、プランナはインデックスを使用するタイミングをよく知っています。クエリを実行したらSET ENABLE_SEQSCAN TO ON;を実行して、他のクエリでは通常操作にすることを忘れないでください。
SET ENABLE_SEQSCAN TO OFF;でクエリ速度が向上する場合には、PostgreSQLのハードウェア関連のチューンが行われていないのかも知れません。プランナがシーケンシャル対インデックスのコストが誤っている場合には、postgresql.conf
内にあるRANDOM_PAGE_COST
の値を変更してみて下さい。SET RANDOM_PAGE_COST TO 1.1;とします。RANDOM_PAGE_COST
のデフォルト値は4.0です。1.1 (SSDの場合)または2.0 (高速磁気ディスクの場合)を試してみて下さい。値を小さくするほど、プランナがインデックススキャンをしやすくなります。
SET ENABLE_SEQSCAN TO OFF;がクエリの助けにならないなら、クエリはPostgreSQLプランナがまだ最適化できないSQL構成なのかも知れません。プランナが処理できるようにクエリを再記述できるかもしれません。例えば、インラインSELECTを持つ副問い合わせがあると、効果的なプランを作らないことがあり、LATERAL JOINを使うように書き換えることができます。
詳細情報についてはPostgreSQLマニュアルの問い合わせ計画節をご覧下さい。
The raison d'etre of spatial databases is to perform queries inside the database which would ordinarily require desktop GIS functionality. Using PostGIS effectively requires knowing what spatial functions are available, how to use them in queries, and ensuring that appropriate indexes are in place to provide good performance.
Spatial relationships indicate how two geometries interact with one another. They are a fundamental capability for querying geometry.
According to the OpenGIS Simple Features Implementation Specification for SQL, "the basic approach to comparing two geometries is to make pair-wise tests of the intersections between the Interiors, Boundaries and Exteriors of the two geometries and to classify the relationship between the two geometries based on the entries in the resulting 'intersection' matrix."
In the theory of point-set topology, the points in a geometry embedded in 2-dimensional space are categorized into three sets:
The boundary of a geometry is the set of geometries of the next lower dimension. For POINT
s, which have a dimension of 0, the boundary is the empty set. The boundary of a LINESTRING
is the two endpoints. For POLYGON
s, the boundary is the linework of the exterior and interior rings.
The interior of a geometry are those points of a geometry that are not in the boundary. For POINT
s, the interior is the point itself. The interior of a LINESTRING
is the set of points between the endpoints. For POLYGON
s, the interior is the areal surface inside the polygon.
The exterior of a geometry is the rest of the space in which the geometry is embedded; in other words, all points not in the interior or on the boundary of the geometry. It is a 2-dimensional non-closed surface.
The Dimensionally Extended 9-Intersection Model (DE-9IM) describes the spatial relationship between two geometries by specifying the dimensions of the 9 intersections between the above sets for each geometry. The intersection dimensions can be formally represented in a 3x3 intersection matrix.
For a geometry g the Interior, Boundary, and Exterior are denoted using the notation I(g), B(g), and E(g). Also, dim(s) denotes the dimension of a set s with the domain of {0,1,2,F}
:
0
=> point
1
=> line
2
=> area
F
=> empty set
Using this notation, the intersection matrix for two geometries a and b is:
Interior | Boundary | Exterior | |
---|---|---|---|
Interior | dim( I(a) ∩ I(b) ) | dim( I(a) ∩ B(b) ) | dim( I(a) ∩ E(b) ) |
Boundary | dim( B(a) ∩ I(b) ) | dim( B(a) ∩ B(b) ) | dim( B(a) ∩ E(b) ) |
Exterior | dim( E(a) ∩ I(b) ) | dim( E(a) ∩ B(b) ) | dim( E(a) ∩ E(b) ) |
Visually, for two overlapping polygonal geometries, this looks like:
| ||||||||||||||||||
|
|
Reading from left to right and top to bottom, the intersection matrix is represented as the text string '212101212'.
For more information, refer to:
To make it easy to determine common spatial relationships, the OGC SFS defines a set of named spatial relationship predicates. PostGIS provides these as the functions ???, ???, ???, ???, ???, ???, ???, ???. It also defines the non-standard relationship predicates ???, ???, and ???.
Spatial predicates are usually used as conditions in SQL WHERE
or JOIN
clauses. The named spatial predicates automatically use a spatial index if one is available, so there is no need to use the bounding box operator &&
as well. For example:
SELECT city.name, state.name, city.geom FROM city JOIN state ON ST_Intersects(city.geom, state.geom);
For more details and illustrations, see the PostGIS Workshop.
In some cases the named spatial relationships are insufficient to provide a desired spatial filter condition.
![]() For example, consider a linear dataset representing a road network. It may be required to identify all road segments that cross each other, not at a point, but in a line (perhaps to validate some business rule). In this case ??? does not provide the necessary spatial filter, since for linear features it returns A two-step solution would be to first compute the actual intersection (???) of pairs of road lines that spatially intersect (???), and then check if the intersection's ST_GeometryType is ' Clearly, a simpler and faster solution is desirable. |
![]() A second example is locating wharves that intersect a lake's boundary on a line and where one end of the wharf is up on shore. In other words, where a wharf is within but not completely contained by a lake, intersects the boundary of a lake on a line, and where exactly one of the wharf's endpoints is within or on the boundary of the lake. It is possible to use a combination of spatial predicates to find the required features:
|
These requirements can be met by computing the full DE-9IM intersection matrix. PostGIS provides the ??? function to do this:
SELECT ST_Relate( 'LINESTRING (1 1, 5 5)', 'POLYGON ((3 3, 3 7, 7 7, 7 3, 3 3))' ); st_relate ----------- 1010F0212
To test a particular spatial relationship, an intersection matrix pattern is used. This is the matrix representation augmented with the additional symbols {T,*}
:
T
=> intersection dimension is non-empty; i.e. is in {0,1,2}
*
=> don't care
Using intersection matrix patterns, specific spatial relationships can be evaluated in a more succinct way. The ??? and the ??? functions can be used to test intersection matrix patterns. For the first example above, the intersection matrix pattern specifying two lines intersecting in a line is '1*1***1**':
-- Find road segments that intersect in a line SELECT a.id FROM roads a, roads b WHERE a.id != b.id AND a.geom && b.geom AND ST_Relate(a.geom, b.geom, '1*1***1**');
For the second example, the intersection matrix pattern specifying a line partly inside and partly outside a polygon is '102101FF2':
-- Find wharves partly on a lake's shoreline SELECT a.lake_id, b.wharf_id FROM lakes a, wharfs b WHERE a.geom && b.geom AND ST_Relate(a.geom, b.geom, '102101FF2');
When constructing queries using spatial conditions, for best performance it is important to ensure that a spatial index is used, if one exists (see Section 4.9, “Spatial Indexes”). To do this, a spatial operator or index-aware function must be used in a WHERE
or ON
clause of the query.
Spatial operators include the bounding box operators (of which the most commonly used is &&; see Section 8.8.1, “Bounding Box Operators” for the full list) and the distance operators used in nearest-neighbor queries (the most common being <->; see Section 8.8.2, “演算子” for the full list.)
Index-aware functions automatically add a bounding box operator to the spatial condition. Index-aware functions include the named spatial relationship predicates ???, ???, ???, ???, ???, ???, ???, ???, ???, ???, and ???, and the distance predicates ???, ???, ???, and ??? .)
Functions such as ST_Distance do not use indexes to optimize their operation. For example, the following query would be quite slow on a large table:
SELECT geom FROM geom_table WHERE ST_Distance( geom, 'SRID=312;POINT(100000 200000)' ) < 100
This query selects all the geometries in geom_table
which are within 100 units of the point (100000, 200000). It will be slow because it is calculating the distance between each point in the table and the specified point, ie. one ST_Distance()
calculation is computed for every row in the table.
The number of rows processed can be reduced substantially by using the index-aware function ???:
SELECT geom FROM geom_table WHERE ST_DWithin( geom, 'SRID=312;POINT(100000 200000)', 100 )
This query selects the same geometries, but it does it in a more efficient way. This is enabled by ST_DWithin()
using the &&
operator internally on an expanded bounding box of the query geometry. If there is a spatial index on the_geom
, the query planner will recognize that it can use the index to reduce the number of rows scanned before calculating the distance. The spatial index allows retrieving only records with geometries whose bounding boxes overlap the expanded extent and hence which might be within the required distance. The actual distance is then computed to confirm whether to include the record in the result set.
For more information and examples see the PostGIS Workshop.
The examples in this section will make use of two tables, a table of linear roads, and a table of polygonal municipality boundaries. The table definitions for the bc_roads
table is:
Column | Type | Description ------------+-------------------+------------------- gid | integer | Unique ID name | character varying | Road Name the_geom | geometry | Location Geometry (Linestring)
The table definition for the bc_municipality
table is:
Column | Type | Description -----------+-------------------+------------------- gid | integer | Unique ID code | integer | Unique ID name | character varying | City / Town Name the_geom | geometry | Location Geometry (Polygon)
現版のPostgreSQL (9.6を含む)では、TOASTテーブルに従うクエリオプティマイザの弱さに苦しみます。 TOASTテーブルは、(長いテキスト、イメージ、多数の頂点を持つ複合ジオメトリといった)通常のデータページに適合しない、(データサイズという意味では)巨大な値を納めるための「拡張部屋」の一種です。詳細情報は the PostgreSQL Documentation for TOASTをご覧ください。
(高解像度で全てのヨーロッパの国の境界を含むテーブルのような)大きなジオメトリがあるうえ、行がそう多くないテーブルを持つようになると、この問題が出てきます。テーブル自体は小さいのですが、多くのTOASTスペースを使います。例として、テーブル自体は概ね80行で3データページしか使わなくてもTOASTテーブルで8225ページを使うとします。
ここで、ジオメトリ演算子の&&を使って、ほとんどマッチしないようなバウンダリボックスを検索するクエリを出してみます。クエリオプティマイザにはテーブルは3ページ80行しかないように見えます。オプティマイザは、小さなテーブルを順に走査する方がインデクスを使うよりも早いと見積もります。そして、GiSTインデクスは無視すると決めます。通常なら、この見積もりは正しいです。しかし、この場合は&&演算子が全てのジオメトリをディスクから呼び出してバウンディングボックスと比較しなければならなくなり、ゆえに、全てのTOASTページもまた呼び出す必要があります。
この問題に苦しむかどうかを見るには、PostgreSQLの"EXPLAIN ANALYZE"コマンドを使います。詳細情報と技術情報については、PostgreSQL性能メーリングリストのスレッドhttp://archives.postgresql.org/pgsql-performance/2005-02/msg00030.phpをご覧下さい。
また、PostGISの新しいスレッドhttps://lists.osgeo.org/pipermail/postgis-devel/2017-June/026209.htmlもご覧下さい。
PostgreSQLコミュニティでは、TOASTを意識したクエリ見積もりを作ることで、この問題を解決しようとしています。今のところは、二つの応急処置があります。
一つは、クエリプランナにインデクスの使用を強制することです。クエリを発行する前に"SET enable_seqscan TO off;"をサーバに送信します。これは基本的にクエリプランナに対して可能な限り順に走査することを避けるよう強制します。そのためGiSTインデクスを通常使うようになります。しかし、このフラグは接続するたびに設定しなければならず、他のケースにおいてはクエリプランナに誤った見積もりをさせることになるので、 "SET enable_seqscan TO on;"をクエリの後に送信すべきです。
もう一つは、順に走査することをクエリプランナが考える程度に早くすることです。これは、バウンダリボックスの「キャッシュ」を行う追加カラムを作成し、このカラムにマッチさせるようにすることで達成することができます。ここでの例では次のようになります。
SELECT AddGeometryColumn('myschema','mytable','bbox','4326','GEOMETRY','2'); UPDATE mytable SET bbox = ST_Envelope(ST_Force2D(the_geom));
そして、次のように、&&演算子をgeom_columnに対して行っていたものをbboxに変更します。
SELECT geom_column FROM mytable WHERE bbox && ST_SetSRID('BOX3D(0 0,1 1)'::box3d,4326);
もちろん、mytableの行を変更または追加したら、bboxを「同期」するようにしなければなりません。最もすっきりした方法はトリガです。もしくは、アプリケーションを変更してbboxカラムの現状を保持するか、テーブル更新後にいつもUPDATEクエリを実行するかでも対応できます。
読み込むことがほとんどで、かつほとんどのクエリでひとつのインデクスを使うようなテーブルのために、PostgreSQLはCLUSTERコマンドを提供しています。このコマンドは、全てのデータ行を、インデクス基準にあわせて物理的に再整理するので、二つの性能の利点を生みます。一つは、インデクスの範囲走査のために、データテーブルのシーク回数が劇的に減少することです。もう一つは、いくつかの小さなインデクス間隔に集中する場合には、データ行が分布するデータページがより少なくなるので、より効率的なキャッシュを持つことです (この点で、PostgreSQLマニュアルのCLUSTERコマンドのドキュメントを読むように仕向けられていると感じて下さい)。
しかし、GiSTインデクスは単純にNULL値を無視するため現在のところPostGISのGiSTインデクスのクラスタリングはできず、次のようなエラーメッセージを得ます。
lwgeom=# CLUSTER my_geom_index ON my_table; ERROR: cannot cluster when index access method does not handle null values (エラー: インデクスアクセスメソッドがNULL値を扱わない場合クラスタ化できません) HINT: You may be able to work around this by marking column "the_geom" NOT NULL. (ヒント: 列"the_geom"をNOT NULLとすることで、これを回避できるかもしれません)
ヒントメッセージにある通り、テーブルに"not null"制限を追加することで、この欠陥にとりあえず対応できます。例を示します。
lwgeom=# ALTER TABLE my_table ALTER COLUMN the_geom SET not null; ALTER TABLE
もちろん、ジオメトリカラムで実際にNULL値が必要な場合、この対応はできません。さらには、制限を追加するには上の方法を使わなければならず、"ALTER TABLE blubb ADD CHECK (geometry is not null);"のようなCHECK制限は使えません。
ときどき、テーブルで3次元、4次元のデータを持つのに、常にOpenGIS準拠のST_AsText()またはST_AsBinary()関数を使ってアクセスして 2次元ジオメトリを出力させるようなことが起きます。内部でST_Force_2d()関数を呼んでいるために発生しますが、これは、大きなジオメトリでは重大なオーバヘッドを誘引することになります。このオーバヘッドを回避するには、一度追加された次元を前もって落とし、かつこれを永続化するのが適当かも知れません。
UPDATE mytable SET the_geom = ST_Force2D(the_geom); VACUUM FULL ANALYZE mytable;
AddGeometryColumn()を使ってジオメトリカラムを追加した場合、ジオメトリの次元に関する制限があることに注意してください。この制限を迂回するには、制限の削除が必要になります。geometry_columnsテーブル内のエントリを更新して、その後で制限を再作成することを忘れないで下さい。
大きなテーブルの場合、WHERE節、およびプライマリキー若しくは他の適切な基準によってテーブルの一部へのUPDATEを制限させて、UPDATEの実行の間に単に"VACUUM;"と実行することで、UPDATEをより小さい塊に分割するのが賢いやり方かもしれません。これにより、テンポラリディスクスペースが劇的に減少します。さらに、次元混合のジオメトリを持つ場合、"WHERE dimension(the_geom)>2"によってUPDATEを制限することで、2次元で書かれているジオメトリの再書き込みをスキップさせることができます。
Minnesota MapServerはOpenGIS Web Mapping Server仕様を満たすウェブマッピングサーバです。
MapServerのウェブサイトはhttp://mapserver.org/です。
The OpenGIS Web Map Specificationはhttp://www.opengeospatial.org/standards/wmsにあります。
MapServerでPostGISを使うには、MapServerのコンフィギュレーション方法についての知識が必要ですが、この文書の範囲外です。この節では、PostGIS特有の問題とコンフィギュレーション詳細について記載します。
PostGISをMapServerで使うには、次のものが必要です。
PostGIS 0.6以上
MapServer 3.5以上
MapServerは、他のクライアントのように、libpq
インタフェースを使って、PostGIS/PostgreSQLデータにアクセスします。よってMapServerはPostGISサーバにアクセスするネットワークを持つ計算機にインストールでき、PostGISをデータソースとして使用することができます。システム間の接続は速いほど良いです。
"--with-postgis"と好きなconfigureオプションを付けてMpaServerのコンパイルとインストールを行います。
Mapserverのmapファイルの中に、PostGISレイヤを追加します。たとえば次のようになります。
LAYER CONNECTIONTYPE postgis NAME "widehighways" # リモートの空間データベースに接続します CONNECTION "user=dbuser dbname=gisdatabase host=bigserver" PROCESSING "CLOSE_CONNECTION=DEFER" # 'roads'テーブルの'geom'カラムからラインを取得します DATA "geom from roads using srid=4326 using unique gid" STATUS ON TYPE LINE # 範囲内のラインである広い高速道路のみ描画します FILTER "type = 'highway' and numlanes >= 4" CLASS # 非常に広い高速道路はより明るい色かつ2ピクセル幅にします EXPRESSION ([numlanes] >= 6) STYLE COLOR 255 22 22 WIDTH 2 END END CLASS # 残りは、暗い色かつ1ピクセル幅です EXPRESSION ([numlanes] < 6) STYLE COLOR 205 92 82 END END END
上の例におけるPostGIS特有のディレクティブは次の通りです。
PostGISレイヤでは常に"postgis"とします。
データベース接続は「接続文字列」によって制御されます。接続文字列は、次に示すような標準的なキーと値からなります(<>内はデフォルト値)。
user=<ユーザ名> password=<パスワード> dbname=<ユーザ名> hostname=<サーバ> port=<5432>
空の接続文字列も妥当とされますし、あらゆるキーと値のペアは省略できます。接続するためには一般的にはdbnameとusernameとが最少で与えるものとなります。
このパラメータの形式は "<カラム名> from <テーブル名> using srid=<SRID> using unique <主キー>"となります。ここで、カラム名は地図に描画したい空間カラムを指し、SRIDはそのカラムで使われるSRIDで、主キーはそのテーブルの主キー (またはインデックスを伴う一意の値を持つカラム)です。
"using srid"と"using unique"節は省略できます。MapServerは可能なら自動的に正しい値を判断しますが、地図を描画するサーバ上で余分なクエリを若干実行するコストがかかります。
接続を閉じずに複数のレイヤで再利用する場合にCLOSE_CONNECTION=DEFERとします。速度が改善します。詳細な説明についてはMapServer PostGIS Performance Tipsを参照して下さい。
フィルタは、妥当なSQL文字列でなければなりません。この文字列は、通常はSQLクエリにおける"WHERE"に続く論理式に対応します。たとえば、6レーン以上の道路だけを描画する場合には、"num_lanes >= 6"というフィルタを使います。
空間データベースにおいては、空間 (GiST)インデックスを、マップに描かれるレイヤ全てに構築していることを保証して下さい。
CREATE INDEX [インデックス名] ON [テーブル名] USING GIST ( [ジオメトリカラム] );
MapServerを使用するレイヤのクエリを実行する場合には、"using unique"節もDATAステートメントに追加しなければなりません。
MapServerでは、クエリ実行の際には、それぞれの空間レコードを識別するための一意な識別子が必要です。MapServerのPostGISモジュールは、一意な識別子を提供するために、ユーザ指定の一意な値を使います。テーブルの主キーを使うのが最も良い方法です。
USING
疑似SQL節を使ってMapServerがより複雑なクエリの結果を理解できるようにするための情報を追加します。より詳しく言うと、ビューまたは副問い合わせが元テーブル (DATA
定義で"FROM"の右にあるもの)として使われる時、MapServerが自動的に一意な識別子がそれぞれの行にあるか、また、SRIDがテーブルにあるかを判別するのは困難です。USING
節によって、MapServerがこれらの情報を得ることができます。例を次に挙げます。
DATA "geom FROM ( SELECT table1.geom AS geom, table1.gid AS gid, table2.data AS data FROM table1 LEFT JOIN table2 ON table1.id = table2.id ) AS new_table USING UNIQUE gid USING SRID=4326"
MapServerは、マップクエリを実行する際、行識別のために、それぞれの行に一意な識別子を求めます。通常ならシステムテーブルから主キーを識別しますが、ビューや副問い合わせでは、一意性のあるカラムを自動的に知ることができません。MapServerのクエリ機能を使いたいなら、一意性のあるカラムをビューまたは副問い合わせに追加する必要があり、USING UNIQUE
宣言を付ける必要があります。たとえば、この目的のための主キー値のテーブルでのカラム名や、結果セットで一意性が保障されたカラムを明示的にSELECTに入れることができます。
![]() | |
「マップクエリ」はマップ上でクリックして、その場所におけるフィーチャーに関する情報を問い合わせる動作です。「マップクエリ」と |
PostGISは、MapServerに正しいデータを返すために、ジオメトリがどの空間参照系を使っているかを知る必要があります。通常は、この情報はPostGISデータベースの"geometry_columns"テーブルから得ることができます。しかし、副問い合わせやビューのような一時テーブルでは、この方法は不可能です。そこで、 USING SRID=
オプションを使って、正しいSRIDがDATA
定義で使われるように指定します。
簡単な例から始めて、ステップアップしていきましょう。次のMapServerレイヤ定義を考えて下さい。
LAYER CONNECTIONTYPE postgis NAME "roads" CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" DATA "geom from roads" STATUS ON TYPE LINE CLASS STYLE COLOR 0 0 0 END END END
このレイヤは"roads"テーブルにある道路ジオメトリの全部を黒線で表示するものです。
では、少なくとも1:100000にズームするまでは高速道路だけを表示したい、としましょう。次の二つのレイヤで、その効果が実現できます。
LAYER CONNECTIONTYPE postgis CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" PROCESSING "CLOSE_CONNECTION=DEFER" DATA "geom from roads" MINSCALE 100000 STATUS ON TYPE LINE FILTER "road_type = 'highway'" CLASS COLOR 0 0 0 END END LAYER CONNECTIONTYPE postgis CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" PROCESSING "CLOSE_CONNECTION=DEFER" DATA "geom from roads" MAXSCALE 100000 STATUS ON TYPE LINE CLASSITEM road_type CLASS EXPRESSION "highway" STYLE WIDTH 2 COLOR 255 0 0 END END CLASS STYLE COLOR 0 0 0 END END END
一つ目のレイヤはスケールが1:100000以上であるときに使われ、道路タイプが"highway"である道路のみ黒線で表示されます。FILTER
オプションによって、道路タイプが"highway"の場合のみ表示することになります。
二つ目のレイヤはスケールが1:100000未満である時に使われ、"highway"は赤い二重細線で表示され、他の道路は黒線で表示されます。
さて、MapServerの機能を使うだけで、二つのおもしろいことを実行しました。しかし、DATA
のSQLステートメントは、単純なままです。道路名が (どういう理由かは知りませんが)他のテーブルに収められていて、それのデータを取得するためにテーブルを連結して、道路のラベルを取る必要がある、とします。
LAYER CONNECTIONTYPE postgis CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" DATA "geom FROM (SELECT roads.gid AS gid, roads.geom AS geom, road_names.name as name FROM roads LEFT JOIN road_names ON roads.road_name_id = road_names.road_name_id) AS named_roads USING UNIQUE gid USING SRID=4326" MAXSCALE 20000 STATUS ON TYPE ANNOTATION LABELITEM name CLASS LABEL ANGLE auto SIZE 8 COLOR 0 192 0 TYPE truetype FONT arial END END END
このANNOTAIONレイヤでは、縮尺が1:20000以下のときに、全ての道路に緑色のラベルを表示します。また、この例は、 DATA
定義で、SQLのJOINを使用する方法も示しています。
Javaクライアントは、直接的にテキスト表現として、またはPostGISに同梱されているJDBC拡張オブジェクトを使用して、PostgreSQLデータベース内にある、PostGISの"geometry"オブジェクトにアクセスできます。JDBC拡張オブジェクトを使うためには、"postgis.jar"ファイルを、JDBCドライバパッケージの"postgresql.jar"とともに、 CLASSPATHに置く必要があります。
import java.sql.*; import java.util.*; import java.lang.*; import org.postgis.*; public class JavaGIS { public static void main(String[] args) { java.sql.Connection conn; try { /* * JDBCドライバをロードして接続を確立します。 */ Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost:5432/database"; conn = DriverManager.getConnection(url, "postgres", ""); /* * ジオメトリ型を接続に追加します。 * ご注意 : addDateType()を呼ぶ前に * 接続をpgsql特有の接続実装にキャストしなければなりません。 */ ((org.postgresql.PGConnection)conn).addDataType("geometry",Class.forName("org.postgis.PGgeometry")); ((org.postgresql.PGConnection)conn).addDataType("box3d",Class.forName("org.postgis.PGbox3d")); /* * ステートメントの生成とSELECTクエリの実行を行います。 */ Statement s = conn.createStatement(); ResultSet r = s.executeQuery("select geom,id from geomtable"); while( r.next() ) { /* * ジオメトリをオブジェクトとして検索してジオメトリ型にキャストします。 * オブジェクトを印字します */ PGgeometry geom = (PGgeometry)r.getObject(1); int id = r.getInt(2); System.out.println("Row " + id + ":"); System.out.println(geom.toString()); } s.close(); conn.close(); } catch( Exception e ) { e.printStackTrace(); } } }
"PGeometry"オブジェクトは、Point、LineString、Polygon、MultiPoint、MultiLineString、MultiPolygonの各型に依存する、特定のトポロジカルジオメトリオブジェクト ("Geometory"抽象クラスの子クラス)を持つラッパオブジェクトです。
PGgeometry geom = (PGgeometry)r.getObject(1); if( geom.getType() == Geometry.POLYGON ) { Polygon pl = (Polygon)geom.getGeometry(); for( int r = 0; r < pl.numRings(); r++) { LinearRing rng = pl.getRing(r); System.out.println("Ring: " + r); for( int p = 0; p < rng.numPoints(); p++ ) { Point pt = rng.getPoint(p); System.out.println("Point: " + p); System.out.println(pt.toString()); } } }
幾何オブジェクトのさまざまなデータアクセサ関数に関する参照情報については、拡張オブジェクトのJavaDocをご覧下さい。
ここで示す関数はPostGISユーザが必要とすると思われる関数です。この他に、一般的なユーザが使わないPostGISオブジェクトに対して求められるサポート関数があります。
![]() | |
PostGISは、既存の名前付け方針からSQL-MM中心の方針への切り替えを開始しています。結果として、ユーザが知っていて愛用している関数の多くが標準空間型 (ST) プレフィクスを使うように名前変更されました。以前の関数はまだ有効ですが、更新された等価な関数があるものについては、この文書の一覧から外しています (訳注: 非推奨関数はPostGIS 2.0では基本的に外れています)。これらの関数は非推奨であり、将来のリリースでは削除されますので、*使わないでください*。 |
本節では、PostGISによってインストールされるPostgreSQLデータ型を挙げます。特にユーザ定義関数をデザインする際に大変重要なキャストの挙動を記載しています。
Each data type describes its type casting behavior. A type cast converts values of one data type into another type. PostgreSQL allows defining casting behavior for custom types, along with the functions used to convert type values. Casts can have automatic behavior, which allows automatic conversion of a function argument to a type supported by the function.
Some casts have explicit behavior, which means the cast must be specified using the syntax CAST(myval As sometype)
or myval::sometype
. Explicit casting avoids the issue of ambiguous casts, which can occur when using an overloaded function which does not support a given type. For example, a function may accept a box2d or a box3d, but not a geometry. Since geometry has an automatic cast to both box types, this produces an "ambiguous function" error. To prevent the error use an explicit cast to the desired box type.
All data types can be cast to text
, so this does not need to be specified explicitly.
box2d — The type representing a 2-dimensional bounding box.
box3d — The type representing a 3-dimensional bounding box.
box3dは、ジオメトリまたはジオメトリ集合を囲むボックスを表現するPostGIS空間データ型です。ST_3DExtentはbox3dオブジェクトを返します。
The representation contains the values xmin, ymin, zmin, xmax, ymax, zmax
. These are the minimum and maxium values of the X, Y and Z extents.
box3d
objects have a text representation which looks like BOX3D(1 2 3,5 6 5)
.
geometry_dump — A composite type used to describe the parts of complex geometry.
geometry_dump
is a composite data type containing the fields:
geom
- a geometry representing a component of the dumped geometry. The geometry type depends on the originating function.
path[]
- an integer array that defines the navigation path within the dumped geometry to the geom
component. The path array is 1-based (i.e. path[1]
is the first element.)
It is used by the ST_Dump*
family of functions as an output type to explode a complex geometry into its constituent parts.
postgis.backend — GEOSとSFCGALで重複する関数を提供するバックエンドです。GEOSまたはSFCGALを選択します。デフォルトはGEOSです。
このGUCはSFCGALサポートでPostGISをコンパイルした場合にのみ適切なものとなります。デフォルトでは、geos
バックエンドはGEOSとSFCGALが同じ名前の関数を持つ関数で使われます。この変数によって、SFCGALをリクエストを提供するバックエンドにすることができます。
Availability: 2.1.0
postgis.gdal_datapath — GDALのGDAL_DATAオプションの値を設定するためのコンフィギュレーションオプションです。設定しない場合には、GDAL_DATA環境変数が使われます。
GDALのGDAL_DATAオプションの値の設定に使うPostgreSQL GUC変数です。postgis.gdal_datapath
値は完全にGDALのデータファイルへの物理的なパスになるべきものです。
コンフィギュレーションオプションは、GDALのデータファイルパスがハードコーディングされていないWindowsプラットフォームのためにほとんど使われます。このオプションは、GDALのデータファイルがGDALの期待されているパスに無いときに設定します。
![]() | |
このオプションは、PostgreSQLのコンフィギュレーションファイルpostgresql.confで設定できます。コネクションまたはトランザクションでも設定できます。 |
Availability: 2.2.0
![]() | |
GDAL_DATAに関する追加情報報は、GDALのConfiguration Optionsにあります。 |
postgis.gdal_enabled_drivers — PostGIS環境でGDALドライバを有効にするコンフィギュレーションオプションです。GDALコンフィギュレーション変数GDAL_SKIPに影響を与えます。
PostGIS環境でGDALドライバを有効にするコンフィギュレーションオプションです。GDALコンフィギュレーション変数GDAL_SKIPに影響を与えます。このオプションは、PostgreSQLのコンフィギュレーションファイルpostgresql.confで設定できます。コネクションまたはトランザクションでも設定できます。
postgis.gdal_enabled_drivers
の初期値は、PostgreSQL開始プロセスに渡される、有効とするドライバの一覧からなる環境変数POSTGIS_GDAL_ENABLED_DRIVERS
によって設定されます。
有効にするGDALドライバは、ドライバの短縮名またはコードで指定します。ドライバの短縮名またはコードはGDAL Raster Formatsにあります。複数のドライバを指定するには、ドライバの間に一つの空白を置きます。
![]() | |
|
![]() | |
標準的なPostGISのインストールでは、 |
![]() | |
GDAL_SKIPに関する追加情報は、GDALのConfiguration Optionsにあります。 |
Availability: 2.2.0
postgis.gdal_enabled_drivers
の設定とリセット。
データベースへの新規接続にバックエンドを設定します。
ALTER DATABASE mygisdb SET postgis.gdal_enabled_drivers TO 'GTiff PNG JPEG';
サーバへの全ての新規接続のための、有効なドライバのデフォルトを設定します。スーパーユーザ権限とPostgreSQL 9.4以上が必要です。データベース、セッション、ユーザ設定によって上書きされます。
ALTER SYSTEM SET postgis.gdal_enabled_drivers TO 'GTiff PNG JPEG'; SELECT pg_reload_conf();
SET postgis.gdal_enabled_drivers TO 'GTiff PNG JPEG'; SET postgis.gdal_enabled_drivers = default;
全てのGDALドライバを有効にします。
SET postgis.gdal_enabled_drivers = 'ENABLE_ALL';
全てのGDALドライバを無効にします。
SET postgis.gdal_enabled_drivers = 'DISABLE_ALL';
postgis.enable_outdb_rasters — データベース外ラスタのバンドにアクセスできるようにする、真偽型のコンフィギュレーションオプション。
データベース外ラスタのバンドにアクセスできるようにする、真偽型のコンフィギュレーションオプションです。このオプションは、PostgreSQLのコンフィギュレーションファイルpostgresql.confで設定できます。コネクションまたはトランザクションでも設定できます。
postgis.enable_outdb_rasters
の初期値は、環境変数POSTGIS_ENABLE_OUTDB_RASTERS
が0でない値で、PostgreSQL開始プロセスに渡されることでで設定されます。
![]() | |
|
![]() | |
標準的なPostGISのインストールでは、 |
Availability: 2.2.0
postgis.enable_outdb_rasters
の設定とリセット。
SET postgis.enable_outdb_rasters TO True; SET postgis.enable_outdb_rasters = default; SET postgis.enable_outdb_rasters = True; SET postgis.enable_outdb_rasters = False;
Set for specific database
ALTER DATABASE mygisdb SET postgis.backend = sfcgal;
Setting for whole database cluster. You need to reconnect to the database for changes to take effect.
--writes to postgres.auto.conf ALTER SYSTEM postgis.enable_outdb_rasters = true; --Reloads postgres conf SELECT pg_reload_conf();
postgis.gdal_datapath — データベース外ラスタのバンドにアクセスできるようにする、真偽型のコンフィギュレーションオプション。
A string configuration to set options used when working with an out-db raster. Configuration options control things like how much space GDAL allocates to local data cache, whether to read overviews, and what access keys to use for remote out-db data sources.
Availability: 2.2.0
postgis.enable_outdb_rasters
の設定とリセット。
SET postgis.gdal_config_options = 'AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxx AWS_SECRET_ACCESS_KEY=yyyyyyyyyyyyyyyyyyyyyyyyyy';
Set postgis.gdal_vsi_options
just for the current transaction using the LOCAL
keyword:
SET LOCAL postgis.gdal_config_options = 'AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxx AWS_SECRET_ACCESS_KEY=yyyyyyyyyyyyyyyyyyyyyyyyyy';
AddGeometryColumn — ジオメトリカラムを空間テーブルから除去します。
text AddGeometryColumn(
varchar table_name, varchar column_name, integer srid, varchar type, integer dimension, boolean use_typmod=true)
;
text AddGeometryColumn(
varchar schema_name, varchar table_name, varchar column_name, integer srid, varchar type, integer dimension, boolean use_typmod=true)
;
text AddGeometryColumn(
varchar catalog_name, varchar schema_name, varchar table_name, varchar column_name, integer srid, varchar type, integer dimension, boolean use_typmod=true)
;
ジオメトリカラムを既存の属性テーブルに追加します。schema_name
はスキーマ名です。srid
はSPATIAL_REF_SYSテーブルのエントリを参照する整数でなければなりません。type
は'POLYGON'や'MULTILINESTRING'といった、ジオメトリタイプを示す文字でなければなりません。指定したスキーマが存在しない (または現在のsearch_pathからは見えない)場合、または指定したSRID、ジオメトリタイプもしくは次元が不正である場合はエラーが投げられます。
![]() | |
Changed: 2.0.0 geometry_columnsがシステムカタログを読むビューになったため、geometry_columnsを更新しないようになりました。デフォルトでは制約を生成せず、PostgreSQLの型修飾子を使います。この関数によるWGS 84のPOINTカラムの構築と Changed: 2.0.0 制約を使う必要がある場合には、 |
![]() | |
Changed: 2.0.0 ビューについては、geometry_columnsへの手動登録はできなくなりました。しかし、typmodテーブルジオメトリに対して構築されていて、かつラッパ関数が無いビューは、親テーブルカラムのtypmodの挙動を継承するので、正しく登録されます。他のジオメトリを出力するジオメトリ関数を使うビューについては、ビューのジオメトリカラムが正しく登録されるようにするため、typmodジオメトリへのキャストが必要です。Section 4.4.3, “手動でジオメトリカラムをgeometry_columnsに登録する”を参照して下さい。 |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
Enhanced: 2.0.0 use_typmod引数が導入されました。デフォルトでは制約を基にしたものでなくtypmodジオメトリカラムが生成されます。
-- データを保持するスキーマの生成 CREATE SCHEMA my_schema; -- 新しい単純なPostgreSQLテーブルの生成 CREATE TABLE my_schema.my_spatial_table (id serial); -- "id"カラムのみを持つ単純なテーブルの説明 postgis=# \d my_schema.my_spatial_table Table "my_schema.my_spatial_table" Column | Type | Modifiers --------+---------+------------------------------------------------------------------------- id | integer | not null default nextval('my_schema.my_spatial_table_id_seq'::regclass) -- テーブルにジオメトリカラムを追加\ SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom',4326,'POINT',2); -- 制約を基にした古い方法でPOINTカラムを追加 SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom_c',4326,'POINT',2, false); -- 制約を基にした古い方法でCURVEPOLYGONカラムを追加 SELECT AddGeometryColumn ('my_schema','my_spatial_table','geomcp_c',4326,'CURVEPOLYGON',2, false); -- 再度説明を表示し、新しいジオメトリカラムの追加を明らかにする \d my_schema.my_spatial_table addgeometrycolumn ------------------------------------------------------------------------- my_schema.my_spatial_table.geomcp_c SRID:4326 TYPE:CURVEPOLYGON DIMS:2 (1 row) Table "my_schema.my_spatial_table" Column | Type | Modifiers ----------+----------------------+------------------------------------------------------------------------- id | integer | not null default nextval('my_schema.my_spatial_table_id_seq'::regclass) geom | geometry(Point,4326) | geom_c | geometry | geomcp_c | geometry | Check constraints: "enforce_dims_geom_c" CHECK (st_ndims(geom_c) = 2) "enforce_dims_geomcp_c" CHECK (st_ndims(geomcp_c) = 2) "enforce_geotype_geom_c" CHECK (geometrytype(geom_c) = 'POINT'::text OR geom_c IS NULL) "enforce_geotype_geomcp_c" CHECK (geometrytype(geomcp_c) = 'CURVEPOLYGON'::text OR geomcp_c IS NULL) "enforce_srid_geom_c" CHECK (st_srid(geom_c) = 4326) "enforce_srid_geomcp_c" CHECK (st_srid(geomcp_c) = 4326) -- geometry_columnsビューにも新しいカラムが登録されています -- SELECT f_geometry_column As col_name, type, srid, coord_dimension As ndims FROM geometry_columns WHERE f_table_name = 'my_spatial_table' AND f_table_schema = 'my_schema'; col_name | type | srid | ndims ----------+--------------+------+------- geom | Point | 4326 | 2 geom_c | Point | 4326 | 2 geomcp_c | CurvePolygon | 4326 | 2
DropGeometryColumn — ジオメトリカラムを空間テーブルから除去します。
text DropGeometryColumn(
varchar table_name, varchar column_name)
;
text DropGeometryColumn(
varchar schema_name, varchar table_name, varchar column_name)
;
text DropGeometryColumn(
varchar catalog_name, varchar schema_name, varchar table_name, varchar column_name)
;
ジオメトリカラムを空間テーブルから除去します。schema_nameはgeometry_columnsテーブルの該当行のf_table_schemaフィールドと一致しなければならないことにご注意ください。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
![]() | |
Changed: 2.0.0 この関数は後方互換のためのものです。geometry_columnsは現在はシステムカタログに対するビューですので、他のテーブルのカラムと同じように |
SELECT DropGeometryColumn ('my_schema','my_spatial_table','geom'); ---- 結果出力 ---- dropgeometrycolumn ------------------------------------------------------ my_schema.my_spatial_table.geom effectively removed. -- PostGIS 2.0以上では標準的なALTER TABLEと上の例とは等価です -- 両方ともgeometry_columnsの登録を抹消します ALTER TABLE my_schema.my_spatial_table DROP column geom;
DropGeometryTable — テーブルとgeometry_columnsの当該テーブルへの参照の全てを削除します。
boolean DropGeometryTable(
varchar table_name)
;
boolean DropGeometryTable(
varchar schema_name, varchar table_name)
;
boolean DropGeometryTable(
varchar catalog_name, varchar schema_name, varchar table_name)
;
テーブルとgeometry_columnsの当該テーブルへの参照の全てを削除します。スキーマ対応版PostgreSQLではスキーマが与えられない場合はcurrent_schema()を使います。
![]() | |
Changed: 2.0.0で この関数は後方互換のためのものです。geometry_columnsは現在はシステムカタログに対するビューですので、他のテーブルのカラムと同じように |
Find_SRID — Returns the SRID defined for a geometry column.
text Populate_Geometry_Columns(
boolean use_typmod=true)
;
int Populate_Geometry_Columns(
oid relation_oid, boolean use_typmod=true)
;
Returns the integer SRID of the specified geometry column by searching through the GEOMETRY_COLUMNS table. If the geometry column has not been properly added (e.g. with the AddGeometryColumn function), this function will not work.
Populate_Geometry_Columns — Ensures geometry columns are defined with type modifiers or have appropriate spatial constraints.
text Populate_Geometry_Columns(
boolean use_typmod=true)
;
int Populate_Geometry_Columns(
oid relation_oid, boolean use_typmod=true)
;
ジオメトリカラムが型修飾子で定義されるか、適切な制約を持つことを確実にします。ジオメトリカラムがgeometry_columns
に正しく登録されることを確実にします。デフォルトでは、型修飾子によらないジオメトリカラムを型修飾子によるジオメトリカラムに変換します。以前の挙動にするにはuse_typmod=false
とします。
後方互換のためと、それぞれの子テーブルが異なるジオメトリタイプを持つテーブル継承といった空間テーブルにとって必要があるためとの二つの理由から、古いCHECK制約の挙動がなお有効になっています。古い挙動が必要な場合には、新しいオプション引数でuse_typmod=false
を渡す必要があります。これが実行されると、型修飾子なしのジオメトリカラムが生成され、三つの制約が定義されます。特に、これは、テーブルに属するすべてのジオメトリカラムが少なくとも三つの制約を持つことを意味します。
enforce_dims_the_geom
- あらゆるジオメトリが同じ次元を持つことを確実にします (ST_NDimsをご覧下さい)
enforce_geotype_the_geom
- あらゆるジオメトリが同じ型を持つことを確実にします (GeometryTypeをご覧下さい)
enforce_srid_the_geom
- あらゆるジオメトリが同じ投影法になることを確実にします (???をご覧下さい)
テーブルにoid
がある場合には、この関数はテーブルのジオメトリカラム全てについて、SRIDと次元とジオメトリタイプを判定して、必要に応じて制約を追加しようとします。 成功した場合には、geometry_columns
に適切な行が追加され、その他の場合には、例外が捕まえられ、問題を記述したエラーが通知されます。
ビューのoid
がある場合、テーブルの場合と同じで、SIRDと次元とジオメトリタイプを判定して、適切なエントリをgeometry_columns
テーブルに挿入しますが、制約の追加はされません。
パラメタの無い形式は、geometry_columns
の行を削除したうえで、全ての空間テーブルと空間ビューについて再挿入し、適切な空間制約をテーブルに追加する、パラメタ付きの形式の単純なラッパです。パラメタが無い形式は、検出したジオメトリカラムの数の要約とgeometry_columns
に挿入された行の数とを返します。パラメタ付きの形式は単純にgeometry_columns
に挿入された行の数を返します。
Availability: 1.4.0
Changed: 2.0.0 デフォルトでは、ジオメトリタイプの制限について、制約を確認する代わりに型修飾子を使います。新しいuse_typmod
をFALSEに設定して使うことで、制約確認を使用することができます。
Enhanced: 2.0.0 use_typmod
任意引数が導入されました。カラムが型修飾子で生成されるか制約チェックで作られるかの制御ができます。
CREATE TABLE public.myspatial_table(gid serial, geom geometry); INSERT INTO myspatial_table(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) ); -- 型修飾子を使います -- 動作するにはデータが存在していなければなりません SELECT Populate_Geometry_Columns('public.myspatial_table'::regclass); populate_geometry_columns -------------------------- 1 \d myspatial_table Table "public.myspatial_table" Column | Type | Modifiers --------+---------------------------+--------------------------------------------------------------- gid | integer | not null default nextval('myspatial_table_gid_seq'::regclass) geom | geometry(LineString,4326) |
-- カラムが型修飾子でないか、既に制約が存在している場合には制約を使います -- 動作するにはデータが存在していなければなりません CREATE TABLE public.myspatial_table_cs(gid serial, geom geometry); INSERT INTO myspatial_table_cs(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) ); SELECT Populate_Geometry_Columns('public.myspatial_table_cs'::regclass, false); populate_geometry_columns -------------------------- 1 \d myspatial_table_cs Table "public.myspatial_table_cs" Column | Type | Modifiers --------+----------+------------------------------------------------------------------ gid | integer | not null default nextval('myspatial_table_cs_gid_seq'::regclass) geom | geometry | Check constraints: "enforce_dims_geom" CHECK (st_ndims(geom) = 2) "enforce_geotype_geom" CHECK (geometrytype(geom) = 'LINESTRING'::text OR geom IS NULL) "enforce_srid_geom" CHECK (st_srid(geom) = 4326)
UpdateGeometrySRID — Updates the SRID of all features in a geometry column, and the table metadata.
text UpdateGeometrySRID(
varchar table_name, varchar column_name, integer srid)
;
text UpdateGeometrySRID(
varchar schema_name, varchar table_name, varchar column_name, integer srid)
;
text UpdateGeometrySRID(
varchar catalog_name, varchar schema_name, varchar table_name, varchar column_name, integer srid)
;
ジオメトリカラムの全てのフィーチャーのSRID、geometry_columnsメタデータとSRIDテーブル制約を更新します。スキーマ対応版pgsqlでは、スキーマが提供されていない場合には、この関数はcurrent_schema()を使うことにご注意下さい。
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
Insert geometries into roads table with a SRID set already using EWKT format:
COPY roads (geom) FROM STDIN; SRID=4326;LINESTRING(0 0, 10 10) SRID=4326;LINESTRING(10 10, 15 0) \.
この関数は、以前のSRIDに関係なく、道路テーブルのSRIDを4326に変更します。
SELECT UpdateGeometrySRID('roads','geom',4326);
上述の例と、このDDL手続き (訳注: DDLはData Definition Languageの略で、データ構造の操作を行う言語を指し、この場合は CREATE TABLEやALTER TABLE等が該当します)とは同じです。
ALTER TABLE roads ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 4326) USING ST_SetSRID(geom,4326);
ロードデータの変換座標系が誤りである (またはunknownになっている)けれどもWebメルカトルに一度の処理で変換したい場合、DDLで実行可能ですが、PostGIS管理関数では一度の処理ですむ等価なものはありません。
ALTER TABLE roads ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 3857) USING ST_Transform(ST_SetSRID(geom,4326),3857) ;
ST_GeomCollFromText — Creates a GeometryCollection or Multi* geometry from a set of geometries.
geometry ST_GeomFromGeoJSON(
text geomjson)
;
geometry ST_GeomFromGeoJSON(
json geomjson)
;
geometry ST_GeomFromGeoJSON(
jsonb geomjson)
;
Collects geometries into a geometry collection. The result is either a Multi* or a GeometryCollection, depending on whether the input geometries have the same or different types (homogeneous or heterogeneous). The input geometries are left unchanged within the collection.
Variant 1: accepts two input geometries
Variant 2: accepts an array of geometries
Variant 3: aggregate function accepting a rowset of geometries.
![]() | |
If any of the input geometries are collections (Multi* or GeometryCollection) ST_Collect returns a GeometryCollection (since that is the only type which can contain nested collections). To prevent this, use ST_Dump in a subquery to expand the input collections to their atomic elements (see example below). |
![]() | |
ST_Collect and ??? appear similar, but in fact operate quite differently. ST_Collect aggregates geometries into a collection without changing them in any way. ST_Union geometrically merges geometries where they overlap, and splits linestrings at intersections. It may return single geometries when it dissolves boundaries. |
Availability: 1.4.0 - ST_MakeLine(geomarray)が導入されました。ST_MakeLine集約関数はより多くのポイントをより早く扱うための強化が施されています。
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
Collect 2D points.
SELECT ST_AsText( ST_Collect( ST_GeomFromText('POINT(1 2)'), ST_GeomFromText('POINT(-2 3)') )); st_astext ---------- MULTIPOINT(1 2,-2 3)
Collect 3D points.
SELECT ST_AsEWKT( ST_Collect( ST_GeomFromEWKT('POINT(1 2 3)'), ST_GeomFromEWKT('POINT(1 2 4)') ) ); st_asewkt ------------------------- MULTIPOINT(1 2 3,1 2 4)
Collect curves.
SELECT ST_AsText( ST_Collect( 'CIRCULARSTRING(220268 150415,220227 150505,220227 150406)', 'CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)')); st_astext ------------------------------------------------------------------------------------ MULTICURVE(CIRCULARSTRING(220268 150415,220227 150505,220227 150406), CIRCULARSTRING(220227 150406,2220227 150407,220227 150406))
Using an array constructor for a subquery.
SELECT ST_Collect( ARRAY( SELECT geom FROM sometable ) );
Using an array constructor for values.
SELECT ST_AsText( ST_Collect( ARRAY[ ST_GeomFromText('LINESTRING(1 2, 3 4)'), ST_GeomFromText('LINESTRING(3 4, 4 5)') ] )) As wktcollect; --wkt collect -- MULTILINESTRING((1 2,3 4),(3 4,4 5))
ST_LineFromMultiPoint — マルチポイントジオメトリからラインストリングを生成します。
geometry ST_LineFromMultiPoint(
geometry aMultiPoint)
;
マルチポイントジオメトリからラインストリングを生成します。
X, Y, Mのポイントを生成する必要がある場合には、ST_MakePointMを使います。
This function supports 3d and will not drop the z-index.
ST_MakeEnvelope — 与えられた最小値と最大値から長方形ポリゴンを生成します。入力値はSRIDで指定された空間参照系でなければなりません。
geometry ST_MakeEnvelope(
double precision xmin, double precision ymin, double precision xmax, double precision ymax, integer srid=unknown)
;
与えられた最小値と最大値から長方形ポリゴンを生成します。入力値はSRIDで指定された空間参照系でなければなりません。SRIDが指定されない場合には、不明な空間参照系と仮定します。
Availability: 1.5
Enhanced: 2.0 SRID指定なしでエンベロープを指定できるようになりました。
ST_MakeLine — ポイント、マルチポイント、ラインジオメトリからラインストリングを生成します。
geometry ST_MakeLine(
geometry set geoms)
;
geometry ST_MakeLine(
geometry geom1, geometry geom2)
;
geometry ST_MakeLine(
geometry[] geoms_array)
;
Creates a LineString containing the points of Point, MultiPoint, or LineString geometries. Other geometry types cause an error.
Variant 1: accepts two input geometries
Variant 2: accepts an array of geometries
Variant 3: aggregate function accepting a rowset of geometries. To ensure the order of the input geometries use ORDER BY
in the function call, or a subquery with an ORDER BY
clause.
Repeated nodes at the beginning of input LineStrings are collapsed to a single point. Repeated points in Point and MultiPoint inputs are not collapsed. ST_RemoveRepeatedPoints can be used to collapse repeated points from the output LineString.
This function supports 3d and will not drop the z-index.
Availability: 2.3.0 - マルチポイントの入力要素に対応するようになりました。
Availability: 2.0.0 - ラインストリング入力要素が導入されました。
Availability: 1.4.0 - ST_MakeLine(geomarray)が導入されました。ST_MakeLine集約関数はより多くのポイントをより早く扱うための強化が施されています。
Create a line composed of two points.
SELECT ST_MakeLine(ARRAY(SELECT ST_Centroid(the_geom) FROM visit_locations ORDER BY visit_time)); -- 三つの3次元ポイントから3次元ラインを生成 SELECT ST_AsEWKT(ST_MakeLine(ARRAY[ST_MakePoint(1,2,3), ST_MakePoint(3,4,5), ST_MakePoint(6,6,6)])); st_asewkt ------------------------- LINESTRING(1 2 3,3 4 5,6 6 6)
与えられた二つの3次元ポイントジオメトリから定義されるBOX3Dを生成します。
SELECT ST_AsEWKT( ST_MakeLine(ST_MakePoint(1,2,3), ST_MakePoint(3,4,5) )); st_asewkt ------------------------- LINESTRING(1 2 3,3 4 5)
ポイント、マルチポイント、ラインジオメトリからラインストリングを生成します。
select ST_AsText( ST_MakeLine( 'LINESTRING(0 0, 1 1)', 'LINESTRING(2 2, 3 3)' ) ); st_astext ----------------------------- LINESTRING(0 0,1 1,2 2,3 3)
Create a line from an array formed by a subquery with ordering.
SELECT ST_MakeLine( ARRAY( SELECT ST_Centroid(geom) FROM visit_locations ORDER BY visit_time) );
Create a 3D line from an array of 3D points
SELECT ST_MakeLine(ARRAY(SELECT ST_Centroid(the_geom) FROM visit_locations ORDER BY visit_time)); -- 三つの3次元ポイントから3次元ラインを生成 SELECT ST_AsEWKT(ST_MakeLine(ARRAY[ST_MakePoint(1,2,3), ST_MakePoint(3,4,5), ST_MakePoint(6,6,6)])); st_asewkt ------------------------- LINESTRING(1 2 3,3 4 5,6 6 6)
この例では、GPS位置の順列を取り、ジオメトリフィールドがGPSポイントからなるラインストリングで行程順になるよう、行程ごとに一つのレコードを生成します。
Using aggregate ORDER BY
provides a correctly-ordered LineString.
SELECT gps.track_id, ST_MakeLine(gps.geom ORDER BY gps_time) As geom FROM gps_points As gps GROUP BY track_id;
Prior to PostgreSQL 9, ordering in a subquery can be used. However, sometimes the query plan may not respect the order of the subquery.
-- PostgreSQL 9.0より前の版 - これは普通に動きますが、 -- プランナが副問い合わせの並び順を尊重しない選択を発生させることがあります。 SELECT gps.gps_track, ST_MakeLine(gps.the_geom) As newgeom FROM (SELECT gps_track, gps_time, the_geom FROM gps_points ORDER BY gps_track, gps_time) As gps GROUP BY gps.gps_track;
ST_MakePoint — 2次元、XYZの3次元または4次元のポイントジオメトリを生成します。
geometry ST_Point(
float x_lon, float y_lat)
;
geometry ST_MakePointM(
float x, float y, float m)
;
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
2次元、XYZの3次元または4次元のポイントジオメトリを生成します。
X, Y, Mのポイントを生成する必要がある場合には、ST_MakePointMを使います。
2次元、XYZの3次元、4次元 (M値を持つジオメトリ)のポイントジオメトリを生成します。ST_MakePoint
はOGC準拠ではありませんが、一般的に???や???より速く、高精度です。また、WKTでなく生の座標値を持っている場合は扱いやすいです。
![]() | |
For geodetic coordinates, |
This function supports 3d and will not drop the z-index.
-- SRID不明のポイントを返します SELECT ST_MakePoint(-71.1043443253471, 42.3150676015829); -- WGS 84経度緯度とするポイントを返します。 SELECT ST_SetSRID(ST_MakePoint(-71.1043443253471, 42.3150676015829),4326); -- 3次元ポイント (たとえば標高を持つ)を返します SELECT ST_MakePoint(1, 2,1.5); -- ポイントのZ値を得ます SELECT ST_Z(ST_MakePoint(1, 2,1.5)); result ------- 1.5
ST_MakePointM — X, Y, M座標を持つポイントジオメトリを生成します。
geometry ST_MakePointM(
float x, float y, float m)
;
X, Y, M座標を持つポイントジオメトリを生成します。
X, Y, Mのポイントを生成する必要がある場合には、ST_MakePointMを使います。
![]() | |
For geodetic coordinates, |
Create point with unknown SRID.
SELECT ST_AsEWKT( ST_MakePointM(-71.1043443253471, 42.3150676015829, 10) ); st_asewkt ----------------------------------------------- POINTM(-71.1043443253471 42.3150676015829 10)
X, Y, M座標を持つポイントジオメトリを生成します。
SELECT ST_AsEWKT( ST_SetSRID( ST_MakePointM(-71.104, 42.315, 10), 4326)); st_asewkt --------------------------------------------------------- SRID=4326;POINTM(-71.104 42.315 10)
Get measure of created point.
SELECT ST_M( ST_MakePointM(-71.104, 42.315, 10) ); result ------- 10
ST_MakePolygon — Creates a Polygon from a shell and optional list of holes.
geometry ST_MakePolygon(
geometry linestring)
;
geometry ST_MakePolygon(
geometry outerlinestring, geometry[] interiorlinestrings)
;
与えられた外環で形成されるポリゴンを生成します。入力ジオメトリは閉じたラインストリングでなければなりません。
Variant 1: Accepts one shell LineString.
Variant 2: Accepts a shell LineString and an array of inner (hole) LineStrings. A geometry array can be constructed using the PostgreSQL array_agg(), ARRAY[] or ARRAY() constructs.
![]() | |
この関数はマルチラインストリングを受け付けません。ST_LineMergeまたはST_Dumpでラインストリングを生成して下さい。 |
This function supports 3d and will not drop the z-index.
エンコード化ポリラインからラインストリングを生成します。
SELECT ST_MLineFromText('MULTILINESTRING((1 2, 3 4), (4 5, 6 7))');
Create a Polygon from an open LineString, using ST_StartPoint and ST_AddPoint to close it.
SELECT ST_MakePolygon( ST_AddPoint(foo.open_line, ST_StartPoint(foo.open_line)) ) FROM ( SELECT ST_GeomFromText('LINESTRING(75 29,77 29,77 29, 75 29)') As open_line) As foo;
エンコード化ポリラインからラインストリングを生成します。
SELECT ST_AsEWKT( ST_MakePolygon( 'LINESTRING(75.15 29.53 1,77 29 1,77.6 29.5 1, 75.15 29.53 1)')); st_asewkt ----------- POLYGON((75.15 29.53 1,77 29 1,77.6 29.5 1,75.15 29.53 1))
Create a Polygon from a LineString with measures
SELECT ST_AsEWKT( ST_MakePolygon( 'LINESTRINGM(75.15 29.53 1,77 29 1,77.6 29.5 2, 75.15 29.53 2)' )); st_asewkt ---------- POLYGONM((75.15 29.53 1,77 29 1,77.6 29.5 2,75.15 29.53 2))
蟻の穴を持つドーナツの生成です。
SELECT ST_MakePolygon( ST_ExteriorRing(ST_Buffer(foo.line,10)), ARRAY[ST_Translate(foo.line,1,1), ST_ExteriorRing(ST_Buffer(ST_MakePoint(20,20),1)) ] ) FROM (SELECT ST_ExteriorRing(ST_Buffer(ST_MakePoint(10,10),10,10)) As line ) As foo;
Create a set of province boundaries with holes representing lakes. The input is a table of province Polygons/MultiPolygons and a table of water linestrings. Lines forming lakes are determined by using ST_IsClosed. The province linework is extracted by using ST_Boundary. As required by ST_MakePolygon
, the boundary is forced to be a single LineString by using ST_LineMerge. (However, note that if a province has more than one region or has islands this will produce an invalid polygon.) Using a LEFT JOIN ensures all provinces are included even if they have no lakes.
![]() | |
NULL配列をST_MakePolygonに渡すとNULLを返すのでCASEを使います。 |
SELECT p.gid, p.province_name, CASE WHEN array_agg(w.geom) IS NULL THEN p.geom ELSE ST_MakePolygon( ST_LineMerge(ST_Boundary(p.geom)), array_agg(w.geom)) END FROM provinces p LEFT JOIN waterlines w ON (ST_Within(w.geom, p.geom) AND ST_IsClosed(w.geom)) GROUP BY p.gid, p.province_name, p.geom;
Another technique is to utilize a correlated subquery and the ARRAY() constructor that converts a row set to an array.
SELECT p.gid, p.province_name, CASE WHEN ST_Accum(w.the_geom) IS NULL THEN p.the_geom ELSE ST_MakePolygon(ST_LineMerge(ST_Boundary(p.the_geom)), ST_Accum(w.the_geom)) END FROM provinces p LEFT JOIN waterlines w ON (ST_Within(w.the_geom, p.the_geom) AND ST_IsClosed(w.the_geom)) GROUP BY p.gid, p.province_name, p.the_geom; -- 上と同じ例ですが、相関副問い合わせと行集合を -- 配列に変換するPostgreSQL組み込み関数ARRAY()を使っています。 SELECT p.gid, p.province_name, CASE WHEN EXISTS(SELECT w.the_geom FROM waterlines w WHERE ST_Within(w.the_geom, p.the_geom) AND ST_IsClosed(w.the_geom)) THEN ST_MakePolygon(ST_LineMerge(ST_Boundary(p.the_geom)), ARRAY(SELECT w.the_geom FROM waterlines w WHERE ST_Within(w.the_geom, p.the_geom) AND ST_IsClosed(w.the_geom))) ELSE p.the_geom END As the_geom FROM provinces p;
ST_Point — 与えられた座標値のST_Pointを返します。ST_MakePointのOGC別名です。
geometry ST_Point(
float x_lon, float y_lat)
;
geometry ST_MakePointM(
float x, float y, float m)
;
与えられた座標値のST_Pointを返します。XとYを取るST_MakePointのMM対応の別名です。
![]() | |
For geodetic coordinates, |
This method implements the SQL/MM specification. SQL-MM 3: 6.1.2
SELECT CAST(ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326) As geography);
PostgreSQL also provides the ::
short-hand for casting
SELECT CAST(ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326) As geography);
If the point coordinates are not in a geodetic coordinate system (such as WGS84), then they must be reprojected before casting to a geography. In this example a point in Pennsylvania State Plane feet (SRID 2273) is projected to WGS84 (SRID 4326).
SELECT CAST(ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326) As geography);
ST_Point — 与えられた座標値のST_Pointを返します。ST_MakePointのOGC別名です。
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
ST_Point — 与えられた座標値のST_Pointを返します。ST_MakePointのOGC別名です。
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
ST_Point — 与えられた座標値のST_Pointを返します。ST_MakePointのOGC別名です。
geometry ST_MakeEnvelope(
double precision xmin, double precision ymin, double precision xmax, double precision ymax, integer srid=unknown)
;
ST_Polygon — Creates a Polygon from a LineString with a specified SRID.
geometry ST_Polygon(
geometry aLineString, integer srid)
;
Returns a polygon built from the given LineString and sets the spatial reference system from the srid
.
ST_Polygon is similar to ST_MakePolygon Variant 1 with the addition of setting the SRID.
, ST_MakePoint, ???
![]() | |
この関数はマルチラインストリングを受け付けません。ST_LineMergeまたはST_Dumpでラインストリングを生成して下さい。 |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 8.3.2
This function supports 3d and will not drop the z-index.
Create a 2D polygon.
SELECT ST_AsText( ST_Polygon('LINESTRING(75 29, 77 29, 77 29, 75 29)'::geometry, 4326) ); -- result -- POLYGON((75 29, 77 29, 77 29, 75 29))
Create a 3D polygon.
SELECT ST_AsEWKT( ST_Polygon( ST_GeomFromEWKT('LINESTRING(75 29 1, 77 29 2, 77 29 3, 75 29 1)'), 4326) ); -- result -- SRID=4326;POLYGON((75 29 1, 77 29 2, 77 29 3, 75 29 1))
ST_MakeEnvelope — Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system. By default, the bounds are the in EPSG:3857 using the standard range of the Web Mercator system (-20037508.342789, 20037508.342789). The optional bounds parameter can be used to generate envelopes for any tiling scheme: provide a geometry that has the SRID and extent of the initial "zoom level zero" square within which the tile system is to be inscribed.
The optional margin parameter can be used to grow a tile by the given percentage, e.g. margin=0.125 grows the tile by 12.5%, which is equivalent to buffer=512 when extent is 4096, as used in ST_AsMVTGeom. This is useful to create a tile buffer -- to include data lying outside of the tile's visible area, but whose existence affects current tile's rendering. For example, a city name (a geopoint) could be near an edge of a tile, but the text would need to render on two tiles, even though the geopoint is located in the visible area of just one tile. Using an expanded tile in a search would include the city geopoint for both tiles. Use negative value to shrink the tile instead. Values less than -0.5 are prohibited because that would eliminate the tile completely. Do not use margin with ST_AsMVTGeom(). See example in ST_AsMVT.
Enhanced: 2.0.0 SRID任意引数が追加されました。
Availability: 2.1.0
SELECT ST_AsText( ST_TileEnvelope(2, 1, 1) ); st_astext ------------------------------ POLYGON((-10018754.1713945 0,-10018754.1713945 10018754.1713945,0 10018754.1713945,0 0,-10018754.1713945 0)) SELECT ST_AsText( ST_TileEnvelope(3, 1, 1, ST_MakeEnvelope(-180, -90, 180, 90, 4326) ) ); st_astext ------------------------------------------------------ POLYGON((-135 45,-135 67.5,-90 67.5,-90 45,-135 45))
ST_HexagonGrid — Returns a set of hexagons and cell indices that completely cover the bounds of the geometry argument.
geometry ST_Point(
float x_lon, float y_lat)
;
Starts with the concept of a hexagon tiling of the plane. (Not a hexagon tiling of the globe, this is not the H3 tiling scheme.) For a given planar SRS, and a given edge size, starting at the origin of the SRS, there is one unique hexagonal tiling of the plane, Tiling(SRS, Size). This function answers the question: what hexagons in a given Tiling(SRS, Size) overlap with a given bounds.
The SRS for the output hexagons is the SRS provided by the bounds geometry.
Doubling or tripling the edge size of the hexagon generates a new parent tiling that fits with the origin tiling. Unfortunately, it is not possible to generate parent hexagon tilings that the child tiles perfectly fit inside.
Availability: 2.1.0
To do a point summary against a hexagonal tiling, generate a hexagon grid using the extent of the points as the bounds, then spatially join to that grid.
SELECT COUNT(*), hexes.geom FROM ST_HexagonGrid( 10000, ST_SetSRID(ST_EstimatedExtent('pointtable', 'geom'), 3857) ) AS hexes INNER JOIN pointtable AS pts ON ST_Intersects(pts.geom, hexes.geom) GROUP BY hexes.geom;
If we generate a set of hexagons for each polygon boundary and filter out those that do not intersect their hexagons, we end up with a tiling for each polygon.
Tiling states results in a hexagon coverage of each state, and multiple hexagons overlapping at the borders between states.
![]() | |
The LATERAL keyword is implied for set-returning functions when referring to a prior table in the FROM list. So CROSS JOIN LATERAL, CROSS JOIN, or just plain , are equivalent constructs for this example. |
SELECT admin1.gid, hex.geom FROM admin1 CROSS JOIN ST_HexagonGrid(100000, admin1.geom) AS hex WHERE adm0_a3 = 'USA' AND ST_Intersects(admin1.geom, hex.geom)
ST_Hexagon — Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon grid space.
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Uses the same hexagon tiling concept as ST_HexagonGrid, but generates just one hexagon at the desired cell coordinate. Optionally, can adjust origin coordinate of the tiling, the default origin is at 0,0.
Hexagons are generated with no SRID set, so use ??? to set the SRID to the one you expect.
Availability: 2.1.0
ST_SquareGrid — Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.
geometry ST_Point(
float x_lon, float y_lat)
;
Starts with the concept of a square tiling of the plane. For a given planar SRS, and a given edge size, starting at the origin of the SRS, there is one unique square tiling of the plane, Tiling(SRS, Size). This function answers the question: what grids in a given Tiling(SRS, Size) overlap with a given bounds.
The SRS for the output squares is the SRS provided by the bounds geometry.
Doubling or edge size of the square generates a new parent tiling that perfectly fits with the original tiling. Standard web map tilings in mercator are just powers-of-two square grids in the mercator plane.
Availability: 2.1.0
The grid will fill the whole bounds of the country, so if you want just squares that touch the country you will have to filter afterwards with ST_Intersects.
WITH grid AS ( SELECT (ST_SquareGrid(1, ST_Transform(geom,4326))).* FROM admin0 WHERE name = 'Canada' ) SELEcT ST_AsText(geom) FROM grid
To do a point summary against a square tiling, generate a square grid using the extent of the points as the bounds, then spatially join to that grid. Note the estimated extent might be off from actual extent, so be cautious and at very least make sure you've analyzed your table.
SELECT COUNT(*), squares.geom FROM pointtable AS pts INNER JOIN ST_SquareGrid( 1000, ST_SetSRID(ST_EstimatedExtent('pointtable', 'geom'), 3857) ) AS squares ON ST_Intersects(pts.geom, squares.geom) GROUP BY squares.geom
ST_Square — Returns a single square, using the provided edge size and cell coordinate within the square grid space.
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Uses the same square tiling concept as ST_SquareGrid, but generates just one square at the desired cell coordinate. Optionally, can adjust origin coordinate of the tiling, the default origin is at 0,0.
Squares are generated with no SRID set, so use ??? to set the SRID to the one you expect.
Availability: 2.1.0
ST_Geometry値の座標次元を返します。
ST_Geometry値の座標次元を返します。
geometry_dump
rows for the components of a geometry.ジオメトリについての要約文を返します。
ジオメトリについての要約文を返します。
geometry_dump
rows for the exterior and interior rings of a Polygon.LINESTRING
の始点と終点が一致する場合にTRUE
を返します。多面体サーフェスの場合は閉じているかどうか (ボリュームであるかどうか)を返します。 ST_Geometry値の座標次元を返します。
ジオメトリについての要約文を返します。
GeometryType — ST_Geometry値のジオメトリ型を返します。
text GeometryType(
geometry geomA)
;
ジオメトリ型を'LINESTRING', 'POLYGON', 'MULTIPOINT'などの文字列で返します。
OGC SPEC s2.1.1.1 - このジオメトリインスタンスがメンバーになっているジオメトリのインスタンス化可能な派生タイプの名前を返します。インスタンス化可能な派生タイプの名前は、文字列として返されます。
![]() | |
この関数は、'POINTM'等が返るので、ジオメトリがM値を持っているかどうかも示します。 |
Enhanced: 2.0.0 多面体サーフェス対応、三角対応、TIN対応が導入されました。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT GeometryType(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)')); geometrytype -------------- LINESTRING
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); -- 結果 -- POLYHEDRALSURFACE
SELECT GeometryType(geom) as result FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; result -------- TIN
ST_Boundary — ジオメトリの組み合わせ境界の閉包を返します。
geometry ST_Boundary(
geometry geomA)
;
ジオメトリの組み合わせ境界の閉包を返します (訳注: ラインストリングは端点、ポリゴンはエッジ、複合オブジェクトは境界のうち奇数番)。組み合わせ境界はOGC仕様の3.12.3.2節に記述されています。結果として出てくる境界は、OGC SPEC 3.12.2で議論されているように、ジオメトリプリミティブを使って表現できます。
GEOSモジュールによって実現しています。
![]() | |
2.0.0より前の版では、この関数は |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. OGC SPEC s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.14
This function supports 3d and will not drop the z-index.
Enhanced: 2.1.0で三角対応が導入されました。
Changed: 3.2.0 support for TIN, does not use geos, does not linearize curves
![]() 境界ポイントを重ねたラインストリング
SELECT ST_Boundary(geom) FROM (SELECT 'LINESTRING(100 150,50 60, 70 80, 160 170)'::geometry As geom) As f;
-- ST_AsText 出力 MULTIPOINT(100 150,160 170)
| ![]() 境界マルチラインストリングを重ねたポリゴンの穴
SELECT ST_Boundary(geom) FROM (SELECT 'POLYGON (( 10 130, 50 190, 110 190, 140 150, 150 80, 100 10, 20 40, 10 130 ), ( 70 40, 100 50, 120 80, 80 110, 50 90, 70 40 ))'::geometry As geom) As f;
-- ST_AsText 出力 -- MULTILINESTRING((10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130), (70 40,100 50,120 80,80 110,50 90,70 40))
|
SELECT ST_AsText(ST_Boundary(ST_GeomFromText('LINESTRING(1 1,0 0, -1 1)'))); st_astext ----------- MULTIPOINT(1 1,-1 1) SELECT ST_AsText(ST_Boundary(ST_GeomFromText('POLYGON((1 1,0 0, -1 1, 1 1))'))); st_astext ---------- LINESTRING(1 1,0 0,-1 1,1 1) -- 3次元ポリゴンを使用 SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('POLYGON((1 1 1,0 0 1, -1 1 1, 1 1 1))'))); st_asewkt ----------------------------------- LINESTRING(1 1 1,0 0 1,-1 1 1,1 1 1) -- 3次元マルチラインストリングを使用 SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('MULTILINESTRING((1 1 1,0 0 0.5, -1 1 1),(1 1 0.5,0 0 0.5, -1 1 0.5, 1 1 0.5) )'))); st_asewkt ---------- MULTIPOINT(-1 1 1,1 1 0.75)
ST_BoundingDiagonal — 与えられたジオメトリのバウンディングボックスの対角線を返します。
geometry ST_BoundingDiagonal(
geometry geom, boolean fits=false)
;
与えられたジオメトリのバウンディングボックスの対角線をラインストリングで返します。入力ジオメトリが空の場合には、対角線も空になります。その他の場合には、最小値のポイントを始点とし、最大値のポイントを終点とする、二つのポイントからなるラインストリングになります。
fits
パラメータは、最良適合が必要かどうかを指定するものです。FALSEの場合には、幾分大きめなバウンディングボックスの対角線を受け付けることができます (多数の頂点からなるジオメトリの取得が早くなります)。いずれにしても返された対角線のバウンディングボックスは常に入力ジオメトリを含みます。
返されるラインストリングは常に、入力ジオメトリのSRIDと次元 (ZとMがあること)を維持します。
![]() | |
縮退した (入力の頂点が一つ)場合、返されるラインストリングはトポロジ的に不正です (内部が無い)。返り値を意味的な不正にはしません。 |
Availability: 2.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_CoordDim —
ST_Geometry値の座標次元を返します。
integer ST_CoordDim(
geometry geomA)
;
ST_Geometry値の座標次元を返します。
この関数はST_NDimsのMM対応の別名です。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.3
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
ST_Dimension —
ST_Geometry値の座標次元を返します。
integer ST_Dimension(
geometry g)
;
ジオメトリの固有次元を返します。ジオメトリは座標次元以下でなければなりません。OGC SPEC s2.1.1.1 - 0ならPOINT
、1ならLINESTRING
、2ならPOLYGON
で、GEOMETRYCOLLECTION
の場合は要素ごとの次元の最大値です。不明なジオメトリ (空ジオメトリ)の場合はNULLが返ります。
This method implements the SQL/MM specification. SQL-MM 3: 5.1.2
Enhanced: 2.0.0 多面体サーフェス対応とTIN対応が導入されました。空ジオメトリを与えた場合に例外を投げなくなりました。
![]() | |
2.0.0より前では、空ジオメトリを与えると例外を投げていました。 |
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
ST_Dump — Returns a set of geometry_dump
rows for the components of a geometry.
geometry ST_Envelope(
geometry g1)
;
A set-returning function (SRF) that extracts the components of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
For an atomic geometry type (POINT,LINESTRING,POLYGON) a single record is returned with an empty path
array and the input geometry as geom
. For a collection or multi-geometry a record is returned for each of the collection components, and the path
denotes the position of the component inside the collection.
ST_Dump is useful for expanding geometries. It is the inverse of a ST_GeomCollFromText / GROUP BY, in that it creates new rows. For example it can be use to expand MULTIPOLYGONS into POLYGONS.
Enhanced: 2.0.0 多面体サーフェス対応、三角対応、TIN対応が導入されました。
Availability: PostGIS 1.0.0RC1. Requires PostgreSQL 7.3 or higher.
![]() | |
1.3.4より前では、曲線を含むジオメトリで使用すると、この関数はクラッシュします。これは1.3.4以上で訂正されています。 |
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT sometable.field1, sometable.field1, (ST_Dump(sometable.geom)).geom AS geom FROM sometable; -- Break a compound curve into its constituent linestrings and circularstrings SELECT ST_AsEWKT(a.geom), ST_HasArc(a.geom) FROM ( SELECT (ST_Dump(p_geom)).geom AS geom FROM (SELECT ST_GeomFromEWKT('COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))') AS p_geom) AS b ) AS a; st_asewkt | st_hasarc -----------------------------+---------- CIRCULARSTRING(0 0,1 1,1 0) | t LINESTRING(1 0,0 1) | f (2 rows)
-- 多面体サーフェスの例 -- 多面体サーフェスをフェイスに分解します。 SELECT ST_AsEWKT(ST_GeometryN(p_geom,3)) As geom_ewkt FROM (SELECT ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )') AS p_geom ) AS a; geom_ewkt ------------------------------------------ POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0))
-- TIN -- SELECT ST_AsEWKT(ST_GeometryN(geom,2)) as wkt FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; -- 結果-- wkt ------------------------------------- TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
ST_NumPoints —
ジオメトリについての要約文を返します。
geometry ST_Points(
geometry geom )
;
A set-returning function (SRF) that extracts the coordinates (vertices) of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
the geom
field POINT
s represent the coordinates of the supplied geometry.
the path
field (an integer[]
) is an index enumerating the coordinate positions in the elements of the supplied geometry. The indices are 1-based. For example, for a LINESTRING
the paths are {i}
where i
is the nth
coordinate in the LINESTRING
. For a POLYGON
the paths are {i,j}
where i
is the ring number (1 is outer; inner rings follow) and j
is the coordinate position in the ring.
To obtain a single geometry containing the coordinates use ST_Points.
Enhanced: 2.1.0 Faster speed. Reimplemented as native-C.
Enhanced: 2.0.0 多面体サーフェス対応、三角対応、TIN対応が導入されました。
Availability: 1.2.2
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT edge_id, (dp).path[1] As index, ST_AsText((dp).geom) As wktnode FROM (SELECT 1 As edge_id , ST_DumpPoints(ST_GeomFromText('LINESTRING(1 2, 3 4, 10 10)')) AS dp UNION ALL SELECT 2 As edge_id , ST_DumpPoints(ST_GeomFromText('LINESTRING(3 5, 5 6, 9 10)')) AS dp ) As foo; edge_id | index | wktnode ---------+-------+-------------- 1 | 1 | POINT(1 2) 1 | 2 | POINT(3 4) 1 | 3 | POINT(10 10) 2 | 1 | POINT(3 5) 2 | 2 | POINT(5 6) 2 | 3 | POINT(9 10)
SELECT path, ST_AsText(geom) FROM ( SELECT (ST_DumpPoints(g.geom)).* FROM (SELECT 'GEOMETRYCOLLECTION( POINT ( 0 1 ), LINESTRING ( 0 3, 3 4 ), POLYGON (( 2 0, 2 3, 0 2, 2 0 )), POLYGON (( 3 0, 3 3, 6 3, 6 0, 3 0 ), ( 5 1, 4 2, 5 2, 5 1 )), MULTIPOLYGON ( (( 0 5, 0 8, 4 8, 4 5, 0 5 ), ( 1 6, 3 6, 2 7, 1 6 )), (( 5 4, 5 8, 6 7, 5 4 )) ) )'::geometry AS geom ) AS g ) j; path | st_astext -----------+------------ {1,1} | POINT(0 1) {2,1} | POINT(0 3) {2,2} | POINT(3 4) {3,1,1} | POINT(2 0) {3,1,2} | POINT(2 3) {3,1,3} | POINT(0 2) {3,1,4} | POINT(2 0) {4,1,1} | POINT(3 0) {4,1,2} | POINT(3 3) {4,1,3} | POINT(6 3) {4,1,4} | POINT(6 0) {4,1,5} | POINT(3 0) {4,2,1} | POINT(5 1) {4,2,2} | POINT(4 2) {4,2,3} | POINT(5 2) {4,2,4} | POINT(5 1) {5,1,1,1} | POINT(0 5) {5,1,1,2} | POINT(0 8) {5,1,1,3} | POINT(4 8) {5,1,1,4} | POINT(4 5) {5,1,1,5} | POINT(0 5) {5,1,2,1} | POINT(1 6) {5,1,2,2} | POINT(3 6) {5,1,2,3} | POINT(2 7) {5,1,2,4} | POINT(1 6) {5,2,1,1} | POINT(5 4) {5,2,1,2} | POINT(5 8) {5,2,1,3} | POINT(6 7) {5,2,1,4} | POINT(5 4) (29 rows)
-- Polyhedral surface cube -- SELECT (g.gdump).path, ST_AsEWKT((g.gdump).geom) as wkt FROM (SELECT ST_DumpPoints(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )') ) AS gdump ) AS g; -- result -- path | wkt ---------+-------------- {1,1,1} | POINT(0 0 0) {1,1,2} | POINT(0 0 1) {1,1,3} | POINT(0 1 1) {1,1,4} | POINT(0 1 0) {1,1,5} | POINT(0 0 0) {2,1,1} | POINT(0 0 0) {2,1,2} | POINT(0 1 0) {2,1,3} | POINT(1 1 0) {2,1,4} | POINT(1 0 0) {2,1,5} | POINT(0 0 0) {3,1,1} | POINT(0 0 0) {3,1,2} | POINT(1 0 0) {3,1,3} | POINT(1 0 1) {3,1,4} | POINT(0 0 1) {3,1,5} | POINT(0 0 0) {4,1,1} | POINT(1 1 0) {4,1,2} | POINT(1 1 1) {4,1,3} | POINT(1 0 1) {4,1,4} | POINT(1 0 0) {4,1,5} | POINT(1 1 0) {5,1,1} | POINT(0 1 0) {5,1,2} | POINT(0 1 1) {5,1,3} | POINT(1 1 1) {5,1,4} | POINT(1 1 0) {5,1,5} | POINT(0 1 0) {6,1,1} | POINT(0 0 1) {6,1,2} | POINT(1 0 1) {6,1,3} | POINT(1 1 1) {6,1,4} | POINT(0 1 1) {6,1,5} | POINT(0 0 1) (30 rows)
-- TIN -- SELECT ST_AsEWKT(ST_GeometryN(geom,2)) as wkt FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; -- 結果-- wkt ------------------------------------- TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
-- TIN -- SELECT ST_AsEWKT(ST_GeometryN(geom,2)) as wkt FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; -- 結果-- wkt ------------------------------------- TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
ST_NumPoints —
ジオメトリについての要約文を返します。
geometry ST_Points(
geometry geom )
;
A set-returning function (SRF) that extracts the segments of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
LINESTRING
が閉じていて、かつ単純である場合にTRUE
を返します。
the path
field (an integer[]
) is an index enumerating the segment start point positions in the elements of the supplied geometry. The indices are 1-based. For example, for a LINESTRING
the paths are {i}
where i
is the nth
segment start point in the LINESTRING
. For a POLYGON
the paths are {i,j}
where i
is the ring number (1 is outer; inner rings follow) and j
is the segment start point position in the ring.
Availability: 2.2.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT path, ST_AsText(geom) FROM ( SELECT (ST_DumpSegments(g.geom)).* FROM (SELECT 'GEOMETRYCOLLECTION( LINESTRING(1 1, 3 3, 4 4), POLYGON((5 5, 6 6, 7 7, 5 5)) )'::geometry AS geom ) AS g ) j; path │ st_astext --------------------------------- {1,1} │ LINESTRING(1 1,3 3) {1,2} │ LINESTRING(3 3,4 4) {2,1,1} │ LINESTRING(5 5,6 6) {2,1,2} │ LINESTRING(6 6,7 7) {2,1,3} │ LINESTRING(7 7,5 5) (5 rows)
-- TIN -- SELECT ST_AsEWKT(ST_GeometryN(geom,2)) as wkt FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; -- 結果-- wkt ------------------------------------- TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
-- TIN -- SELECT ST_AsEWKT(ST_GeometryN(geom,2)) as wkt FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; -- 結果-- wkt ------------------------------------- TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
ST_NRings — Returns a set of geometry_dump
rows for the exterior and interior rings of a Polygon.
geometry ST_ExteriorRing(
geometry a_polygon)
;
A set-returning function (SRF) that extracts the rings of a polygon. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
The geom
field contains each ring as a POLYGON. The path
field is an integer array of length 1 containing the polygon ring index. The exterior ring (shell) has index 0. The interior rings (holes) have indices of 1 and higher.
![]() | |
この関数はマルチポリゴンでは動作しません。マルチポリゴンに対してはST_Dumpを併用して下さい。 |
Availability: PostGIS 1.1.3. Requires PostgreSQL 7.3 or higher.
This function supports 3d and will not drop the z-index.
General form of query.
SELECT polyTable.field1, polyTable.field1, (ST_DumpRings(polyTable.geom)).geom As geom FROM polyTable;
A polygon with a single hole.
SELECT path, ST_AsEWKT(geom) As geom FROM ST_DumpRings( ST_GeomFromEWKT('POLYGON((-8149064 5133092 1,-8149064 5132986 1,-8148996 5132839 1,-8148972 5132767 1,-8148958 5132508 1,-8148941 5132466 1,-8148924 5132394 1, -8148903 5132210 1,-8148930 5131967 1,-8148992 5131978 1,-8149237 5132093 1,-8149404 5132211 1,-8149647 5132310 1,-8149757 5132394 1, -8150305 5132788 1,-8149064 5133092 1), (-8149362 5132394 1,-8149446 5132501 1,-8149548 5132597 1,-8149695 5132675 1,-8149362 5132394 1))') ) as foo; path | geom ---------------------------------------------------------------------------------------------------------------- {0} | POLYGON((-8149064 5133092 1,-8149064 5132986 1,-8148996 5132839 1,-8148972 5132767 1,-8148958 5132508 1, | -8148941 5132466 1,-8148924 5132394 1, | -8148903 5132210 1,-8148930 5131967 1, | -8148992 5131978 1,-8149237 5132093 1, | -8149404 5132211 1,-8149647 5132310 1,-8149757 5132394 1,-8150305 5132788 1,-8149064 5133092 1)) {1} | POLYGON((-8149362 5132394 1,-8149446 5132501 1, | -8149548 5132597 1,-8149695 5132675 1,-8149362 5132394 1))
ST_EndPoint — ST_LineStringまたはST_CircularStringのポイント数を返します。
geometry ST_Points(
geometry geom )
;
LINESTRING
またはCIRCULARLINESTRING
ジオメトリの、最初のポイントをPOINT
で返します。入力パラメータがLINESTRING
でもCIRCULARLINESTRING
でもない場合には、NULL
を返します。
This method implements the SQL/MM specification. SQL-MM 3: 7.1.4
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
![]() | |
Changed: 2.0.0では単一ジオメトリのMULTILINESTRINGで動作しなくなりました。単一のラインストリングからなるMULTILINESTRINGについては幸運にも動いていて、最初のポイントを返していました。2.0.0では他のMULTILINESTRINGと同様にNULLを返すようになりました。古い挙動は記載されていませんでしたが、LINESTRINGとして格納されているデータを持っていると思われる人々は2.0でNULLが返って来ることを経験することでしょう。 |
ポイントとラインストリングの最小バウンディングボックス
postgis=# SELECT ST_AsText(ST_EndPoint('LINESTRING(1 1, 2 2, 3 3)'::geometry)); st_astext ------------ POINT(3 3)
End point of a non-LineString is NULL
SELECT ST_EndPoint('POINT(1 1)'::geometry) IS NULL AS is_null; is_null ---------- t
ポイントとラインストリングの最小バウンディングボックス
--3d endpoint SELECT ST_AsEWKT(ST_EndPoint('LINESTRING(1 1 2, 1 2 3, 0 0 5)')); st_asewkt -------------- POINT(0 0 5)
ST_LineStringまたはST_CircularStringのポイント数を返します。
SELECT ST_AsText(ST_EndPoint('CIRCULARSTRING(5 2,-3 1.999999, -2 1, -4 2, 6 3)'::geometry)); st_astext ------------ POINT(6 3)
ST_Envelope — ジオメトリの浮動小数点数 (float8)バウンディングボックスを表現するジオメトリを返します。
geometry ST_Envelope(
geometry g1)
;
ジオメトリのfloat8数の最小バウンディングボックスをジオメトリとして返します。バウンディングボックスの角で定義されたポリゴンで、 ((MINX
, MINY
), (MINX
, MAXY
), (MAXX
, MAXY
), (MAXX
, MINY
), (MINX
, MINY
))となります。可能ならZMIN
/ZMAX
座標が追加されます。
縮退する場合 (縦のライン、ポイント)はPOLYGON
より低い次元のジオメトリ、すなわちPOINT
またはLINESTRING
を返します。
Availability: 1.5.0 挙動が変更され出力がfloat4からfloat8になりました。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.15
SELECT ST_AsText(ST_Envelope('POINT(1 3)'::geometry)); st_astext ------------ POINT(1 3) (1 row) SELECT ST_AsText(ST_Envelope('LINESTRING(0 0, 1 3)'::geometry)); st_astext -------------------------------- POLYGON((0 0,0 3,1 3,1 0,0 0)) (1 row) SELECT ST_AsText(ST_Envelope('POLYGON((0 0, 0 1, 1.0000001 1, 1.0000001 0, 0 0))'::geometry)); st_astext -------------------------------------------------------------- POLYGON((0 0,0 1,1.00000011920929 1,1.00000011920929 0,0 0)) (1 row) SELECT ST_AsText(ST_Envelope('POLYGON((0 0, 0 1, 1.0000000001 1, 1.0000000001 0, 0 0))'::geometry)); st_astext -------------------------------------------------------------- POLYGON((0 0,0 1,1.00000011920929 1,1.00000011920929 0,0 0)) (1 row) SELECT Box3D(geom), Box2D(geom), ST_AsText(ST_Envelope(geom)) As envelopewkt FROM (SELECT 'POLYGON((0 0, 0 1000012333334.34545678, 1.0000001 1, 1.0000001 0, 0 0))'::geometry As geom) As foo;
ポイントとラインストリングの最小バウンディングボックス
SELECT ST_AsText(ST_Envelope( ST_Collect( ST_GeomFromText('LINESTRING(55 75,125 150)'), ST_Point(20, 80)) )) As wktenv; wktenv ----------- POLYGON((20 75,20 150,125 150,125 75,20 75))
ST_ExteriorRing — ポリゴンジオメトリの内環の数を返します。
geometry ST_ExteriorRing(
geometry a_polygon)
;
POLYGON
の外環を表現するラインストリングを返します。ジオメトリがポリゴンでない場合はNULLを返します。
![]() | |
この関数はマルチポリゴンでは動作しません。マルチポリゴンに対してはST_Dumpを併用して下さい。 |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. 2.1.5.1
This method implements the SQL/MM specification. SQL-MM 3: 8.2.3, 8.3.3
This function supports 3d and will not drop the z-index.
-- ポリゴンのテーブルを持っているとします SELECT gid, ST_ExteriorRing(the_geom) AS ering FROM sometable; -- マルチポリゴンのテーブルを持っていて、 -- それぞれのポリゴンの外環からなるマルチラインストリングを返させたいとします。 SELECT gid, ST_Collect(ST_ExteriorRing(the_geom)) AS erings FROM (SELECT gid, (ST_Dump(the_geom)).geom As the_geom FROM sometable) As foo GROUP BY gid; --3次元の例 SELECT ST_AsEWKT( ST_ExteriorRing( ST_GeomFromEWKT('POLYGON((0 0 1, 1 1 1, 1 2 1, 1 1 1, 0 0 1))') ) ); st_asewkt --------- LINESTRING(0 0 1,1 1 1,1 2 1,1 1 1,0 0 1)
ST_GeometryN — ST_Geometry値のジオメトリ型を返します。
geometry ST_GeometryN(
geometry geomA, integer n)
;
GEOMETRYCOLLECTION, (MULTI)POINT, (MULTI)LINESTRING, MULTICURVE, (MULTI)POLYGON, POLYHEDRALSURFACEの場合には、1始まりでN番目のジオメトリを返します。それ以外の場合にはNULLを返します。
![]() | |
OGC仕様のため0.8.0版からインデクスを1始まりにしています。これより前の版では0始まりになっています。 |
![]() | |
一つのジオメトリから全てのジオメトリを抽出したい場合は、ST_Dumpを使う方が効果的ですし、単一ジオメトリにも対応しています。 |
Enhanced: 2.0.0 多面体サーフェス対応、三角対応、TIN対応が導入されました。
Changed: 2.0.0 以前の版では非マルチのジオメトリではNULLが返りました。ST_GeometryN(..,1)の場合にはジオメトリを返すよう変更されました。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 9.1.5
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
-- 3次元マルチポイントから部分集合を抽出 SELECT n, ST_AsEWKT(ST_GeometryN(the_geom, n)) As geomewkt FROM ( VALUES (ST_GeomFromEWKT('MULTIPOINT(1 2 7, 3 4 7, 5 6 7, 8 9 10)') ), ( ST_GeomFromEWKT('MULTICURVE(CIRCULARSTRING(2.5 2.5,4.5 2.5, 3.5 3.5), (10 11, 12 11))') ) )As foo(the_geom) CROSS JOIN generate_series(1,100) n WHERE n <= ST_NumGeometries(the_geom); n | geomewkt ---+----------------------------------------- 1 | POINT(1 2 7) 2 | POINT(3 4 7) 3 | POINT(5 6 7) 4 | POINT(8 9 10) 1 | CIRCULARSTRING(2.5 2.5,4.5 2.5,3.5 3.5) 2 | LINESTRING(10 11,12 11) -- 全てのジオメトリを抽出(idを付けたい場合に便利です) SELECT gid, n, ST_GeometryN(the_geom, n) FROM sometable CROSS JOIN generate_series(1,100) n WHERE n <= ST_NumGeometries(the_geom);
-- 多面体サーフェスの例 -- 多面体サーフェスをフェイスに分解します。 SELECT ST_AsEWKT(ST_GeometryN(p_geom,3)) As geom_ewkt FROM (SELECT ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )') AS p_geom ) AS a; geom_ewkt ------------------------------------------ POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0))
-- TIN -- SELECT ST_AsEWKT(ST_GeometryN(geom,2)) as wkt FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; -- 結果-- wkt ------------------------------------- TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
ST_GeometryType — ST_Geometry値のジオメトリ型を返します。
text ST_GeometryType(
geometry g1)
;
ジオメトリ型を'ST_LineString', 'ST_Polygon', 'ST_MultiPolygon'等の文字列で返します。この関数はGeometryType(geometry)とは異なり、先頭に'ST'が付き、M値を持っているかを示しません。
Enhanced: 2.0.0 多面体サーフェス対応が導入されました。
This method implements the SQL/MM specification. SQL-MM 3: 5.1.4
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
SELECT ST_GeometryType(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)')); -- 結果 ST_LineString
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); --結果 -- ST_PolyhedralSurface
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); --結果 -- ST_PolyhedralSurface
SELECT ST_GeometryType(geom) as result FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; result -------- ST_Tin
ST_HasArc — Tests if a geometry contains a circular arc
boolean ST_IsEmpty(
geometry geomA)
;
ジオメトリが、空のジオメトリコレクション、ポリゴン、ポイント等の場合に、trueを返します。
Availability: 1.2.2
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_InteriorRingN — ポリゴンジオメトリの内環の数を返します。
geometry ST_InteriorRingN(
geometry a_polygon, integer n)
;
ポリゴンのN番目の内環を返します。ジオメトリがポリゴンでないかNが範囲外の場合はNULLを返します。
![]() | |
この関数はマルチポリゴンでは動作しません。マルチポリゴンに対してはST_Dumpを併用して下さい。 |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 8.2.6, 8.3.5
This function supports 3d and will not drop the z-index.
ST_IsClosed — LINESTRING
の始点と終点が一致する場合にTRUE
を返します。多面体サーフェスの場合は閉じているかどうか (ボリュームであるかどうか)を返します。
boolean ST_IsClosed(
geometry g)
;
LINESTRING
の始点と終点が一致する場合にTRUE
を返します。多面体サーフェスの場合は面であるか (開いているか)、またはボリュームであるか (閉じているか)を返します。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 7.1.5, 9.3.3
![]() | |
SQL-MMでは |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
Enhanced: 2.0.0 多面体サーフェス対応が導入されました。
This function supports Polyhedral surfaces.
postgis=# SELECT ST_IsClosed('LINESTRING(0 0, 1 1)'::geometry); st_isclosed ------------- f (1 row) postgis=# SELECT ST_IsClosed('LINESTRING(0 0, 0 1, 1 1, 0 0)'::geometry); st_isclosed ------------- t (1 row) postgis=# SELECT ST_IsClosed('MULTILINESTRING((0 0, 0 1, 1 1, 0 0),(0 0, 1 1))'::geometry); st_isclosed ------------- f (1 row) postgis=# SELECT ST_IsClosed('POINT(0 0)'::geometry); st_isclosed ------------- t (1 row) postgis=# SELECT ST_IsClosed('MULTIPOINT((0 0), (1 1))'::geometry); st_isclosed ------------- t (1 row)
-- 立方体 -- SELECT ST_IsClosed(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); st_isclosed ------------- t -- 立方体のようなものだけれども側面が一つ無いもの-- SELECT ST_IsClosed(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)) )')); st_isclosed ------------- f
ST_IsCollection — ジオメトリが、空のジオメトリコレクション、ポリゴン、ポイント等の場合に、trueを返します。
boolean ST_IsCollection(
geometry g)
;
引数が次のいずれかの場合にはTRUE
を返します。
ジオメトリコレクション
マルチポイント、マルチポリゴン、マルチラインストリング、マルチ曲線、マルチサーフェス
複合曲線
![]() | |
この関数はジオメトリのタイプを解析します。これは、空のコレクションである場合、または一つのエレメントを持つコレクションである場合には |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
postgis=# SELECT ST_IsCollection('LINESTRING(0 0, 1 1)'::geometry); st_iscollection ------------- f (1 row) postgis=# SELECT ST_IsCollection('MULTIPOINT EMPTY'::geometry); st_iscollection ------------- t (1 row) postgis=# SELECT ST_IsCollection('MULTIPOINT((0 0))'::geometry); st_iscollection ------------- t (1 row) postgis=# SELECT ST_IsCollection('MULTIPOINT((0 0), (42 42))'::geometry); st_iscollection ------------- t (1 row) postgis=# SELECT ST_IsCollection('GEOMETRYCOLLECTION(POINT(0 0))'::geometry); st_iscollection ------------- t (1 row)
ST_IsEmpty — Tests if a geometry is empty.
boolean ST_IsEmpty(
geometry geomA)
;
ジオメトリが空ジオメトリの場合にtrueを返します。 trueの場合には、このジオメトリは、空のジオメトリコレクション、ポリゴン、ポイント等です。
![]() | |
SQL-MMでは、ST_IsEmpty(NULL)は0を返しますが、PostGISではNULLを返します。 |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.7
This method supports Circular Strings and Curves
![]() | |
Changed: 2.0.0 以前の版のPostGISではST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)')を許しました。PostGIS 2.0.0では、SQL/MM標準により準拠させるため、これは不正となります。 |
SELECT ST_IsEmpty(ST_GeomFromText('GEOMETRYCOLLECTION EMPTY')); st_isempty ------------ t (1 row) SELECT ST_IsEmpty(ST_GeomFromText('POLYGON EMPTY')); st_isempty ------------ t (1 row) SELECT ST_IsEmpty(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))')); st_isempty ------------ f (1 row) SELECT ST_IsEmpty(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))')) = false; ?column? ---------- t (1 row) SELECT ST_IsEmpty(ST_GeomFromText('CIRCULARSTRING EMPTY')); st_isempty ------------ t (1 row)
ST_IsPolygonCCW — 全ての外環が反時計回りで、全ての内環が時計回りならTRUEを返します。
boolean ST_IsPolygonCCW (
geometry geom )
;
入力ジオメトリの全てのポリゴン要素の外環については反時計回りで、全ての内環については時計回りである場合には、TRUEを返します。
ジオメトリがポリゴン要素を持っていない場合にはTRUEを返します。
![]() | |
閉じたラインストリングはポリゴン要素とみなされません。単一の閉じたラインストリングを渡すと、右回り左回りにかかわらずTRUEが得られます。 |
![]() | |
ポリゴン要素の内環が逆回りになっていない (すなわち外環と同じ方向で回る内環が1個以上ある)場合には、ST_IsPolygonCWとST_IsPolygonCCW の両方ともにFALSEを返します。 |
Availability: 2.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_IsPolygonCW — 入力ジオメトリの全てのポリゴン要素の外環については時計回りで、全ての内環については反時計回りである場合には、TRUEを返します。
boolean ST_IsPolygonCW (
geometry geom )
;
入力ジオメトリの全てのポリゴン要素の外環については時計回りで、全ての内環については反時計回りである場合には、TRUEを返します。
ジオメトリがポリゴン要素を持っていない場合にはTRUEを返します。
![]() | |
閉じたラインストリングはポリゴン要素とみなされません。単一の閉じたラインストリングを渡すと、右回り左回りにかかわらずTRUEが得られます。 |
![]() | |
ポリゴン要素の内環が逆回りになっていない (すなわち外環と同じ方向で回る内環が1個以上ある)場合には、ST_IsPolygonCWとST_IsPolygonCCW の両方ともにFALSEを返します。 |
Availability: 2.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_IsRing — Tests if a LineString is closed and simple.
boolean ST_IsRing(
geometry g)
;
LINESTRING
がST_IsClosed (ST_StartPoint(
g
)~=
ST_Endpoint(
)で、かつST_IsSimple (自己インタセクションが無い)場合にg
)TRUE
を返します。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. 2.1.5.1
This method implements the SQL/MM specification. SQL-MM 3: 7.1.6
![]() | |
SQL-MMでは、 |
SELECT ST_IsRing(the_geom), ST_IsClosed(the_geom), ST_IsSimple(the_geom) FROM (SELECT 'LINESTRING(0 0, 0 1, 1 1, 1 0, 0 0)'::geometry AS the_geom) AS foo; st_isring | st_isclosed | st_issimple -----------+-------------+------------- t | t | t (1 row) SELECT ST_IsRing(the_geom), ST_IsClosed(the_geom), ST_IsSimple(the_geom) FROM (SELECT 'LINESTRING(0 0, 0 1, 1 0, 1 1, 0 0)'::geometry AS the_geom) AS foo; st_isring | st_isclosed | st_issimple -----------+-------------+------------- f | t | f (1 row)
ST_IsSimple — ジオメトリが自己インタセクションや自己接触のような異常な幾何学ポイントを持っていない場合にTRUEを返します。
boolean ST_IsSimple(
geometry geomA)
;
ジオメトリが自己インタセクションや自己接触のような異常な幾何学ポイントを持っていない場合にTRUEを返します。OGCのジオメトリ単純性と妥当性の定義に関する詳細情報については「ジオメトリのOpenGIS準拠を確実にする」をご覧ください。
![]() | |
SQL-MMでは、ST_IsSimple(NULL)は0を返しますが、PostGISではNULLを返します。 |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.8
This function supports 3d and will not drop the z-index.
ST_M — Returns the M coordinate of a Point.
float ST_M(
geometry a_point)
;
ポイントのM座標値を返し、有効でないならNULLを返します。入力はポイントでなければなりません。
![]() | |
これは (いまだに)OGC仕様に入っていませんが、ポイント座標抽出関数のリストを完全にするために挙げています。 |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification.
This function supports 3d and will not drop the z-index.
ST_MemSize — ST_Geometry値のジオメトリ型を返します。
integer ST_NRings(
geometry geomA)
;
ST_Geometry値のジオメトリ型を返します。
This complements the PostgreSQL built-in database object functions pg_column_size, pg_size_pretty, pg_relation_size, pg_total_relation_size.
![]() | |
pg_relation_size which gives the byte size of a table may return byte size lower than ST_MemSize. This is because pg_relation_size does not add toasted table contribution and large geometries are stored in TOAST tables. pg_total_relation_size - includes, the table, the toasted tables, and the indexes. pg_column_size returns how much space a geometry would take in a column considering compression, so may be lower than ST_MemSize |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Changed: 2.2.0 name changed to ST_MemSize to follow naming convention.
--Return how much byte space Boston takes up in our Mass data set SELECT pg_size_pretty(SUM(ST_MemSize(geom))) as totgeomsum, pg_size_pretty(SUM(CASE WHEN town = 'BOSTON' THEN ST_MemSize(geom) ELSE 0 END)) As bossum, CAST(SUM(CASE WHEN town = 'BOSTON' THEN ST_MemSize(geom) ELSE 0 END)*1.00 / SUM(ST_MemSize(geom))*100 As numeric(10,2)) As perbos FROM towns; totgeomsum bossum perbos ---------- ------ ------ 1522 kB 30 kB 1.99 SELECT ST_MemSize(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)')); --- 73 --What percentage of our table is taken up by just the geometry SELECT pg_total_relation_size('public.neighborhoods') As fulltable_size, sum(ST_MemSize(geom)) As geomsize, sum(ST_MemSize(geom))*1.00/pg_total_relation_size('public.neighborhoods')*100 As pergeom FROM neighborhoods; fulltable_size geomsize pergeom ------------------------------------------------ 262144 96238 36.71188354492187500000
ST_NDims —
ST_Geometry値の座標次元を返します。
integer ST_NDims(
geometry g1)
;
ジオメトリの座標次元返します。PostGISでは、2 - (X,Y), 3 - (X,Y,Z), (X,Y,M), 4 - (X,Y,Z,M)に対応しています。
This function supports 3d and will not drop the z-index.
ST_NPoints — ジオメトリのポイント (頂点)数を返します。
integer ST_NPoints(
geometry g1)
;
ジオメトリのポイントの数を返します。全てのジオメトリに対して動作します。
Enhanced: 2.0.0 多面体サーフェス対応が導入されました。
![]() | |
1.3.4より前では、曲線を含むジオメトリで使用すると、この関数はクラッシュします。これは1.3.4以上で訂正されています。 |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
ST_NRings — ポリゴンジオメトリの内環の数を返します。
integer ST_NRings(
geometry geomA)
;
ジオメトリがポリゴンまたはマルチポリゴンの場合、リング数を返します。NumInteriorRingsと違い、外環も数えます。
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_NumGeometries — ジオメトリのポイントの数を返します。全てのジオメトリに対して動作します。
integer ST_NumGeometries(
geometry geom)
;
ジオメトリの数を返します。ジオメトリがジオメトリコレクションまたはマルチ系の場合は、ジオメトリの数を返し、単一のジオメトリの場合は1を返し、それ以外の場合はNULLを返します。
Enhanced: 2.0.0 多面体サーフェス対応、三角対応、TIN対応が導入されました。
Changed: 2.0.0 前の版では、ジオメトリがコレクション/マルチ系でない場合にはNULLを返しました。2.0.0以上では、POLYGON, LINESTRING, POINTといった単一ジオメトリについては1を返します。
This method implements the SQL/MM specification. SQL-MM 3: 9.1.4
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
-- 以前の版ではNULLが返りました -- 2.0.0から1が返ります SELECT ST_NumGeometries(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)')); -- 結果 1 -- ジオメトリコレクションの例 -- - マルチ系はコレクションで一つのジオメトリと数えます。 SELECT ST_NumGeometries(ST_GeomFromEWKT('GEOMETRYCOLLECTION(MULTIPOINT(-2 3 , -2 2), LINESTRING(5 5 ,10 10), POLYGON((-7 4.2,-7.1 5,-7.1 4.3,-7 4.2)))')); -- 結果 3
ST_NumInteriorRings — ポリゴンジオメトリの内環の数を返します。
integer ST_NumInteriorRings(
geometry a_polygon)
;
ポリゴンジオメトリの内環の数を返します。ジオメトリがポリゴンでない場合には、NULLを返します。
This method implements the SQL/MM specification. SQL-MM 3: 8.2.5
Changed: 2.0.0 - 以前の版では、MULTIPOLYGONを渡して最初のPOLYGONの内環の数を返すことができました。
-- 通常のポリゴンの場合 SELECT gid, field1, field2, ST_NumInteriorRings(the_geom) AS numholes FROM sometable; -- マルチポリゴンの内環の総数を知りたい場合 SELECT gid, field1, field2, SUM(ST_NumInteriorRings(the_geom)) AS numholes FROM (SELECT gid, field1, field2, (ST_Dump(the_geom)).geom As the_geom FROM sometable) As foo GROUP BY gid, field1,field2;
ST_NumInteriorRing — ジオメトリ内のポリゴンの内環の数を返します。ST_NumInteriorRingsと同義です。
integer ST_NumInteriorRing(
geometry a_polygon)
;
ST_NumPatches — 多面体サーフェスのフェイス数を返します。多面体でないジオメトリの場合にはNULLを返します。
integer ST_NumPatches(
geometry g1)
;
多面体サーフェスのフェイス数を返します。多面体でないジオメトリの場合にはNULLを返します。ST_NumGeometriesの別名で、MMの名前付けに対応するためのものです。MM規約を気にしない場合はST_NumGeometriesの方が速いです。
Availability: 2.0.0
This function supports 3d and will not drop the z-index.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: ?
This function supports Polyhedral surfaces.
SELECT ST_NumPatches(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); -- 結果 -- 6
ST_NumPoints — ST_LineStringまたはST_CircularStringのポイント数を返します。
integer ST_NumPoints(
geometry g1)
;
ST_LineStringまたはST_CircularStringのポイント数を返します。1.4より前は仕様通りにラインストリングにのみ対応していました。1.4以上ではラインストリングだけでなく頂点数を返すST_NPointsの別名です。多目的で多数のジオメトリタイプで動作するST_NPointsを使うことを考えて下さい。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 7.2.4
ST_PatchN — ST_Geometry値のジオメトリ型を返します。
geometry ST_PatchN(
geometry geomA, integer n)
;
>ジオメトリがPOLYHEDRALSURFACEかPOLYHEDRALSURFACEMの場合には、1始まりでN番目のジオメトリ (フェイス)を返します。それ以外の場合には、NULLを返します。多面体サーフェスを引数にとるST_GeometryNと同じ答えが返ります。ST_GeometryNの方が速いです。
![]() | |
インデクスは1始まりです。 |
![]() | |
一つのジオメトリから全てのジオメトリを抽出したい場合は、ST_Dumpを使う方が効率的です。 |
Availability: 2.0.0
This method implements the SQL/MM specification. SQL-MM 3: ?
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
-- 多面体サーフェスの2番目のフェイスを抽出 SELECT ST_AsEWKT(ST_PatchN(geom, 2)) As geomewkt FROM ( VALUES (ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')) ) As foo(geom); geomewkt ---+----------------------------------------- POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0))
ST_PointN — ST_LineStringまたはST_CircularStringのポイント数を返します。
geometry ST_PointN(
geometry a_linestring, integer n)
;
ラインストリングまたは曲線ストリングのN番目の点を返します。負数はラインストリングの終端から逆方向に遡って数えます。-1は終端を指します。ジオメトリにラインストリングが無い場合には、NULLを返します。
![]() | |
OGC仕様のため0.8.0版からインデックスを1始まりにしています。これより前の版では0はじまりになっています。後方インデックス (負数インデックス)はOGC仕様ではありません。 |
![]() | |
マルチラインストリングからN番目のポイントを得たい場合には、ST_Dumpを併用して下さい。 |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 7.2.5, 7.3.5
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
![]() | |
Changed: 2.0.0 単一ジオメトリのMULTILINESTRINGで動作しなくなりました。単一のラインストリングからなるMULTILINESTRINGについては幸運にも動いていて、最初のポイントを返していました。2.0.0では他のMULTILINESTRINGと同様にNULLを返すようになりました。 Changed: 2.3.0 : 負数インデックスが有効になりました (-1は終端を指します) |
-- LINESTRINGから全てのPOINTを抽出 SELECT ST_AsText( ST_PointN( column1, generate_series(1, ST_NPoints(column1)) )) FROM ( VALUES ('LINESTRING(0 0, 1 1, 2 2)'::geometry) ) AS foo; st_astext ------------ POINT(0 0) POINT(1 1) POINT(2 2) (3 rows) -- CIRCULARSTRINGの例 SELECT ST_AsText(ST_PointN(ST_GeomFromText('CIRCULARSTRING(1 2, 3 2, 1 2)'),2)); st_astext ---------- POINT(3 2) SELECT st_astext(f) FROM ST_GeometryFromtext('LINESTRING(0 0 0, 1 1 1, 2 2 2)') as g ,ST_PointN(g, -2) AS f -- 1 based index st_astext ---------- "POINT Z (1 1 1)"
ST_Points — ジオメトリの全ての座標値からなるマルチポイントを返します。
geometry ST_Points(
geometry geom )
;
ジオメトリの全ての座標値からなるマルチポイントを返します。入力ジオメトリの重複ポイントを削除せず、環ジオメトリの開始点と終了点も削除しません (この挙動を望まない場合にはST_RemoveRepeatedPointsを使って消します)。
To obtain information about the position of each coordinate in the parent geometry use ST_NumPoints.
M値とZ値は、存在する場合には保存されます。
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
Availability: 2.3.0
ST_StartPoint — Returns the first point of a LineString.
geometry ST_StartPoint(
geometry geomA)
;
LINESTRING
またはCIRCULARLINESTRING
ジオメトリの、最初のポイントをPOINT
で返します。入力パラメータがLINESTRING
でもCIRCULARLINESTRING
でもない場合には、NULL
を返します。
This method implements the SQL/MM specification. SQL-MM 3: 7.1.3
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
![]() | |
Enhanced: 3.2.0 returns a point for all geometries. Prior behavior returns NULLs if input was not a LineString. Changed: 2.0.0では単一ジオメトリのMULTILINESTRINGで動作しなくなりました。単一のラインストリングからなるMULTILINESTRINGについては幸運にも動いていて、最初のポイントを返していました。2.0.0では他のMULTILINESTRINGと同様にNULLを返すようになりました。古い挙動は記載されていませんでしたが、LINESTRINGとして格納されているデータを持っていると思われる人々は2.0でNULLが返って来ることを経験することでしょう。 |
Start point of a LineString
SELECT ST_AsText(ST_StartPoint('LINESTRING(0 1, 0 2)'::geometry)); st_astext ------------ POINT(0 1)
Start point of a non-LineString is NULL
SELECT ST_StartPoint('POINT(0 1)'::geometry) IS NULL AS is_null; is_null ---------- t
Start point of a 3D LineString
SELECT ST_AsEWKT(ST_StartPoint('LINESTRING(0 1 1, 0 2 2)'::geometry)); st_asewkt ------------ POINT(0 1 1)
ST_LineStringまたはST_CircularStringのポイント数を返します。
SELECT ST_AsText(ST_StartPoint('CIRCULARSTRING(5 2,-3 1.999999, -2 1, -4 2, 6 3)'::geometry)); st_astext ------------ POINT(5 2)
ST_Summary —
ジオメトリについての要約文を返します。
text ST_Summary(
geometry g)
;
text ST_Summary(
geography g)
;
ジオメトリについての要約文を返します。
ジオメトリ型の後の角括弧で示されたフラグには次の意味があります。
M: M軸を持ちます
Z: Z軸を持ちます
B: バウンディングボックスを持ちます
G: 測地座標系 (ジオグラフィ)です
S: 空間参照系を持ちます
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Availability: 1.2.2
Enhanced: 2.0.0でジオグラフィ対応が追加されました。
Enhanced: 2.1.0 空間参照系を持つかを示すSフラグが追加されました。
Enhanced: 2.2.0 TINと曲線の対応が追加されました。
=# SELECT ST_Summary(ST_GeomFromText('LINESTRING(0 0, 1 1)')) as geom, ST_Summary(ST_GeogFromText('POLYGON((0 0, 1 1, 1 2, 1 1, 0 0))')) geog; geom | geog -----------------------------+-------------------------- LineString[B] with 2 points | Polygon[BGS] with 1 rings | ring 0 has 5 points : (1 row) =# SELECT ST_Summary(ST_GeogFromText('LINESTRING(0 0 1, 1 1 1)')) As geog_line, ST_Summary(ST_GeomFromText('SRID=4326;POLYGON((0 0 1, 1 1 2, 1 2 3, 1 1 1, 0 0 1))')) As geom_poly; ; geog_line | geom_poly -------------------------------- +-------------------------- LineString[ZBGS] with 2 points | Polygon[ZBS] with 1 rings : ring 0 has 5 points : (1 row)
ST_X — Returns the X coordinate of a Point.
float ST_X(
geometry a_point)
;
ポイントのX座標値を返し、有効でないならNULLを返します。入力はポイントでなければなりません。
This method implements the SQL/MM specification. SQL-MM 3: 6.1.3
This function supports 3d and will not drop the z-index.
ST_Y — Returns the Y coordinate of a Point.
float ST_Y(
geometry a_point)
;
ポイントのY座標値を返し、有効でないならNULLを返します。入力はポイントでなければなりません。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 6.1.4
This function supports 3d and will not drop the z-index.
ST_Z — Returns the Z coordinate of a Point.
float ST_Z(
geometry a_point)
;
ST_Zmflag — ST_Geometry値の座標次元を返します。
smallint ST_Zmflag(
geometry geomA)
;
ST_Geometry値の座標次元を返します。
Values are: 0 = 2D, 1 = 3D-M, 2 = 3D-Z, 3 = 4D.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
SELECT ST_Zmflag(ST_GeomFromEWKT('LINESTRING(1 2, 3 4)')); st_zmflag ----------- 0 SELECT ST_Zmflag(ST_GeomFromEWKT('LINESTRINGM(1 2 3, 3 4 3)')); st_zmflag ----------- 1 SELECT ST_Zmflag(ST_GeomFromEWKT('CIRCULARSTRING(1 2 3, 3 4 3, 5 6 3)')); st_zmflag ----------- 2 SELECT ST_Zmflag(ST_GeomFromEWKT('POINT(1 2 3 4)')); st_zmflag ----------- 3
ST_AddPoint — ラインストリングにポイントを追加します。
geometry ST_AddPoint(
geometry linestring, geometry point)
;
geometry ST_AddPoint(
geometry linestring, geometry point, integer position = -1)
;
LINESTRINGのposition
の位置 (0はじまり)の前にポイントを追加します。position
パラメータが省略されるか-1の場合には、LINESTRINGの末尾に追加されます。
Availability: 1.1.0
This function supports 3d and will not drop the z-index.
3次元ラインの末尾へのポイントの追加
SELECT ST_AsEWKT(ST_AddPoint('LINESTRING(0 0 1, 1 1 1)', ST_MakePoint(1, 2, 3))); st_asewkt ---------- LINESTRING(0 0 1,1 1 1,1 2 3)
テーブル内の全てのラインについて、閉じていないラインにだけ始端を末尾に追加することで、閉じていることを保証します。
UPDATE sometable SET geom = ST_AddPoint(geom, ST_StartPoint(geom)) FROM sometable WHERE ST_IsClosed(geom) = false;
ST_CollectionExtract — ジオメトリコレクションを与えると、指定されたタイプの要素だけからなるマルチジオメトリを返します。
geometry ST_CollectionExtract(
geometry collection)
;
geometry ST_CollectionExtract(
geometry collection, integer type)
;
ジオメトリコレクションを指定すると、要素のタイプが統一されたマルチジオメトリを返します。
type
が指定されていない場合には、最大次元のジオメトリだけを含むマルチジオメトリを返します。このため、ポリゴンはラインに優先され、ラインはポイントに優先されます。
type
が指定されている場合には、指定されたタイプだけを含むマルチジオメトリを返します。指定されたタイプの要素が無い場合には、EMPTYジオメトリを返します。ポイント、ライン、ポリゴンだけに対応しています。タイプの番号は次の通りです。
1 == POINT
2 == LINESTRING
3 == POLYGON
非マルチジオメトリの入力に対しては、ジオメトリのタイプと指定したタイプが合致している場合には変更せず返します。合致しない場合には、指定したタイプのEMPTYジオメトリを返します。ST_Multi"/>を使ってマルチ系ジオメトリに変換する必要があるならST_Multiを使います。
![]() | |
マルチポリゴンの結果は妥当性チェックを行いません。ポリゴン要素が隣接やオーバラップしている場合には、結果ジオメトリは不正となります (たとえば、この関数を???の結果に適用すると発生します)。この状況に陥っているかは???で確認でき、???で修復できます。 |
Availability: 1.5.0
![]() | |
1.5.3より前のこの関数は非マルチジオメトリの入力に対して、指定タイプに関係なく変更せずに返しました。1.5.3で指定タイプに合致しない単一ジオメトリ入力に対してNULLを返すようになりました。2.0.0で、合致しないジオメトリに対して、指定タイプのEMPTYジオメトリを返すようになりました。 |
最大次元となるタイプの抽出:
SELECT ST_AsText(ST_CollectionExtract( 'GEOMETRYCOLLECTION( POINT(0 0), LINESTRING(1 1, 2 2) )')); st_astext --------------- MULTILINESTRING((1 1, 2 2))
ポイントの抽出 (type 1 == POINT):
SELECT ST_AsText(ST_CollectionExtract( 'GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(POINT(0 0)))', 1 )); st_astext --------------- MULTIPOINT(0 0)
ラインの抽出 (type 2 == LINESTRING):
SELECT ST_AsText(ST_CollectionExtract( 'GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(LINESTRING(0 0, 1 1)),LINESTRING(2 2, 3 3))', 2 )); st_astext --------------- MULTILINESTRING((0 0, 1 1), (2 2, 3 3))
ST_CollectionHomogenize — ジオメトリコレクションを与えると、最も単純な表現を返します。
geometry ST_CollectionHomogenize(
geometry collection)
;
ジオメトリコレクションを与えると、「最も単純な」表現を返します。
同種の要素からなるコレクションが適切なマルチ系ジオメトリとして返されます。
タイプ混合のコレクションはフラットな単一のGEOMETRYCOLLECTIONに変換されます。
単一の非マルチジオメトリ要素からなるコレクションはその要素が返されます。
非マルチジオメトリは変更されずに返ります。マルチジオメトリへの変換が必要ならST_Multiを使います。
Availability: 2.0.0
単一要素のコレクションから非マルチジオメトリへの変換
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0))')); st_astext ------------ POINT(0 0)
ネスト下単一要素のコレクションから非マルチジオメトリへの変換:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(MULTIPOINT((0 0)))')); st_astext ------------ POINT(0 0)
コレクションからマルチ系ジオメトリへの変換:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0),POINT(1 1))')); st_astext --------------------- MULTIPOINT(0 0,1 1)
ネストしたタイプ混合のコレクションからフラットなジオメトリコレクションへの変換:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0), GEOMETRYCOLLECTION( LINESTRING(1 1, 2 2)))')); st_astext --------------------- GEOMETRYCOLLECTION(POINT(0 0),LINESTRING(1 1,2 2))
ポリゴンのコレクションから (不正な)マルチポリゴンへの変換:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION (POLYGON ((10 50, 50 50, 50 10, 10 10, 10 50)), POLYGON ((90 50, 90 10, 50 10, 50 50, 90 50)))')); st_astext --------------------- MULTIPOLYGON(((10 50,50 50,50 10,10 10,10 50)),((90 50,90 10,50 10,50 50,90 50)))
ST_CurveToLine — 曲線を含むジオメトリを線ジオメトリに変換します。
geometry ST_CurveToLine(
geometry curveGeom, float tolerance, integer tolerance_type, integer flags)
;
CIRCULARSTRINGをLINESTRINGに、CURVEPOLYGONをPOLYGONに、MULTISURFACEをMULTIPOLYGONに、それぞれ変換します。CIRCULARSTRINGジオメトリタイプに対応していないデバイスへの出力に使用します。
与えられたジオメトリを線型ジオメトリに変換します。それぞれの曲線ジオメトリまたは辺は、`tolerance` とオプションを使用して線形近似に変換します (デフォルトでは4分の1円ごとに32辺でオプションなしです)。
'tolerance_type'引数によって`tolerance`引数の解釈が決定されます。
0 (デフォルト): toleranceは4分の1円の最大辺数です。
1: toleranceは曲線からラインまでの最大差です。単位は入力ジオメトリの単位です。
2: toleranceは生成される半径がなす角度のラジアン単位の最大値です。
'flags'引数はビットフィールドです。デフォルトでは0です。次のビットに対応します。
1: 対称となる (方向独立)出力。
2: 角度維持。対称出力を生成する時に角度 (辺長)減少を避けます。対称フラグがOFFの時は何の効果もありません。
Availability: 1.3.0
Enhanced: 2.4.0 最大距離差による許容範囲と最大角度による許容範囲に対応し、対称出力に対応しました。
Enhanced: 3.0.0 線形化した弧ごとの最小線分数を実装しました。トポロジ的な崩壊を防ぐためです。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 7.1.7
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
SELECT ST_AsText(ST_CurveToLine(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'))); --Result -- LINESTRING(220268 150415,220269.95064912 150416.539364228,220271.823415575 150418.17258804,220273.613787707 150419.895736857, 220275.317452352 150421.704659462,220276.930305234 150423.594998003,220278.448460847 150425.562198489, 220279.868261823 150427.60152176,220281.186287736 150429.708054909,220282.399363347 150431.876723113, 220283.50456625 150434.10230186,220284.499233914 150436.379429536,220285.380970099 150438.702620341,220286.147650624 150441.066277505, 220286.797428488 150443.464706771,220287.328738321 150445.892130112,220287.740300149 150448.342699654, 220288.031122486 150450.810511759,220288.200504713 150453.289621251,220288.248038775 150455.77405574, 220288.173610157 150458.257830005,220287.977398166 150460.734960415,220287.659875492 150463.199479347, 220287.221807076 150465.64544956,220286.664248262 150468.066978495,220285.988542259 150470.458232479,220285.196316903 150472.81345077, 220284.289480732 150475.126959442,220283.270218395 150477.39318505,220282.140985384 150479.606668057, 220280.90450212 150481.762075989,220279.5637474 150483.85421628,220278.12195122 150485.87804878, 220276.582586992 150487.828697901,220274.949363179 150489.701464356,220273.226214362 150491.491836488, 220271.417291757 150493.195501133,220269.526953216 150494.808354014,220267.559752731 150496.326509628, 220265.520429459 150497.746310603,220263.41389631 150499.064336517,220261.245228106 150500.277412127, 220259.019649359 150501.38261503,220256.742521683 150502.377282695,220254.419330878 150503.259018879, 220252.055673714 150504.025699404,220249.657244448 150504.675477269,220247.229821107 150505.206787101, 220244.779251566 150505.61834893,220242.311439461 150505.909171266,220239.832329968 150506.078553494, 220237.347895479 150506.126087555,220234.864121215 150506.051658938,220232.386990804 150505.855446946, 220229.922471872 150505.537924272,220227.47650166 150505.099855856,220225.054972724 150504.542297043, 220222.663718741 150503.86659104,220220.308500449 150503.074365683, 220217.994991777 150502.167529512,220215.72876617 150501.148267175, 220213.515283163 150500.019034164,220211.35987523 150498.7825509, 220209.267734939 150497.441796181,220207.243902439 150496, 220205.293253319 150494.460635772,220203.420486864 150492.82741196,220201.630114732 150491.104263143, 220199.926450087 150489.295340538,220198.313597205 150487.405001997,220196.795441592 150485.437801511, 220195.375640616 150483.39847824,220194.057614703 150481.291945091,220192.844539092 150479.123276887,220191.739336189 150476.89769814, 220190.744668525 150474.620570464,220189.86293234 150472.297379659,220189.096251815 150469.933722495, 220188.446473951 150467.535293229,220187.915164118 150465.107869888,220187.50360229 150462.657300346, 220187.212779953 150460.189488241,220187.043397726 150457.710378749,220186.995863664 150455.22594426, 220187.070292282 150452.742169995,220187.266504273 150450.265039585,220187.584026947 150447.800520653, 220188.022095363 150445.35455044,220188.579654177 150442.933021505,220189.25536018 150440.541767521, 220190.047585536 150438.18654923,220190.954421707 150435.873040558,220191.973684044 150433.60681495, 220193.102917055 150431.393331943,220194.339400319 150429.237924011,220195.680155039 150427.14578372,220197.12195122 150425.12195122, 220198.661315447 150423.171302099,220200.29453926 150421.298535644,220202.017688077 150419.508163512,220203.826610682 150417.804498867, 220205.716949223 150416.191645986,220207.684149708 150414.673490372,220209.72347298 150413.253689397,220211.830006129 150411.935663483, 220213.998674333 150410.722587873,220216.22425308 150409.61738497,220218.501380756 150408.622717305,220220.824571561 150407.740981121, 220223.188228725 150406.974300596,220225.586657991 150406.324522731,220227 150406) --3d example SELECT ST_AsEWKT(ST_CurveToLine(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'))); Output ------ LINESTRING(220268 150415 1,220269.95064912 150416.539364228 1.0181172856673, 220271.823415575 150418.17258804 1.03623457133459,220273.613787707 150419.895736857 1.05435185700189,....AD INFINITUM .... 220225.586657991 150406.324522731 1.32611114201132,220227 150406 3) --use only 2 segments to approximate quarter circle SELECT ST_AsText(ST_CurveToLine(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'),2)); st_astext ------------------------------ LINESTRING(220268 150415,220287.740300149 150448.342699654,220278.12195122 150485.87804878, 220244.779251566 150505.61834893,220207.243902439 150496,220187.50360229 150462.657300346, 220197.12195122 150425.12195122,220227 150406) -- Ensure approximated line is no further than 20 units away from -- original curve, and make the result direction-neutral SELECT ST_AsText(ST_CurveToLine( 'CIRCULARSTRING(0 0,100 -100,200 0)'::geometry, 20, -- Tolerance 1, -- Above is max distance between curve and line 1 -- Symmetric flag )); st_astext ------------------------------------------------------------------------------------------- LINESTRING(0 0,50 -86.6025403784438,150 -86.6025403784439,200 -1.1331077795296e-13,200 0)
ST_Scroll — 閉じたLINESTRINGの開始点を変更する
geometry ST_Scroll(
geometry linestring, geometry point)
;
閉じたLINESTRINGの開始/終了点を point
で指定した頂点に変更します。
Availability: 3.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_FlipCoordinates — X値とY値を入れ替えたジオメトリを返します。
geometry ST_FlipCoordinates(
geometry geom)
;
与えられたジオメトリのX値とY値を入れ替えたものを返します。緯度経度 (Y,X)で表現される座標値を持つジオメトリを修正するのに使います。
Availability: 2.0.0
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
ST_Force2D — ジオメトリを2次元モードに強制します。
geometry ST_Force2D(
geometry geomA)
;
ジオメトリを「2次元モード」に強制させます。全ての出力表現はXY座標値のみを持つことになります。OGC準拠の出力 (OGCは2次元ジオメトリのみ策定しています)に強制するために使われます。
Enhanced: 2.0.0 多面体サーフェス対応が導入されました。
Changed: 2.1.0 2.0.xの間はST_Force_2Dと呼ばれていました。
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports 3d and will not drop the z-index.
SELECT ST_AsEWKT(ST_Force2D(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt ------------------------------------- CIRCULARSTRING(1 1,2 3,4 5,6 7,5 6) SELECT ST_AsEWKT(ST_Force2D('POLYGON((0 0 2,0 5 2,5 0 2,0 0 2),(1 1 2,3 1 2,1 3 2,1 1 2))')); st_asewkt ---------------------------------------------- POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))
ST_Force3D — ジオメトリをXYZモードに強制します。これはST_Force3DZの別名です。
geometry ST_Force3D(
geometry geomA, float Zvalue = 0.0)
;
ジオメトリをXYZモードに強制します。これはST_Force_3DZの別名です。ジオメトリがZ値を持っていない場合はZvalue
のZ値を追加します。
Enhanced: 2.0.0 多面体サーフェス対応が導入されました。
Changed: 2.1.0 2.0.xの間はST_Force_3Dと呼ばれていました。
Changed: 3.1.0. 0でないZ値を指定できるようになりました。
This function supports Polyhedral surfaces.
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
-- 既に3次元ジオメトリになっている場合は何も起きません SELECT ST_AsEWKT(ST_Force3D(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt ----------------------------------------------- CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2) SELECT ST_AsEWKT(ST_Force3D('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))')); st_asewkt -------------------------------------------------------------- POLYGON((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
ST_Force3DZ — ジオメトリをXYZモードに強制します。
geometry ST_Force3DZ(
geometry geomA, float Zvalue = 0.0)
;
ジオメトリをXYZモードに強制します。これはST_Force_3DZの別名です。ジオメトリがZ値を持っていない場合はZvalue
のZ値を追加します。
Enhanced: 2.0.0 多面体サーフェス対応が導入されました。
Changed: 2.1.0 2.0.xの間はST_Force_3DZと呼ばれていました。
Changed: 3.1.0. 0でないZ値を指定できるようになりました。
This function supports Polyhedral surfaces.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
-- 既に3次元ジオメトリになっている場合は何も起きません SELECT ST_AsEWKT(ST_Force3DZ(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt ----------------------------------------------- CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2) SELECT ST_AsEWKT(ST_Force3DZ('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))')); st_asewkt -------------------------------------------------------------- POLYGON((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
ST_Force3DM — ジオメトリをXYMモードに強制します。
geometry ST_Force3DM(
geometry geomA, float Mvalue = 0.0)
;
ジオメトリをXYMモードに強制します。ジオメトリがM値を持っていない場合はMvalue
のM値を追加します。Z値を持っている場合はZ値は除去されます。
Changed: 2.1.0 2.0.xの間はST_Force_3DMと呼ばれていました。
Changed: 3.1.0. 0でないM値を指定できるようになりました。
This method supports Circular Strings and Curves
-- 既に3次元ジオメトリになっている場合は何も起きません SELECT ST_AsEWKT(ST_Force3DM(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt ------------------------------------------------ CIRCULARSTRINGM(1 1 0,2 3 0,4 5 0,6 7 0,5 6 0) SELECT ST_AsEWKT(ST_Force3DM('POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3 1,1 1 1))')); st_asewkt --------------------------------------------------------------- POLYGONM((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
ST_Force4D — ジオメトリをXYZMモードに強制します。
geometry ST_Force4D(
geometry geomA, float Zvalue = 0.0, float Mvalue = 0.0)
;
ジオメトリをXYZMモードに強制します。Z値やM値が無い場合はZvalue
とMvalue
を追加します。
Changed: 2.1.0 2.0.xの間はST_Force_4Dと呼ばれていました。
Changed: 3.1.0. 0でないZ値とM値を指定できるようになりました。
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
-- 既に3次元ジオメトリになっている場合は何も起きません SELECT ST_AsEWKT(ST_Force4D(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt --------------------------------------------------------- CIRCULARSTRING(1 1 2 0,2 3 2 0,4 5 2 0,6 7 2 0,5 6 2 0) SELECT ST_AsEWKT(ST_Force4D('MULTILINESTRINGM((0 0 1,0 5 2,5 0 3,0 0 4),(1 1 1,3 1 1,1 3 1,1 1 1))')); st_asewkt -------------------------------------------------------------------------------------- MULTILINESTRING((0 0 0 1,0 5 0 2,5 0 0 3,0 0 0 4),(1 1 0 1,3 1 0 1,1 3 0 1,1 1 0 1))
ST_ForcePolygonCCW — 全ての外環を反時計回りに、全ての内環を時計回りに、それぞれ強制します。
geometry ST_ForcePolygonCCW (
geometry geom )
;
ST_ForceCollection — ジオメトリをジオメトリコレクションに変換します。
geometry ST_ForceCollection(
geometry geomA)
;
ジオメトリをジオメトリコレクションに変換します。これはWKB表現を単純化するのに便利です。
Enhanced: 2.0.0 多面体サーフェス対応が導入されました。
Availability: 1.2.2 1.3.4より前は、曲線を含むジオメトリで使うとクラッシュしました。これは1.3.4以上では訂正されています。
Changed: 2.1.0 2.0.xの間はST_Force_Collectionと呼ばれていました。
This function supports Polyhedral surfaces.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
SELECT ST_AsEWKT(ST_ForceCollection('POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3 1,1 1 1))')); st_asewkt ---------------------------------------------------------------------------------- GEOMETRYCOLLECTION(POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3 1,1 1 1))) SELECT ST_AsText(ST_ForceCollection('CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)')); st_astext -------------------------------------------------------------------------------- GEOMETRYCOLLECTION(CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)) (1 row)
-- 多面体の例 -- SELECT ST_AsEWKT(ST_ForceCollection('POLYHEDRALSURFACE(((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)), ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)), ((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)), ((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)), ((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)), ((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))')) st_asewkt ---------------------------------------------------------------------------------- GEOMETRYCOLLECTION( POLYGON((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)), POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)), POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)), POLYGON((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)), POLYGON((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)), POLYGON((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)) )
ST_ForcePolygonCW — 全ての外環を時計回りに、全ての内環を反時計回りに、それぞれ強制します。
geometry ST_ForcePolygonCW (
geometry geom )
;
ST_ForceSFS — SFS 1.1ジオメトリタイプのみ使うようジオメトリに強制します。
geometry ST_ForceSFS(
geometry geomA)
;
geometry ST_ForceSFS(
geometry geomA, text version)
;
ST_ForceRHR — ポリゴンの頂点の方向を右回りに強制します。
geometry ST_ForceRHR(
geometry g)
;
ポリゴンの頂点の方向はRight-Hand-Ruleに従います。この際、ポリゴンの領域は、境界線の右側になります。特に、外環は時計回りに強制され、内環は反時計回りに強制されます。この関数はST_ForcePolygonCW の別名です。
![]() | |
上のRHRの定義は、他の文脈で使われる場合の定義と矛盾します。これを解消するには、ST_ForcePolygonCWを使うことを推奨します。 |
Enhanced: 2.0.0 多面体サーフェス対応が導入されました。
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
ST_ForceCurve — 該当する場合は、ジオメトリを曲線タイプに変換します。
geometry ST_ForceCurve(
geometry g)
;
可能ならジオメトリを曲線表現に変更します。ラインは複合曲線になり、マルチラインはマルチ曲線になり、ポリゴンは曲線ポリゴンになり、マルチポリゴンはマルチサーフェスになります。入力ジオメトリが既に曲線表現であるなら、入力と同じ値が返されます。
Availability: 2.2.0
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_LineToCurve — 曲線を含むジオメトリを線ジオメトリに変換します。
geometry ST_LineToCurve(
geometry geomANoncircular)
;
LINESTRING/POLYGONをCIRCULARSTRINGと曲線ポリゴンに変換します。等価の曲線を記述するのに必要なポイントが少なくなります。
![]() | |
入力ラインストリング/ポリゴンが、曲線をはっきりと表現するのには不十分な場合には、関数は入力ジオメトリと同じものを返します。 |
Availability: 1.3.0
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
-- 2次元の例 SELECT ST_AsText(ST_LineToCurve(foo.geom)) As curvedastext,ST_AsText(foo.geom) As non_curvedastext FROM (SELECT ST_Buffer('POINT(1 3)'::geometry, 3) As geom) As foo; curvedatext non_curvedastext --------------------------------------------------------------------|----------------------------------------------------------------- CURVEPOLYGON(CIRCULARSTRING(4 3,3.12132034355964 0.878679656440359, | POLYGON((4 3,3.94235584120969 2.41472903395162,3.77163859753386 1.85194970290473, 1 0,-1.12132034355965 5.12132034355963,4 3)) | 3.49440883690764 1.33328930094119,3.12132034355964 0.878679656440359, | 2.66671069905881 0.505591163092366,2.14805029709527 0.228361402466141, | 1.58527096604839 0.0576441587903094,1 0, | 0.414729033951621 0.0576441587903077,-0.148050297095264 0.228361402466137, | -0.666710699058802 0.505591163092361,-1.12132034355964 0.878679656440353, | -1.49440883690763 1.33328930094119,-1.77163859753386 1.85194970290472 | --ETC-- ,3.94235584120969 3.58527096604839,4 3)) --3次元の例 SELECT ST_AsText(ST_LineToCurve(geom)) As curved, ST_AsText(geom) AS not_curved FROM (SELECT ST_Translate(ST_Force3D(ST_Boundary(ST_Buffer(ST_Point(1,3), 2,2))),0,0,3) AS geom) AS foo; curved | not_curved ------------------------------------------------------+--------------------------------------------------------------------- CIRCULARSTRING Z (3 3 3,-1 2.99999999999999 3,3 3 3) | LINESTRING Z (3 3 3,2.4142135623731 1.58578643762691 3,1 1 3, | -0.414213562373092 1.5857864376269 3,-1 2.99999999999999 3, | -0.414213562373101 4.41421356237309 3, | 0.999999999999991 5 3,2.41421356237309 4.4142135623731 3,3 3 3) (1 row)
ST_Multi — マルチ系ジオメトリを返します。
geometry ST_Multi(
geometry geom)
;
ST_Normalize — 標準的な形式に変えたジオメトリを返します。
geometry ST_Normalize(
geometry geom)
;
正規化/標準化された形式のジオメトリを返します。ポリゴンの環における頂点の順序、ポリゴンにおける環の順序、複合ジオメトリにおける要素の順序が変更されることがあります。
ほとんどの場合、試験目的 (期待した結果と実際に得た結果との比較)でのみ使用します。
Availability: 2.3.0
SELECT ST_AsText(ST_Normalize(ST_GeomFromText( 'GEOMETRYCOLLECTION( POINT(2 3), MULTILINESTRING((0 0, 1 1),(2 2, 3 3)), POLYGON( (0 10,0 0,10 0,10 10,0 10), (4 2,2 2,2 4,4 4,4 2), (6 8,8 8,8 6,6 6,6 8) ) )' ))); st_astext ---------------------------------------------------------------------------------------------------------------------------------------------------- GEOMETRYCOLLECTION(POLYGON((0 0,0 10,10 10,10 0,0 0),(6 6,8 6,8 8,6 8,6 6),(2 2,4 2,4 4,2 4,2 2)),MULTILINESTRING((2 2,3 3),(0 0,1 1)),POINT(2 3)) (1 row)
ST_QuantizeCoordinates — 座標値の最下位ビットを0にします。
geometry ST_QuantizeCoordinates (
geometry g , int prec_x , int prec_y , int prec_z , int prec_m )
;
ST_QuantizeCoordinates
は、指定した小数点以下の桁数での座標値表現に必要なビット数 (N
)を決定し、最大の有効ビット数N
以外を0にします。結果の座標値は元の値を丸めますが、圧縮性が改善されます。これにより、ジオメトリカラムが compressible storage typeを使って、ディスク使用を劇的に減少させることができます。この関数によって、小数点以下の桁数の異なる指定が可能になります。指定されていない次元はx
次元の精度を持つものとします。負の桁数は、小数点以上の桁数の参照と解釈されます (例: prec_x=-2
は100付近の座標値を保存します)。
ST_QuantizeCoordinates
が生成する座標は、これらの座標を含むジオメトリや、ジオメトリ内のこれらの相対的な位置から独立しています。結果として、ジオメトリ間に存在するトポロジ関係は、この関数の使用によって影響を受けることはありません。この関数は、ジオメトリの内在的な精度より低い桁数では不正なジオメトリを生成する可能性があります。
Availability: 2.5.0
PostGIS はすべての座標値を倍精度浮動小数点数として格納し、15桁の有効桁数を確実に表すことができます。ただし、PostGISでは、本質的に15桁未満のデータの管理ができます。例としては、小数点以下6桁の精度の地理座標として提供されるTigerデータがあります (故に、必要な有効桁数は、経度は9桁、緯度は8桁です)。
有効桁数が15の時、多数のありえる9桁の表現があります。倍精度浮動小数点数は52の明示的なビット数を座標の仮数部に使っています。有効桁数9桁では仮数部は30ビットだけ必要で、22ビットは有効ではありません。これらの値を好きなものにすることができ、結局は入力値を丸める数字となります。例えば、100.123456という値は100.123456000000, 100.123456000001および100.123456432199に近い数として表現されます。全ては等しく妥当で、これらの入力ではST_AsText(geom, 6)
は同じ結果を返します。これらのビット数をあらゆる値にセットすることができるので、ST_QuantizeCoordinates
は無効ビットとなる22ビットに0をセットします。長い座標値のビット列では、連続的な0のブロックから、PostgreSQLによって効率的に圧縮されたパターンを生成します。
![]() | |
ジオメトリのディスク上のサイズだけが |
SELECT ST_AsText(ST_QuantizeCoordinates('POINT (100.123456 0)'::geometry, 4)); st_astext ------------------------- POINT(100.123455047607 0)
WITH test AS (SELECT 'POINT (123.456789123456 123.456789123456)'::geometry AS geom) SELECT digits, encode(ST_QuantizeCoordinates(geom, digits), 'hex'), ST_AsText(ST_QuantizeCoordinates(geom, digits)) FROM test, generate_series(15, -15, -1) AS digits; digits | encode | st_astext --------+--------------------------------------------+------------------------------------------ 15 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 14 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 13 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 12 | 01010000005c9a72083cdd5e405c9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 11 | 0101000000409a72083cdd5e40409a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 10 | 0101000000009a72083cdd5e40009a72083cdd5e40 | POINT(123.456789123455 123.456789123455) 9 | 0101000000009072083cdd5e40009072083cdd5e40 | POINT(123.456789123418 123.456789123418) 8 | 0101000000008072083cdd5e40008072083cdd5e40 | POINT(123.45678912336 123.45678912336) 7 | 0101000000000070083cdd5e40000070083cdd5e40 | POINT(123.456789121032 123.456789121032) 6 | 0101000000000040083cdd5e40000040083cdd5e40 | POINT(123.456789076328 123.456789076328) 5 | 0101000000000000083cdd5e40000000083cdd5e40 | POINT(123.456789016724 123.456789016724) 4 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 123.456787109375) 3 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 123.456787109375) 2 | 01010000000000000038dd5e400000000038dd5e40 | POINT(123.45654296875 123.45654296875) 1 | 01010000000000000000dd5e400000000000dd5e40 | POINT(123.453125 123.453125) 0 | 01010000000000000000dc5e400000000000dc5e40 | POINT(123.4375 123.4375) -1 | 01010000000000000000c05e400000000000c05e40 | POINT(123 123) -2 | 01010000000000000000005e400000000000005e40 | POINT(120 120) -3 | 010100000000000000000058400000000000005840 | POINT(96 96) -4 | 010100000000000000000058400000000000005840 | POINT(96 96) -5 | 010100000000000000000058400000000000005840 | POINT(96 96) -6 | 010100000000000000000058400000000000005840 | POINT(96 96) -7 | 010100000000000000000058400000000000005840 | POINT(96 96) -8 | 010100000000000000000058400000000000005840 | POINT(96 96) -9 | 010100000000000000000058400000000000005840 | POINT(96 96) -10 | 010100000000000000000058400000000000005840 | POINT(96 96) -11 | 010100000000000000000058400000000000005840 | POINT(96 96) -12 | 010100000000000000000058400000000000005840 | POINT(96 96) -13 | 010100000000000000000058400000000000005840 | POINT(96 96) -14 | 010100000000000000000058400000000000005840 | POINT(96 96) -15 | 010100000000000000000058400000000000005840 | POINT(96 96)
ST_RemovePoint — ラインストリングからポイントを削除します。
geometry ST_RemovePoint(
geometry linestring, integer offset)
;
ラインストリングからポイントを削除します。インデックスは0始まりです。閉じたリングを開いたラインストリングに変えるのに使います。
Enhanced: 3.2.0
Availability: 1.1.0
This function supports 3d and will not drop the z-index.
ST_RemoveRepeatedPoints — 入力ジオメトリから重複ポイントを除いたものを返します。
geometry ST_RemoveRepeatedPoints(
geometry geom, float8 tolerance)
;
入力ジオメトリから重複ポイントを除いたものを返します。実際には(MULTI)LINE, (MULTI)POLYGONとMULTIPOINTで動作します。あらゆる種類のジオメトリで安全に呼び出せます。簡略化がオブジェクトごとに行われるので、ジオメトリコレクションでこの関数を呼ぶことができます。
tolerance引数を与えると、他の頂点との距離が許容値内にある頂点は、削除の目的から、「同じ」と考えます。
Enhanced: 3.2.0
Availability: 2.2.0
This function supports Polyhedral surfaces.
This function supports 3d and will not drop the z-index.
ST_Reverse — 頂点の順序を逆にしたジオメトリを返します。
geometry ST_Reverse(
geometry g1)
;
ST_Segmentize — 与えた距離を超える線分を持たないよう変更したジオメトリ/ジオグラフィを返します。
geometry ST_Segmentize(
geometry geom, float max_segment_length)
;
geography ST_Segmentize(
geography geog, float max_segment_length)
;
max_segment_length
より長い辺を持たないジオメトリ/ジオグラフィに編集して返します。距離計算は2次元のみで行います。ジオメトリの場合、距離の単位は空間参照系の単位です。ジオグラフィの場合、メートル単位となります。
Availability: 1.2.2
Enhanced: 3.0.0 ジオグラフィの分割において、現在は、同じ長さに分割しています。
Enhanced: 2.3.0 ジオグラフィの分割において、現在は、同じ長さに分割しています。
Enhanced: 2.1.0 ジオグラフィ対応が導入されました。
Changed: 2.1.0 ジオグラフィ対応導入の結果として、SELECT ST_Segmentize('LINESTRING(1 2, 3 4)',0.5);
では、あいまいな関数呼び出しエラーとなります。確実にタイプを指定したオブジェクトを持たせる必要があります。たとえば、ジオメトリ/ジオグラフィカラムであったり、ST_GeomFromText, ST_GeogFromTextを使ったり、SELECT ST_Segmentize('LINESTRING(1 2, 3 4)'::geometry,0.5);
としたりします。
![]() | |
この関数によって辺の数が増えるだけです。最大長より短い辺の長さを伸ばすことはしません。 |
SELECT ST_AsText(ST_Segmentize( ST_GeomFromText('MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45 -33,-46 -32))') ,5) ); st_astext -------------------------------------------------------------------------------------------------- MULTILINESTRING((-29 -27,-30 -29.7,-34.886615700134 -30.758766735029,-36 -31, -40.8809353009198 -32.0846522890933,-45 -33), (-45 -33,-46 -32)) (1 row) SELECT ST_AsText(ST_Segmentize(ST_GeomFromText('POLYGON((-29 28, -30 40, -29 28))'),10)); st_astext ----------------------- POLYGON((-29 28,-29.8304547985374 37.9654575824488,-30 40,-29.1695452014626 30.0345424175512,-29 28)) (1 row)
ST_SetPoint — ラインストリングのポイントを与えられたポイントに置き換えます。
geometry ST_SetPoint(
geometry linestring, integer zerobasedposition, geometry point)
;
ラインストリングのN番目を与えられたポイントに置き換えます。インデクスは0はじまりです。負のインデックス値を与えると末尾から数えます。-1は末尾のポイントを指します。これは、頂点が一つ動いた時に接続のリレーションシップを維持しようとする場合のトリガに特に便利です。
Availability: 1.1.0
Updated 2.3.0 : 添え字の負数
This function supports 3d and will not drop the z-index.
-- 最初のポイントを -1 3 から -1 1 に変更 SELECT ST_AsText(ST_SetPoint('LINESTRING(-1 2,-1 3)', 0, 'POINT(-1 1)')); st_astext ----------------------- LINESTRING(-1 1,-1 3) -- ラインストリングの最後のポイントを変更 (このクエリでは3次元ラインストリングでやってみましょう) SELECT ST_AsEWKT(ST_SetPoint(foo.geom, ST_NumPoints(foo.geom) - 1, ST_GeomFromEWKT('POINT(-1 1 3)'))) FROM (SELECT ST_GeomFromEWKT('LINESTRING(-1 2 3,-1 3 4, 5 6 7)') As geom) As foo; st_asewkt ----------------------- LINESTRING(-1 2 3,-1 3 4,-1 1 3) SELECT ST_AsText(ST_SetPoint(g, -3, p)) FROM ST_GEomFromText('LINESTRING(0 0, 1 1, 2 2, 3 3, 4 4)') AS g , ST_PointN(g,1) as p; st_astext ----------------------- LINESTRING(0 0,1 1,0 0,3 3,4 4)
ST_ShiftLongitude — 経度座標値を-180度から180度の範囲と0度から360度の範囲との二つの範囲を行き来するようシフトします。
geometry ST_ShiftLongitude(
geometry geom)
;
ジオメトリの全てのポイント/頂点を読み、経度値が-180度から0度の範囲にあるのを180度から360度の範囲にシフトして、180度から360度の範囲にあるのを-180度から0度の範囲にシフトします。この関数は対称となりますので、-180度から180度の範囲のデータを0度から360度の範囲の表現にし、0度から360度の範囲のデータを-180度から180度の範囲の表現にします。
![]() | |
この関数は、SRID 436 (WGS84地理座標系)のような緯度経度の座標値を持つデータの場合に限って使います。 |
![]() | |
1.3.4より前ではMULTIPOINTでは動作しないバグがありました。1.3.4以上ではMULTIPOINTでも動作します。 |
This function supports 3d and will not drop the z-index.
Enhanced: 2.0.0 多面体サーフェス対応とTIN対応が導入されました。
ご注意: この関数は2.0.0で"ST_Shift_Longitude"から名称変更しました。
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
-- 単一ポイントの前方への変換 SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;POINT(270 0)'::geometry)) st_astext ---------- POINT(-90 0) -- 単一ポイントの逆方向への変換 SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;POINT(-90 0)'::geometry)) st_astext ---------- POINT(270 0) -- ラインストリングでは十分な座標値にのみ影響を与えます SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;LINESTRING(174 12, 182 13)'::geometry)) st_astext ---------- LINESTRING(174 12,-178 13)
ST_WrapX — ジオメトリをX値で回り込ませます。
geometry ST_WrapX(
geometry geom, float8 wrap, float8 move)
;
入力ジオメトリを分割して、全ての結果要素が「回り込み ('wrap')」線から’move'パラメータで決められた方向、すなわち、右側 ('move'が負数)または左側 ('move'が正数)に全ての要素が落ちるように移動させ、最後に再結合します。
![]() | |
経度緯度入力を「再センタリング」して、対象地物が一方からもう一方に飛ばないようにするのに使えます。 |
Availability: 2.3.0 GEOSが必要です。
This function supports 3d and will not drop the z-index.
ST_SnapToGrid — 入力ジオメトリの全ての点を規則的なグリッドにスナップします。
geometry ST_SnapToGrid(
geometry geomA, float originX, float originY, float sizeX, float sizeY)
;
geometry ST_SnapToGrid(
geometry geomA, float sizeX, float sizeY)
;
geometry ST_SnapToGrid(
geometry geomA, float size)
;
geometry ST_SnapToGrid(
geometry geomA, geometry pointOrigin, float sizeX, float sizeY, float sizeZ, float sizeM)
;
1, 2, 3番目の形式では、入力ジオメトリの全てのポイントを原点とセルサイズを定めたグリッドにスナップします。同じセルに落ちた、連続するポイントを削除します。引数ジオメトリのジオメトリタイプを定義できないポイントしか残らなかった場合は、NULLを返します。コレクション内で崩壊したジオメトリはそこから削除されます。精度を落とすのに使います。
4番目の形式は、1.1.0で導入されました。入力ジオメトリの全てのポイントを原点 (第2引数で指定するもので、ポイントでなければなりません)とセルサイズを定めたグリッドにスナップします。グリッドにスナップしたくない次元についてはサイズに0を指定します。
![]() | |
返されるジオメトリは単純性が失われているかも知れません (ST_IsSimpleを参照してください)。 |
![]() | |
1.1.0版より前では、この関数は常に2次元ジオメトリを返しました。1.1.0版からは、返されるジオメトリの次元数は、入力値のうちで手のつけられていない最大の次元と同じになります。全てのグリッドの次元を定義するには、第2引数にジオメトリを取る形式を使って下さい。 |
Availability: 1.0.0RC1
Availability: 1.1.0 - Z値とM値に対応しました
This function supports 3d and will not drop the z-index.
-- 10^-3の精度のグリッドにジオメトリをスナップ UPDATE mytable SET geom = ST_SnapToGrid(geom, 0.001); SELECT ST_AsText(ST_SnapToGrid( ST_GeomFromText('LINESTRING(1.1115678 2.123, 4.111111 3.2374897, 4.11112 3.23748667)'), 0.001) ); st_astext ------------------------------------- LINESTRING(1.112 2.123,4.111 3.237) -- 4次元ジオメトリをスナップ SELECT ST_AsEWKT(ST_SnapToGrid( ST_GeomFromEWKT('LINESTRING(-1.1115678 2.123 2.3456 1.11111, 4.111111 3.2374897 3.1234 1.1111, -1.11111112 2.123 2.3456 1.1111112)'), ST_GeomFromEWKT('POINT(1.12 2.22 3.2 4.4444)'), 0.1, 0.1, 0.1, 0.01) ); st_asewkt ------------------------------------------------------------------------------ LINESTRING(-1.08 2.12 2.3 1.1144,4.12 3.22 3.1 1.1144,-1.08 2.12 2.3 1.1144) -- 4次元ジオメトリ - ST_SnapToGrid(geom,size)はX値とY値に触るだけで、M値とZ値はそのままです SELECT ST_AsEWKT(ST_SnapToGrid(ST_GeomFromEWKT('LINESTRING(-1.1115678 2.123 3 2.3456, 4.111111 3.2374897 3.1234 1.1111)'), 0.01) ); st_asewkt --------------------------------------------------------- LINESTRING(-1.11 2.12 3 2.3456,4.11 3.24 3.1234 1.1111)
ST_Snap — 入力ジオメトリの辺と頂点を参照ジオメトリの頂点にスナップします。
geometry ST_Snap(
geometry input, geometry reference, float tolerance)
;
ジオメトリの頂点と辺を、もう一つのジオメトリの頂点にスナップします。スナップが実行される位置を制御するにはスナップ距離許容値を使います。結果ジオメトリはスナップされた頂点を持つ入力ジオメトリです。スナップが発生しなかった場合には、入力ジオメトリが変更されずに返されます。
一つのジオメトリからもう一つへの変換によって、近傍エッジ (ノード生成とインタセクション計算で問題を引き起こします)を除くことになり、オーバレイ演算のロバスト性が改善されます。
あまりに多数のスナップを行った場合には、生成されるトポロジが不正になる可能性があります。いつスナップが安全かを判定するために、ヒューリスティックにスナップされた頂点の数と位置が決めるしかありません。しかし、省略された潜在的なスナップになりえます。
![]() | |
返されるジオメトリは単純性が失われているかも知れません (ST_IsSimpleを参照してください)し、妥当性が失われているかも知れません (???を参照して下さい)。 |
GEOSモジュールで実現しています。
Availability: 2.0.0
![]() マルチポリゴンとラインストリング (スナップ前) | |
![]() ラインストリングに1.01の許容距離でマルチポリゴンをスナップします。新しいマルチポリゴンはラインストリングにつながります。
SELECT ST_AsText(ST_Snap(poly,line, ST_Distance(poly,line)*1.01)) AS polysnapped FROM (SELECT ST_GeomFromText('MULTIPOLYGON( ((26 125, 26 200, 126 200, 126 125, 26 125 ), ( 51 150, 101 150, 76 175, 51 150 )), (( 151 100, 151 200, 176 175, 151 100 )))') As poly, ST_GeomFromText('LINESTRING (5 107, 54 84, 101 100)') As line ) As foo; polysnapped --------------------------------------------------------------------- MULTIPOLYGON(((26 125,26 200,126 200,126 125,101 100,26 125), (51 150,101 150,76 175,51 150)),((151 100,151 200,176 175,151 100))) | ![]() マルチラインストリングに1.25の許容距離でマルチポリゴンをスナップします。新しいマルチポリゴンはラインストリングにつながります。
SELECT ST_AsText( ST_Snap(poly,line, ST_Distance(poly,line)*1.25) ) AS polysnapped FROM (SELECT ST_GeomFromText('MULTIPOLYGON( (( 26 125, 26 200, 126 200, 126 125, 26 125 ), ( 51 150, 101 150, 76 175, 51 150 )), (( 151 100, 151 200, 176 175, 151 100 )))') As poly, ST_GeomFromText('LINESTRING (5 107, 54 84, 101 100)') As line ) As foo; polysnapped --------------------------------------------------------------------- MULTIPOLYGON(((5 107,26 200,126 200,126 125,101 100,54 84,5 107), (51 150,101 150,76 175,51 150)),((151 100,151 200,176 175,151 100))) |
![]() 元のマルチポリゴンに1.01の許容距離でラインストリングをスナップします。新しいラインストリングはマルチポリゴンにつながります。
SELECT ST_AsText( ST_Snap(line, poly, ST_Distance(poly,line)*1.01) ) AS linesnapped FROM (SELECT ST_GeomFromText('MULTIPOLYGON( ((26 125, 26 200, 126 200, 126 125, 26 125), (51 150, 101 150, 76 175, 51 150 )), ((151 100, 151 200, 176 175, 151 100)))') As poly, ST_GeomFromText('LINESTRING (5 107, 54 84, 101 100)') As line ) As foo; linesnapped ---------------------------------------- LINESTRING(5 107,26 125,54 84,101 100)
| ![]() 元のマルチポリゴンに1.25の許容距離でラインストリングをスナップします。新しいラインストリングはマルチポリゴンにつながります。
SELECT ST_AsText( ST_Snap(line, poly, ST_Distance(poly,line)*1.25) ) AS linesnapped FROM (SELECT ST_GeomFromText('MULTIPOLYGON( (( 26 125, 26 200, 126 200, 126 125, 26 125 ), (51 150, 101 150, 76 175, 51 150 )), ((151 100, 151 200, 176 175, 151 100 )))') As poly, ST_GeomFromText('LINESTRING (5 107, 54 84, 101 100)') As line ) As foo; linesnapped --------------------------------------- LINESTRING(26 125,54 84,101 100) |
ST_SwapOrdinates — 与えられたジオメトリにおいて与えられた座標の値を入れ替えたジオメトリを返します。
geometry ST_SwapOrdinates(
geometry geom, cstring ords)
;
与えられたジオメトリにおいて与えられた座標の値を入れ替えたジオメトリを返します。
ords
引数は2文字の文字列で、入れ替える座標名を示します。座標名はx, y, z, mが有効です。
Availability: 2.2.0
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
ST_AsEWKT — ジオメトリのSRIDメタデータが付いたWell-Known Text (WKT)表現を返します。
text ST_AsEWKT(
geometry g1)
;
text ST_AsEWKT(
geometry g1, integer maxdecimaldigits=15)
;
text ST_AsEWKT(
geography g1)
;
text ST_AsEWKT(
geography g1, integer maxdecimaldigits=15)
;
Returns the Well-Known Text representation of the geometry prefixed with the SRID. The optional maxdecimaldigits
argument may be used to reduce the maximum number of decimal digits after floating point used in output (defaults to 15).
To perform the inverse conversion of EWKT representation to PostGIS geometry use ???.
![]() | |
Using the |
![]() | |
The WKT spec does not include the SRID. To get the OGC WKT format use ST_AsText. |
![]() | |
WKT format does not maintain precision so to prevent floating truncation, use ST_AsBinary or ST_AsEWKB format for transport. |
Enhanced: 3.1.0 精度パラメータ (任意)に対応しました
Enhanced: 2.0.0 ジオグラフィ対応、多面体サーフェス対応、三角形対応、TIN対応が導入されました。
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_AsEWKT('0103000020E61000000100000005000000000000 000000000000000000000000000000000000000000000000000000 F03F000000000000F03F000000000000F03F000000000000F03 F000000000000000000000000000000000000000000000000'::geometry); st_asewkt -------------------------------- SRID=4326;POLYGON((0 0,0 1,1 1,1 0,0 0)) (1 row) SELECT ST_AsEWKT('0108000080030000000000000060E30A4100000000785C0241000000000000F03F0000000018 E20A4100000000485F024100000000000000400000000018 E20A4100000000305C02410000000000000840') --st_asewkt--- CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)
ST_AsText — ジオメトリ/ジオグラフィのSRIDメタデータのないWell-Known Text (WKT)表現を返します。
text ST_AsText(
geometry g1)
;
text ST_AsText(
geometry g1, integer maxdecimaldigits = 15)
;
text ST_AsText(
geography g1)
;
text ST_AsText(
geography g1, integer maxdecimaldigits = 15)
;
ジオメトリ/ジオグラフィのWell-Known Text (WKT)表現を返します。任意引数maxdecimaldigits
は、出力で使われる小数点以下の最大桁数を制限するのに使います (デフォルトは15)。
WKT表現をPostGISジオメトリに逆変換するには???を使います。
![]() | |
標準のOGC WKT表現はSRIDを含みません。出力表現にSRIDを持たせるには、非標準のPostGIS関数ST_AsEWKTを使います。 |
![]() | |
The textual representation of numbers in WKT may not maintain full floating-point precision. To ensure full accuracy for data storage or transport it is best to use Well-Known Binary (WKB) format (see ST_AsBinary and |
![]() | |
Using the |
Availability: 1.5 - ジオグラフィ対応が導入されました。
Enhanced: 2.5 - 精度の任意引数が導入されました。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.25
This method supports Circular Strings and Curves
SELECT ST_AsText('01030000000100000005000000000000000000 000000000000000000000000000000000000000000000000 F03F000000000000F03F000000000000F03F000000000000F03 F000000000000000000000000000000000000000000000000'); st_astext -------------------------------- POLYGON((0 0,0 1,1 1,1 0,0 0))
完全な出力制度がデフォルトです。
SELECT ST_AsText('POINT(111.1111111 1.1111111)')); st_astext ------------------------------ POINT(111.1111111 1.1111111)
引数maxdecimaldigits
は、出力精度の制限に使います。
SELECT ST_AsText('POINT(111.1111111 1.1111111)'), 2); st_astext -------------------- POINT(111.11 1.11)
ST_AsBinary — ジオメトリ/ジオグラフィの、SRIDメタデータを持たないOGC/ISO Well-Knownバイナリ (WKB)表現を返します。
bytea ST_AsBinary(
geometry g1)
;
bytea ST_AsBinary(
geometry g1, text NDR_or_XDR)
;
bytea ST_AsBinary(
geography g1)
;
bytea ST_AsBinary(
geography g1, text NDR_or_XDR)
;
ジオメトリのOGC/ISOWell-Knownバイナリ (WKB)表現を返します。最初の形式では、サーバ機のエンディアンをデフォルトとして使います。二つ目の形式では、リトルエンディアン ('NDR')またはビッグエンディアン ('XDR')を指定する文字列を取ります。
WKB書式は、ジオメトリデータをデータベースから、完全な数値精度を維持して読み取るために使われます。これにより、WKT等のテキスト書式で発生する丸め誤差を回避できます。
WKB表現をPostGISジオメトリに逆変換するには???を使います。
![]() | |
OGC/ISO WKB書式はSRIDを持ちません。SRIDを含むEWKB書式を得るにはST_AsEWKBを使います。 |
![]() | |
PostgreSQL 9.0でのデフォルトの振る舞いが変更され、出力がbytea型の16進数エンコーディングなりました。GUIツールで古い振る舞いが必要な場合には、データベース内で SET bytea_output='escape' を実行します。 |
Enhanced: 2.0.0 多面体サーフェス対応、三角対応、TIN対応が導入されました。
Enhanced: 2.0.0 高次元が導入されました。
Enhanced: 2.0.0 ジオグラフィでのエンディアン指定が導入されました。
Availability: 1.5.0 ジオグラフィが導入されました。
Changed: 2.0.0 この関数への入力は不明な型にすることができなくなり、必ずジオメトリでなければなりません。ST_AsBinary('POINT(1 2)')
といった構築ではもはや妥当ではなく、n st_asbinary(unknown) is not unique error
が得られます。このようなコードはST_AsBinary('POINT(1 2)'::geometry);
に変更する必要があります。これが不可能な場合にはlegacy.sql
をインストールして下さい。
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.37
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)); st_asbinary -------------------------------- \x01030000000100000005000000000000000000000000000000000000000000000000000000000000 000000f03f000000000000f03f000000000000f03f000000000000f03f0000000000000000000000 00000000000000000000000000
SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326), 'XDR'); st_asbinary -------------------------------- \x000000000300000001000000050000000000000000000000000000000000000000000000003ff000 00000000003ff00000000000003ff00000000000003ff00000000000000000000000000000000000 00000000000000000000000000
ST_AsEWKB — ジオメトリの、SRIDメタデータを持つExtended Well-Knownバイナリ (EWKB)表現を返します。
bytea ST_AsEWKB(
geometry g1)
;
bytea ST_AsEWKB(
geometry g1, text NDR_or_XDR)
;
ジオメトリの、SRIDメタデータを持つExtended Well-Knownバイナリ (EWKB)表現を返します。最初の形式では、サーバ機のエンディアンをデフォルトとして使います。二つ目の形式では、リトルエンディアン ('NDR')またはビッグエンディアン ('XDR')を指定する文字列を取ります。
WKB書式は、ジオメトリデータをデータベースから、完全な数値精度を維持して読み取るために使われます。これにより、WKT等のテキスト書式で発生する丸め誤差を回避できます。
EWKB表現をPostGISジオメトリに逆変換するには???を使います。
![]() | |
OGC/ISO WKB書式を得るにはST_AsBinaryを使います。OGC/ISO WKB書式はSRIDを持たないことに注意して下さい。 |
Enhanced: 2.0.0 多面体サーフェス対応、三角対応、TIN対応が導入されました。
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)); st_asewkb -------------------------------- \x0103000020e610000001000000050000000000000000000000000000000000000000000000000000 00000000000000f03f000000000000f03f000000000000f03f000000000000f03f00000000000000 0000000000000000000000000000000000
SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326), 'XDR'); st_asewkb -------------------------------- \x0020000003000010e600000001000000050000000000000000000000000000000000000000000000 003ff00000000000003ff00000000000003ff00000000000003ff000000000000000000000000000 0000000000000000000000000000000000
ST_AsHEXEWKB — ジオメトリのHEXEWKB表現を (文字列として)返します。リトルエンディアン (NDR)またはビッグエンディアン (XDR)のどちらかのエンコーディングを使います。
text ST_AsHEXEWKB(
geometry g1, text NDRorXDR)
;
text ST_AsHEXEWKB(
geometry g1)
;
ジオメトリのHEXEWKB表現を (文字列として)返します。リトルエンディアン (NDR)またはビッグエンディアン (XDR)のどちらかのエンコーディングを使います。エンコーディングを指定しない場合はNDRを使います。
![]() | |
Availability: 1.2.2 |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
SELECT ST_AsHEXEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)); which gives same answer as SELECT ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)::text; st_ashexewkb -------- 0103000020E6100000010000000500 00000000000000000000000000000000 00000000000000000000000000000000F03F 000000000000F03F000000000000F03F000000000000F03 F000000000000000000000000000000000000000000000000
ST_AsEncodedPolyline — ラインストリングジオメトリから符号化したポリラインを返します。
text ST_AsEncodedPolyline(
geometry geom, integer precision=5)
;
符号化したポリラインを返します。この書式はGoogle Mapsではprecision=5で、Open Source Routing Machineでは precision=5と6を使います。
任意パラメータprecision
は、ポリライン符号化の際の桁数を決定するものです。符号化と復号とで同じ値であるべきで、異なる場合には座標が正しくなりません。
Availability: 2.2.0
基本
SELECT ST_AsEncodedPolyline(GeomFromEWKT('SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)')); --結果-- |_p~iF~ps|U_ulLnnqC_mqNvxq`@
ジオグラフィ型のラインストリングとジオグラフィ型のセグメント化したラインストリングを結合してGoogle Mapsに置きます。
-- ボストンからサンフランシスコまでの線を100kmでセグメント化するSQL SELECT ST_AsEncodedPolyline( ST_Segmentize( ST_GeogFromText('LINESTRING(-71.0519 42.4935,-122.4483 37.64)'), 100000)::geometry) As encodedFlightPath;
JavaScriptコードは、クエリの結果を$変数と置き換えると次のようになります。
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry" ></script> <script type="text/javascript"> flightPath = new google.maps.Polyline({ path: google.maps.geometry.encoding.decodePath("$encodedFlightPath"), map: map, strokeColor: '#0000CC', strokeOpacity: 1.0, strokeWeight: 4 }); </script>
ST_AsFlatGeobuf — Return a FlatGeobuf representation of a set of rows.
bytea ST_AsFlatGeobuf(
anyelement set row)
;
bytea ST_AsFlatGeobuf(
anyelement row, bool index)
;
bytea ST_AsFlatGeobuf(
anyelement row, bool index, text geom_name)
;
Return a FlatGeobuf representation (http://flatgeobuf.org) of a set of rows corresponding to a FeatureCollection. NOTE: PostgreSQL bytea cannot exceed 1GB.
row
少なくとも一つのジオメトリカラムを持つ行データ
index
toggle spatial index creation. Default is false.
geom_name
行データにおけるジオメトリカラムのカラム名。NULLの場合には、最初に見つけたジオメトリカラムとします。
Availability: 3.2.0
ST_AsGeobuf — 行集合のGeobuf表現を返します。
bytea ST_AsGeobuf(
anyelement set row)
;
bytea ST_AsGeobuf(
anyelement row, text geom_name)
;
FeatureCollectionに対応する行集合のGeobuf表現 (https://github.com/mapbox/geobuf)を返します。最適な格納のために最大精度を決定しますが、そのために全ての入力ジオメトリは解析されます。現在の形式でのGeobufはストリーム化できないので、完全な出力はメモリ内で組み立てられることに注意して下さい。
row
少なくとも一つのジオメトリカラムを持つ行データ
geom_name
行データにおけるジオメトリカラムのカラム名。NULLの場合には、最初に見つけたジオメトリカラムとします。
Availability: 2.4.0
ST_AsGeoJSON — ジオメトリをGeoJSON要素として返します。
text ST_AsGeoJSON(
record feature, text geomcolumnname, integer maxdecimaldigits=9, boolean pretty_bool=false)
;
text ST_AsGeoJSON(
geometry geom, integer maxdecimaldigits=9, integer options=8)
;
text ST_AsGeoJSON(
geography geog, integer maxdecimaldigits=9, integer options=0)
;
ジオメトリをGeoJSONのgeometryとして返すか、行をGeoJSONのfeatureとして返します (GeoJSON specifications RFC 7946をご覧下さい)。2次元と3次元の両方のジオメトリに対応します。GeoJSONはSFS 1.1のジオメトリタイプにのみ対応します (たとえば曲線には対応していません)。
maxdecimaldigits
引数は、出力で使用される小数部の桁数の最大値を減らすために使われます (デフォルトでは9)。EPSG:4326を使っていて、表示専用でジオメトリを出力する場合には、maxdecimaldigits
=6が、多くの地図で良い選択となります。
![]() | |
Using the |
options
引数は、GeoJSON出力でBBOXまたはCRSを追加するために使われます。次のようにします。
0: オプションなし
1: GeoJSON BBOX
2: GeoJSON Short CRS (たとえば EPSG:4326)
4: GeoJSON Long CRS (たとえば urn:ogc:def:crs:EPSG:4326)
8: EPSG:4326でない場合にGeoJSON Short CRS (デフォルト)
GeoJSON仕様では、ポリゴンは右手規則を使い、この方向を求めるクライアントがあります。これはST_ForcePolygonCCW を使用して確実に対応します。仕様はまたジオメトリの座標系としてWGS84 (SRID=4326)が求められます。必要なら???をST_Transform( geom, 4326 )
のように使って、ジオメトリをWGS84に座標変換します。
GeoJSONはgeojson.ioと geojsonlint.comで、オンラインでのテストと表示が可能です。また、Webマッピングフレームワークで広く対応されています。
Availability: 1.3.4
Availability: 1.5.0 ジオグラフィが導入されました。
Changed: 2.0.0 デフォルト引数と名前付き引数に対応しました。
Changed: 3.0.0 レコードの入力に対応しました
Changed: 3.0.0 EPSG:4326以外の場合のSRID出力
This function supports 3d and will not drop the z-index.
FeatureCollectionの生成:
SELECT json_build_object( 'type', 'FeatureCollection', 'features', json_agg(ST_AsGeoJSON(t.*)::json) ) FROM ( VALUES (1, 'one', 'POINT(1 1)'::geometry), (2, 'two', 'POINT(2 2)'), (3, 'three', 'POINT(3 3)') ) as t(id, name, geom);
{"type" : "FeatureCollection", "features" : [{"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "properties": {"id": 1, "name": "one"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[2,2]}, "properties": {"id": 2, "name": "two"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[3,3]}, "properties": {"id": 3, "name": "three"}}]}
Featureの生成:
SELECT ST_AsGeoJSON(t.*) FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
st_asgeojson ----------------------------------------------------------------------------------------------------------------- {"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "properties": {"id": 1, "name": "one"}}
id
プロパティを持つFeatureを生成する別の方法には、JSONB関数と演算子の使用があります。
SELECT jsonb_build_object( 'type', 'Feature', 'id', id, 'geometry', ST_AsGeoJSON(geom)::jsonb, 'properties', to_jsonb( t.* ) - 'id' - 'geom' ) AS json FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
json ----------------------------------------------------------------------------------------------------------------- {"id": 1, "type": "Feature", "geometry": {"type": "Point", "coordinates": [1, 1]}, "properties": {"name": "one"}}
データをGeoJSON使用に準拠したWGS84経度緯度に変換するのを忘れないで下さい。
SELECT ST_AsGeoJSON(ST_Transform(geom,4326)) from fe_edges limit 1;
st_asgeojson ----------------------------------------------------------------------------------------------------------- {"type":"MultiLineString","coordinates":[[[-89.734634999999997,31.492072000000000], [-89.734955999999997,31.492237999999997]]]}
3次元ジオメトリへの対応:
SELECT ST_AsGeoJSON('LINESTRING(1 2 3, 4 5 6)');
{"type":"LineString","coordinates":[[1,2,3],[4,5,6]]}
ST_AsGML — GML第2版または第3版としてジオメトリを返します。
text ST_AsGML(
geometry geom, integer maxdecimaldigits=15, integer options=0)
;
text ST_AsGML(
geography geog, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
text ST_AsGML(
integer version, geometry geom, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
text ST_AsGML(
integer version, geography geog, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
Geography Markup Language (GML)要素としてジオメトリを返します。versionパラメータは、指定する場合には2か3になります。versionパラメータが無い場合には、デフォルトは2です。
![]() | |
Using the |
GML2では2.1.2版を参照し、GML3では3.1.1を参照します。
最後の'options'引数はビットフィールドです。GML出力のCRS出力型を定義するために、また緯度/経度でデータを宣言するために使います。
0: GML Short CRS (たとえば EPSG:4326)、デフォルト値
1: GML Long CRS (たとえば urn:ogc:def:crs:EPSG:4326)
2: GML 3のみ対応。srsDimension属性を出力から削除します。
4: GML 3のみ対応。線について<Curve>でなく<LineString>要素を使います。
16: データは緯度/経度 (すなわち SRID=4326)です。デフォルトではデータは平面上にあると仮定します。このオプションはGML 3.1.1による出力でのみ使われ、軸のオーダに関連します。これを設定すると、座標の順序を入れ替えるので、データベースの経度/緯度の順でなく緯度/経度の順になります。
32: ジオメトリのボックス (エンベロープ)を出力します。
'namespace prefix'引数は、カスタム名前空間のプリフィクスを指定したり、名前空間プリフィクスを指定しない (空にした場合)ために使用します。NULLを指定するか省略した場合には、'gml'プレフィクスを使用します。
Availability: 1.3.2
Availability: 1.5.0 ジオグラフィが導入されました。
Enhanced: 2.0.0 プレフィクスが導入されました。 GML 3用であるoptionsの4は、曲線のかわりにラインストリングを使えるようにするためのものです。GML 3の多面体サーフェスとTINが導入されました。optionsの32はボックスを出力するために導入されました。
Changed: 2.0.0 デフォルトの名前付き引数を使います。
Enhanced: 2.1.0 GML 3用にidが導入されました。
![]() | |
ST_AsGMLのGML 3版以上では多面体サーフェスとTINに対応しています。 |
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_AsGML(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)); st_asgml -------- <gml:Polygon srsName="EPSG:4326" ><gml:outerBoundaryIs ><gml:LinearRing ><gml:coordinates >0,0 0,1 1,1 1,0 0,0</gml:coordinates ></gml:LinearRing ></gml:outerBoundaryIs ></gml:Polygon >
-- 座標を入れ替え、拡張EPSGで出力 (16 | 1)-- SELECT ST_AsGML(3, ST_GeomFromText('POINT(5.234234233242 6.34534534534)',4326), 5, 17); st_asgml -------- <gml:Point srsName="urn:ogc:def:crs:EPSG::4326" ><gml:pos >6.34535 5.23423</gml:pos ></gml:Point >
-- エンベロープ出力 (32) -- SELECT ST_AsGML(3, ST_GeomFromText('LINESTRING(1 2, 3 4, 10 20)',4326), 5, 32); st_asgml -------- <gml:Envelope srsName="EPSG:4326"> <gml:lowerCorner >1 2</gml:lowerCorner> <gml:upperCorner >10 20</gml:upperCorner> </gml:Envelope >
-- エンベロープ出力 (32)、座標入れ替え (経度緯度を緯度経度に)、Long CRS(1) = 32 | 16 | 1 = 49 -- SELECT ST_AsGML(3, ST_GeomFromText('LINESTRING(1 2, 3 4, 10 20)',4326), 5, 49); st_asgml -------- <gml:Envelope srsName="urn:ogc:def:crs:EPSG::4326"> <gml:lowerCorner >2 1</gml:lowerCorner> <gml:upperCorner >20 10</gml:upperCorner> </gml:Envelope >
-- 多面体サーフェスの例 -- SELECT ST_AsGML(3, ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); st_asgml -------- <gml:PolyhedralSurface> <gml:polygonPatches> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3" >0 0 0 0 0 1 0 1 1 0 1 0 0 0 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3" >0 0 0 0 1 0 1 1 0 1 0 0 0 0 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3" >0 0 0 1 0 0 1 0 1 0 0 1 0 0 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3" >1 1 0 1 1 1 1 0 1 1 0 0 1 1 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3" >0 1 0 0 1 1 1 1 1 1 1 0 0 1 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3" >0 0 1 1 0 1 1 1 1 0 1 1 0 0 1</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> </gml:polygonPatches> </gml:PolyhedralSurface >