PostGIS 3.3.6dev 사용자 지침서

DEV (Fri 01 Dec 2023 11:44:03 PM UTC rev. 5b50402 )

PostGIS 개발 그룹

Abstract

PostGIS는 객체 관계형 데이터베이스 시스템인 PostgreSQL 의 확장 프로그램으로, 데이터베이스에 GIS(지리정보 시스템) 객체를 저장할 수 있게 해줍니다. PostGIS는 GiST 기반 R-Tree 공간 인덱스를 지원하며, GIS 객체의 분석 및 공간 처리를 위한 기능을 포함하고 있습니다.

이 문서는 3.3.6dev 버전의 사용자 지침서입니다.

이 저작물은 크리에이티브 커먼즈 저작자표시-동일조건변경허락 3.0 라이선스를 따릅니다. 사용자가 원하는 대로 이 문서를 사용할 수 있지만, 우리는 사용자가 PostGIS 프로젝트의 저작권을 명시하고 가능한 위치에 http://postgis.net으로 연결되는 링크를 삽입하도록 요구합니다.


Table of Contents
1. 소개
1.1. 프로젝트 운영 위원회
1.2. 핵심 공헌자 - 현재
1.3. 핵심 공헌자 - 과거
1.4. 기타 공헌자
2. PostGIS 설치
2.1. 짧은 설명
2.2. 소스를 컴파일하고 설치하기: 상세 설명
2.2.1. 소스 획득
2.2.2. 설치 요구사항
2.2.3. 설정
2.2.4. 빌드
2.2.5. PostGIS Extensions 빌드 및 배포
2.2.6. 테스트
2.2.7. 설치
2.3. 주소 표준화 도구 설치 및 활용
2.3.1. Regex::Assemble 설치
2.4. Tiger Geocoder의 설치, 업그레이드 및 데이터 불러오기
2.4.1. TIGER 지오코딩 도구로 사용자의 PostGIS 데이터베이스 활성화: 확장 프로그램 이용
2.4.2. TIGER 지오코딩 도구로 사용자의 PostGIS 데이터베이스 활성화: 확장 프로그램 없이
2.4.3. 주소 표준화 도구를 TIGER 지오코딩 도구와 함께 사용
2.4.4. Tiger Data 불러오기
2.4.5. Tiger Geocoder 업그레이드
2.5. 설치 과정에서 흔히 발생하는 문제들
3. PostGIS Administration
3.1. Performance Tuning
3.1.1. Startup
3.1.2. Runtime
3.2. Configuring raster support
3.3. 공간 데이터베이스 생성
3.3.1. Spatially enable database using EXTENSION
3.3.2. Spatially enable database without using EXTENSION (discouraged)
3.3.3. Create a spatially-enabled database from a template
3.4. Upgrading spatial databases
3.4.1. Soft upgrade
3.4.2. Hard upgrade
4. Data Management
4.1. GIS (벡터) 데이터 로드
4.1.1. OGC Geometry
4.1.2. SQL-MM Part 3
4.1.3. OpenGIS WKB 및 WKT
4.2. Geometry Data Type
4.2.1. OpenGIS WKB 및 WKT
4.3. PostGIS 지리형 유형
4.3.1. 공간 테이블 생성
4.3.2. PostGIS 지리형 유형
4.3.3. 도형 데이터 유형과 지리형 데이터 유형을 중첩해서 이용하는 경우
4.3.4. 지리형 고급 FAQ
4.4. Geometry Validation
4.4.1. Simple Geometry
4.4.2. Valid Geometry
4.4.3. Managing Validity
4.5. SPATIAL_REF_SYS 테이블과 공간 참조 시스템
4.5.1. SPATIAL_REF_SYS Table
4.5.2. SPATIAL_REF_SYS 테이블과 공간 참조 시스템
4.6. 공간 테이블 생성
4.6.1. 공간 테이블 생성
4.6.2. The GEOMETRY_COLUMNS VIEW
4.6.3. geometry_columns에 도형 열을 직접 등록하기
4.7. GIS (벡터) 데이터 로드
4.7.1. SQL을 이용해 데이터 가져오기
4.7.2. shp2pgsql: ESRI shapefile 로더 이용하기
4.8. 공간 테이블 생성
4.8.1. SQL을 이용해 데이터 가져오기
4.8.2. 덤퍼 이용하기
4.9. 인덱스 빌드 작업
4.9.1. GiST 인덱스
4.9.2. GiST 인덱스
4.9.3. GiST 인덱스
4.9.4. 인덱스 빌드 작업
5. Spatial Queries
5.1. Determining Spatial Relationships
5.1.1. Dimensionally Extended 9-Intersection Model
5.1.2. Named Spatial Relationships
5.1.3. General Spatial Relationships
5.2. Using Spatial Indexes
5.3. Examples of Spatial SQL
6. 성능 향상 비법
6.1. 대용량 도형을 담은 저용량 테이블
6.1.1. 문제점 설명
6.1.2. 해결 방법
6.2. 도형 인덱스에 대한 클러스터 작업
6.3. 차원 변환 피하기
7. PostGIS 도형 활용: 응용 프로그램 빌드
7.1. MapServer 활용
7.1.1. 기본 활용
7.1.2. FAQ
7.1.3. 고급 활용
7.1.4. 예제
7.2. Java 클라이언트(JDBC)
7.3. C 클라이언트(libpq)
7.3.1. 텍스트 커서
7.3.2. 바이너리 커서
8. PostGIS Reference
8.1. PostgreSQL PostGIS Geometry/Geography/Box 유형
8.2. 관리 함수
8.3. 도형 작성자(constructor)
8.4. 도형 접근자(accessor)
8.5. 도형 편집자(editor)
8.6. Geometry Validation
8.7. Spatial Reference System Functions
8.8. Geometry Input
8.8.1. Well-Known Text (WKT)
8.8.2. Well-Known Binary (WKB)
8.8.3. Other Formats
8.9. Geometry Output
8.9.1. Well-Known Text (WKT)
8.9.2. Well-Known Binary (WKB)
8.9.3. Other Formats
8.10. 연산자(operator)
8.10.1. Bounding Box Operators
8.10.2. 연산자(operator)
8.11. Spatial Relationships
8.11.1. Topological Relationships
8.11.2. Distance Relationships
8.12. Measurement Functions
8.13. Overlay Functions
8.14. 도형 공간 처리
8.15. Affine Transformations
8.16. Clustering Functions
8.17. Bounding Box Functions
8.18. 선형 참조(Linear Referencing)
8.19. Trajectory Functions
8.20. SFCGAL 함수
8.21. 장기 실행 트랜잭션(Long Transaction) 지원
8.22. Version Functions
8.23. PostGIS GUC(Grand Unified Custom Variable)
8.24. Troubleshooting Functions
9. PostGIS 자주 묻는 질문들
10. 지형(topology)
10.1. 지형 유형
10.2. 지형 도메인
10.3. 지형 및 TopoGeometry 관리
10.4. Topology Statistics Management
10.5. 지형 작성자
10.6. 지형 편집자
10.7. 지형 접근자
10.8. 지형 공간 처리
10.9. TopoGeometry 작성자
10.10. TopoGeometry 편집자
10.11. TopoGeometry 접근자
10.12. TopoGeometry 출력물
10.13. 지형 공간 관계성
10.14. Importing and exporting Topologies
10.14.1. Using the Topology exporter
10.14.2. Using the Topology importer
11. 래스터 데이터의 관리, 쿼리 및 응용
11.1. 래스터 로드 및 생성
11.1.1. raster2pgsql을 이용해 래스터를 로드하기
11.1.2. PostGIS 래스터 함수를 이용해 래스터 생성하기
11.1.3. Using "out db" cloud rasters
11.2. 래스터 카탈로그
11.2.1. 래스터 열 카탈로그
11.2.2. 래스터 오버뷰
11.3. PostGIS 래스터를 이용하는 사용자 지정 응용 프로그램 빌드하기
11.3.1. 다른 래스터 함수와 함께 ST_AsPNG를 이용해서 PHP 예제를 출력하기
11.3.2. 다른 래스터 함수와 함께 ST_AsPNG를 이용해서 ASP.NET C# 예제를 출력하기
11.3.3. 래스터 쿼리를 이미지 파일로 출력하는 Java 콘솔 응용 프로그램
11.3.4. PLPython을 이용해서 SQL을 통해 이미지를 덤프하기
11.3.5. PSQL을 이용해서 래스터 출력하기
12. 래스트 참조문서
12.1. 래스터 지원 데이터형
12.2. 래스터 관리
12.3. 래스터 작성자(constructor)
12.4. 래스터 접근자(accessor)
12.5. 래스터 밴드 접근자
12.6. 래스터 픽셀 접근자 및 설정자(setter)
12.7. 래스터 편집자
12.8. 래스터 밴드 편집자
12.9. 래스터 밴드 통계 및 분석
12.10. Raster Inputs
12.11. 래스터 출력
12.12. 래스터 공간 처리
12.13. 내장 맵 대수 콜백 함수
12.14. 래스터 공간 처리
12.15. 래스터를 도형으로
12.16. 래스터 연산자
12.17. 래스터 및 래스터 밴드의 공간 관계성
12.18. Raster Tips
12.18.1. Out-DB Rasters
13. PostGIS 래스터 FAQ
14. PostGIS Extras
14.1. 주소 표준화 도구
14.1.1. 파싱 도구의 작동 방식
14.1.2. 주소 표준화 도구 유형
14.1.3. 주소 표준화 도구 테이블
14.1.4. 주소 표준화 도구 함수
14.2. TIGER 지오코딩 도구
15. PostGIS Special Functions Index
15.1. PostGIS Aggregate Functions
15.2. PostGIS Window Functions
15.3. PostGIS SQL-MM Compliant Functions
15.4. PostGIS Geography Support Functions
15.5. PostGIS Raster Support Functions
15.6. PostGIS Geometry / Geography / Raster Dump Functions
15.7. PostGIS Box Functions
15.8. PostGIS Functions that support 3D
15.9. PostGIS Curved Geometry Support Functions
15.10. PostGIS Polyhedral Surface Support Functions
15.11. PostGIS Function Support Matrix
15.12. New, Enhanced or changed PostGIS Functions
15.12.1. PostGIS Functions new or enhanced in 3.3
15.12.2. PostGIS Functions new or enhanced in 3.2
15.12.3. PostGIS Functions new or enhanced in 3.1
15.12.4. PostGIS Functions new or enhanced in 3.0
15.12.5. PostGIS Functions new or enhanced in 2.5
15.12.6. PostGIS Functions new or enhanced in 2.4
15.12.7. PostGIS Functions new or enhanced in 2.3
15.12.8. PostGIS Functions new or enhanced in 2.2
15.12.9. PostGIS functions breaking changes in 2.2
15.12.10. PostGIS Functions new or enhanced in 2.1
15.12.11. PostGIS functions breaking changes in 2.1
15.12.12. PostGIS Functions new, behavior changed, or enhanced in 2.0
15.12.13. PostGIS Functions changed behavior in 2.0
15.12.14. PostGIS Functions new, behavior changed, or enhanced in 1.5
15.12.15. PostGIS Functions new, behavior changed, or enhanced in 1.4
15.12.16. PostGIS Functions new in 1.3
16. Reporting Problems
16.1. Reporting Software Bugs
16.2. Reporting Documentation Issues
A. Appendix
A.1. PostGIS 3.3.5
A.2. PostGIS 3.3.4
A.3. PostGIS 3.3.3
A.4. PostGIS 3.3.2
A.5. PostGIS 3.3.1
A.6. PostGIS 3.3.0
A.7. PostGIS 3.3.0rc2
A.8. PostGIS 3.3.0rc1
A.9. PostGIS 3.3.0beta2
A.10. PostGIS 3.3.0beta1
A.11. PostGIS 3.3.0alpha1
A.12. PostGIS 3.2.0 (Olivier Courtin Edition)
A.13. PostGIS 3.2.0beta3
A.14. Release 3.2.0beta2
A.15. Release 3.2.0beta1
A.16. Release 3.2.0alpha1
A.17. Release 3.1.0beta1
A.18. Release 3.1.0alpha3
A.19. Release 3.1.0alpha2
A.20. Release 3.1.0alpha1
A.21. Release 3.0.0
A.22. Release 3.0.0rc2
A.23. Release 3.0.0rc1
A.24. Release 3.0.0beta1
A.25. Release 3.0.0alpha4
A.26. Release 3.0.0alpha3
A.27. Release 3.0.0alpha2
A.28. Release 3.0.0alpha1
A.29. Release 2.5.0
A.30. Release 2.4.5
A.31. Release 2.4.4
A.32. Release 2.4.3
A.33. Release 2.4.2
A.34. Release 2.4.1
A.35. Release 2.4.0
A.36. Release 2.3.3
A.37. Release 2.3.2
A.38. Release 2.3.1
A.39. Release 2.3.0
A.40. Release 2.2.2
A.41. Release 2.2.1
A.42. Release 2.2.0
A.43. Release 2.1.8
A.44. Release 2.1.7
A.45. Release 2.1.6
A.46. Release 2.1.5
A.47. Release 2.1.4
A.48. Release 2.1.3
A.49. Release 2.1.2
A.50. Release 2.1.1
A.51. Release 2.1.0
A.52. Release 2.0.5
A.53. Release 2.0.4
A.54. Release 2.0.3
A.55. Release 2.0.2
A.56. Release 2.0.1
A.57. Release 2.0.0
A.58. Release 1.5.4
A.59. Release 1.5.3
A.60. Release 1.5.2
A.61. Release 1.5.1
A.62. Release 1.5.0
A.63. Release 1.4.0
A.64. Release 1.3.6
A.65. Release 1.3.5
A.66. Release 1.3.4
A.67. Release 1.3.3
A.68. Release 1.3.2
A.69. Release 1.3.1
A.70. Release 1.3.0
A.71. Release 1.2.1
A.72. Release 1.2.0
A.73. Release 1.1.6
A.74. Release 1.1.5
A.75. Release 1.1.4
A.76. Release 1.1.3
A.77. Release 1.1.2
A.78. Release 1.1.1
A.79. Release 1.1.0
A.80. Release 1.0.6
A.81. Release 1.0.5
A.82. Release 1.0.4
A.83. Release 1.0.3
A.84. Release 1.0.2
A.85. Release 1.0.1
A.86. Release 1.0.0
A.87. Release 1.0.0RC6
A.88. Release 1.0.0RC5
A.89. Release 1.0.0RC4
A.90. Release 1.0.0RC3
A.91. Release 1.0.0RC2
A.92. Release 1.0.0RC1

Chapter 1. 소개

PostGIS is a spatial extension for the PostgreSQL relational database that was created by Refractions Research Inc, as a spatial database technology research project. Refractions is a GIS and database consulting company in Victoria, British Columbia, Canada, specializing in data integration and custom software development.

PostGIS is now a project of the OSGeo Foundation and is developed and funded by many FOSS4G developers and organizations all over the world that gain great benefit from its functionality and versatility.

The PostGIS project development group plans on supporting and enhancing PostGIS to better support a range of important GIS functionality in the areas of OGC and SQL/MM spatial standards, advanced topological constructs (coverages, surfaces, networks), data source for desktop user interface tools for viewing and editing GIS data, and web-based access tools.

1.1. 프로젝트 운영 위원회

PostGIS 프로젝트 운영 위원회(Project Steering Committee; PSC)는 PostGIS 프로젝트의 대략적인 방향, 발표 주기, 문서화 및 원조 활동을 조정합니다. PSC는 또한 일반 사용자 지원을 제공하고, PostGIS 커뮤니티 전반에서 개발하는 소프트웨어 패치를 받아들여 승인하며, 개발자 커밋 접근, PSC 신입회원 결정 또는 중요한 API 변경 등 PostGIS에 관한 여러 가지 사안에 대해 투표를 실시합니다.

Raúl Marín Rodríguez

MVT support, Bug fixing, Performance and stability improvements, GitHub curation, alignment of PostGIS with PostgreSQL releases

레지나 오베(Regina Obe)

Buildbot Maintenance, Windows production and experimental builds, documentation, alignment of PostGIS with PostgreSQL releases, X3D support, TIGER geocoder support, management functions.

Darafei Praliaskouski

Index improvements, bug fixing and geometry/geography function improvements, SFCGAL, raster, GitHub curation, and bot maintenance.

폴 램지(Paul Ramsey) (의장)

Co-founder of PostGIS project. General bug fixing, geography support, geography and geometry index support (2D, 3D, nD index and anything spatial index), underlying geometry internal structures, GEOS functionality integration and alignment with GEOS releases, alignment of PostGIS with PostgreSQL releases, loader/dumper, and Shapefile GUI loader.

산드로 산틸리(Sandro Santilli)

Bug fixes and maintenance, buildbot maintenance, git mirror management, management functions, integration of new GEOS functionality and alignment with GEOS releases, topology support, and raster framework and low level API functions.

1.2. 핵심 공헌자 - 현재

니클라스 아벤(Nicklas Avén)

거리 함수 개선(3D 거리와 관계 함수 포함) 및 추가 작업, TWKB(Tiny WKB) 출력 포맷(개발중), 개괄적인 사용자 지원을 담당

Loïc Bartoletti

SFCGAL enhancements and maintenance and ci support

댄 배스턴(Dan Baston)

Geometry clustering function additions, other geometry algorithm enhancements, GEOS enhancements and general user support

Martin Davis

GEOS enhancements and documentation

Björn Harrtell

MapBox Vector Tile and GeoBuf functions. Gogs testing and GitLab experimentation.

Aliaksandr Kalenik

Geometry Processing, PostgreSQL gist, general bug fixing

1.3. 핵심 공헌자 - 과거

박 뽀리(Bborie Park)

Prior PSC Member. Raster development, integration with GDAL, raster loader, user support, general bug fixing, testing on various OS (Slackware, Mac, Windows, and more)

마크 케이브-에일런드(Mark Cave-Ayland)

Prior PSC Member. Coordinated bug fixing and maintenance effort, spatial index selectivity and binding, loader/dumper, and Shapefile GUI Loader, integration of new and new function enhancements.

호르헤 아레발로(Jorge Arévalo)

래스터 개발, GDAL 드라이버 지원, 로더를 담당

올리비에 쿠르텡(Olivier Courtin)

XML(KML, GML)/GeoJSON 입출력 기능, 3D 지원 및 버그 수정을 담당

크리스 호지슨(Chris Hodgson)

전 PSC 회원. 개괄적인 개발, 사이트 및 빌드봇 유지보수, OSGeo 육성 프로젝트 관리를 담당

마테우스 로스코트(Mateusz Loskot)

PostGIS 용 CMake 지원, 파이썬 래스터 로더 원본 개발, 저레벨 래스터 API 함수 개발을 담당

케빈 뉴펠드(Kevin Neufeld)

전 PSC 회원. 문서화 및 문서화 지원 도구, 빌드봇 유지보수, PostGIS 뉴스그룹에서 고급 사용자 지원, PostGIS 유지보수 기능 개선을 담당

데이브 블래스비(Dave Blasby)

PostGIS의 원 개발자이자 공동 창립자. 서버측 객체, 인덱스 바인딩 및 서버측의 여러 분석 기능들을 작업

제프 라운스버리(Jeff Lounsbury)

shapefile 로더/덤퍼 원본을 개발. 현재 PostGIS 프로젝트 소유자 대표

마크 레슬리(Mark Leslie)

진행중인 유지보수 및 핵심 기능 개발. 곡선 지원 개선, shapefile GUI 로더를 담당

피에르 라신(Pierre Racine)

Architect of PostGIS raster implementation. Raster overall architecture, prototyping, programming support

다피트 츠바르크(David Zwarg)

래스터 개발(대부분 맵 대수학 분석 기능들)을 담당

1.4. 기타 공헌자

개인 공헌자

Alex BodnaruGreg TroxelMatt Bretl
Alex MayrhoferGuillaume LelargeMatthias Bay
Andrea PeriGiuseppe BroccoloMaxime Guillaud
Andreas Forø TollefsenHan WangMaxime van Noppen
Andreas NeumannHaribabu KommiMichael Fuhr
Andrew GierthHavard TveiteMike Toews
Anne GhislaIIDA TetsushiNathan Wagner
Antoine BajoletIngvild NystuenNathaniel Clay
Arthur LesuisseJackie LengNikita Shulga
Artur ZakirovJames MarcaNorman Vine
Barbara PhillipotJan KatinsPatricia Tozer
Ben JubbJason SmithRafal Magda
Bernhard ReiterJeff AdamsRalph Mason
Björn EsserJelte FennemaRémi Cura
Brian HamlinJim JonesRichard Greenwood
Bruce RindahlJoe ConwayRoger Crew
Bruno Wolff IIIJonne SavolainenRon Mayer
Bryce L. NordgrenJose Carlos Martinez LlariSebastiaan Couwenberg
Carl AndersonJörg HabenichtSergei Shoulbakov
Charlie SavageJulien RouhaudSergey Fedoseev
Christoph BergKashif RasulShinichi Sugiyama
Christoph Moench-TegederKlaus FoersterShoaib Burq
Dane SpringmeyerKris JurkaSilvio Grosso
Dave FuhryLaurenz AlbeStefan Corneliu Petrea
다피트 츠바르크(David Zwarg)Lars RoessigerSteffen Macke
다피트 츠바르크(David Zwarg)Leo HsuStepan Kuzmin
다피트 츠바르크(David Zwarg)Loic DacharyStephen Frost
Dmitry VasilyevLuca S. PercichSteven Ottens
Eduin CarrilloLucas C. Villa RealTalha Rizwan
Eugene AntimirovMaria Arias de ReynaTom Glancy
Even RouaultMarc DucobuTom van Tilburg
Frank WarmerdamMark SondheimVincent Mora
George SilvaMarkus SchaberVincent Picavet
Gerald FenoyMarkus WannerVolf Tomáš
Gino LucreziMatt Amos 

후원 기업

PostGIS 프로젝트에 직접적으로 금전을 후원하거나, 개발자 시간 및 호스팅에 기여를 한 기업들입니다.

크라우드 펀딩 캠페인

크라우드 펀딩 캠페인이란 수많은 사람들에게 서비스할 수 있는, 우리가 간절히 원하는 기능들을 후원받기 위해 진행하는 캠페인입니다. 각 캠페인은 특정 기능 또는 일련의 기능에 특화되어 있습니다. 각 후원자는 필요한 펀딩의 작은 일부분을 담당하며, 충분한 공헌자 또는 조직이 모일 경우 많은 사용자를 도울 수 있는 작업을 위한 비용을 충당할 수 있습니다. 여러분이 생각하기에 다른 사람들이 기꺼이 공동 펀딩에 참여할 만한 아이디어가 있다면, PostGIS 뉴스그룹 에 여러분의 생각을 포스팅해서 우리 모두가 함께 실현할 수 있습니다.

PostGIS 2.0.0은 이런 전략 아래 탄생한 첫 번째 출시작입니다. 우리는 PledgBank 를 이용했으며 이를 통해 캠페인을 두 번 성공적으로 진행했습니다.

postgistopology - 10명 이상의 후원자들이 2.0.0 버전에서 toTopGeometry 함수 빌드와 지형 지원 강화를 위해 250달러씩 후원했습니다.

postgis64windows - 후원자 20여 명이 윈도우 용 64비트 PostGIS의 문제점을 해결하기 위한 작업에 100달러씩 지원했고, 성공했습니다. 이제 PostgreSQL 스택 빌더에서 PostGIS 2.0.1 64비트 버전을 다운로드할 수 있습니다.

주요 지원 라이브러리

The GEOS geometry operations library

The GDAL Geospatial Data Abstraction Library used to power much of the raster functionality introduced in PostGIS 2. In kind, improvements needed in GDAL to support PostGIS are contributed back to the GDAL project.

The PROJ cartographic projection library

Last but not least, PostgreSQL, the giant that PostGIS stands on. Much of the speed and flexibility of PostGIS would not be possible without the extensibility, great query planner, GIST index, and plethora of SQL features provided by PostgreSQL.

Chapter 2. PostGIS 설치

이 장에서는 PostGIS 설치에 요구되는 모든 과정을 설명합니다.

2.1. 짧은 설명

사용자의 검색 경로에 모든 의존성이 설정되어 있을 깨 컴파일하려면:

tar xvfz postgis-3.3.6dev.tar.gz
cd postgis-3.3.6dev
./configure
make
make install

PostGIS가 설치되면, PostGIS를 사용하고자 하는 모든 데이터베이스 각각에서 활성화해야 합니다.

2.2. 소스를 컴파일하고 설치하기: 상세 설명

[Note]

현재 많은 OS 시스템들이 PostgreSQL/PostGIS용 사전 구축된 패키지를 포함하고 있습니다. 많은 경우, 최첨단 버전이 필요하거나 패키지 관리자인 경우가 아니라면 컴파일할 필요가 없습니다.

이 단원에서는 일반적인 컴파일에 대해 설명하고 있으므로, 더 상세한 설명을 원할 경우 PostGIS User contributed compile guidesPostGIS Dev Wiki 를 참조하십시오.

PostGIS Pre-built Packages 에서 다양한 OS를 지원하는 사전 빌드된 패키지들을 확인할 수 있습니다.

만약 윈도우 사용자라면 Stackbuilder 또는 PostGIS Windows download site 를 통해 안정적인 버전을 받을 수 있습니다. 또 1~2주에 한 번 혹은 뭔가 특이한 일이 일어날 경우 빌드를 하는 very bleeding-edge windows experimental builds 가 있습니다. 사용자는 이를 통해 진행중인 PostGIS 배포본을 실행해볼 수 있습니다.

The PostGIS module is an extension to the PostgreSQL backend server. As such, PostGIS 3.3.6dev requires full PostgreSQL server headers access in order to compile. It can be built against PostgreSQL versions 11 - 16. Earlier versions of PostgreSQL are not supported.

아직 PostgreSQL을 설치하지 않았다면 PostgreSQL 설치 지침서를 참조하십시오. http://www.postgresql.org .

[Note]

GEOS 기능성을 위해 PostgreSQL설치 시 표준 C++ 라이브러리를 명확하게 링크해야 할 수도 있습니다.

LDFLAGS=-lstdc++ ./configure [YOUR OPTIONS HERE]

이것은 구 버전 개발 도구 이용시 거짓 C++ 예외 상호작용을 피하기 위한 방법입니다. 만약 사용자가 이상한 문제(백엔드가 갑자기 끊어진다거나 또는 비슷한 증상)를 겪는다면 PostgreSQL을 다시 컴파일해야 할 수도 있습니다.

다음은 PostGIS 소스를 설정하고 취합하는 단계를 설명합니다. 리눅스 사용자를 위한 설명이므로 윈도우 또는 맥 사용자에겐 해당되지 않습니다.

2.2.1. 소스 획득

PostGIS 소스 압축파일을 다운로드 웹사이트 http://postgis.net/stuff/postgis-3.3.6dev.tar.gz 에서 다운로드하십시오.

wget http://postgis.net/stuff/postgis-3.3.6dev.tar.gz
tar -xvzf postgis-3.3.6dev.tar.gz
cd postgis-3.3.6dev

이 명령어를 실행하면 현재 작업 디렉토리에 postgis-3.3.6dev (이)라는 명칭의 디렉터리가 생길 것입니다.

다른 방법으로는, svn 저장소 http://svn.osgeo.org/postgis/trunk/ 에서 소스를 체크아웃(checkout)할 수 있습니다.

git clone https://git.osgeo.org/gitea/postgis/postgis.git postgis
cd postgis
sh autogen.sh
    

설치를 계속하려면 새로 만든 postgis-3.3.6dev 디렉터리로 이동합니다.

./configure

2.2.2. 설치 요구사항

PostGIS를 빌드하고 사용하기 위해서는 다음과 같은 요구사항들을 만족해야 합니다.

필수 사항

  • PostgreSQL 11 - 16. A complete installation of PostgreSQL (including server headers) is required. PostgreSQL is available from http://www.postgresql.org .

    전체 PostgreSQL/PostGIS 지원 매트릭스 및 PostGIS/GEOS 지원 매트릭스는 http://trac.osgeo.org/postgis/wiki/UsersWikiPostgreSQLPostGIS 를 참조하십시오.

  • GNU C 컴파일러(gcc). PostGIS를 컴파일하기 위해 그 밖에 다른 ANSI C 컴파일러들을 사용할 수 있으나 gcc 로 컴파일했을 경우 오류가 훨씬 적게 발생합니다.

  • GNU Make(gmake 또는 make). 많은 시스템들에서 GNU make 는 make의 기본 버전입니다. make -v를 통해 버전을 확인하십시오. 다른 버전의 make는 PostGIS Makefile을 제대로 처리하지 못 할 수도 있습니다.

  • Proj reprojection library. Proj 4.9 or above is required. The Proj library is used to provide coordinate reprojection support within PostGIS. Proj is available for download from https://proj.org/ .

  • GEOS geometry library, version 3.6 or greater, but GEOS 3.11+ is required to take full advantage of all the new functions and features. GEOS is available for download from https://libgeos.org/ .

  • LibXML2, version 2.5.x or higher. LibXML2 is currently used in some imports functions (ST_GeomFromGML and ST_GeomFromKML). LibXML2 is available for download from https://gitlab.gnome.org/GNOME/libxml2/-/releases.

  • JSON-C 0.9 또는 이후 버전. JSON-C는 현재 ST_GeomFromGeoJson 함수를 통해 GeoJSON을 임포트하는 데 사용되고 있습니다. JSON-C는 https://github.com/json-c/json-c/releases/ 에서 다운로드할 수 있습니다.

  • GDAL, version 2+ is required 3+ is preferred. This is required for raster support. https://gdal.org/download.html.

  • 이 파라미터는 현재 작동되지 않습니다. 패키지가 PostgreSQL 설치 경로에만 설치될 것이기 때문입니다. 해당 버그를 추적하려면 http://trac.osgeo.org/postgis/ticket/635 를 참조하십시오.

선택 사항

  • Section 2.1, “짧은 설명” 에 설명된 대로 사용자가 사용하길 원하는 드라이버를 활성화하는 작업도 잊지 마십시오.

  • shapefile 로더 shp2pgsql-gui 를 컴파일하기 위한 GTK(GTK+2.0, 2.8+ 필요). http://www.gtk.org/.

  • SFCGAL, version 1.3.1 (or higher), 1.4.1 or higher is recommended. SFCGAL can be used to provide additional 2D and 3D advanced analysis functions to PostGIS cf Section 8.20, “SFCGAL 함수”. And also allow to use SFCGAL rather than GEOS for some 2D functions provided by both backends (like ST_Intersection or ST_Area, for instance). A PostgreSQL configuration variable postgis.backend allow end user to control which backend he want to use if SFCGAL is installed (GEOS by default). Nota: SFCGAL 1.2 require at least CGAL 4.3 and Boost 1.54 (cf: https://sfcgal.org) https://gitlab.com/sfcgal/SFCGAL/.

  • Section 14.1, “주소 표준화 도구” 를 빌드하려면 PCRE 도 필요합니다(일반적으로 유닉스 파생 시스템에 이미 설치되어 있습니다). parseaddress-stcities.h 파일에 인코딩되어 있는 데이터를 다시 빌드하려 하는 경우에만 Regex::Assemble 펄 CPAN 패키지가 필요합니다. Section 14.1, “주소 표준화 도구” 는 PCRE 라이브러리를 감지할 경우 자동적으로 빌드될 것입니다. 또는 설정 과정에서 유효한 --with-pcre-dir=/path/to/pcre 경로 변수를 입력할 수도 있습니다.

  • To enable ST_AsMVT protobuf-c library 1.1.0 or higher (for usage) and the protoc-c compiler (for building) are required. Also, pkg-config is required to verify the correct minimum version of protobuf-c. See protobuf-c. By default, Postgis will use Wagyu to validate MVT polygons faster which requires a c++11 compiler. It will use CXXFLAGS and the same compiler as the PostgreSQL installation. To disable this and use GEOS instead use the --without-wagyu during the configure step.

  • CUnit(CUnit). 회기 검증을 하는 데 필요합니다. http://cunit.sourceforge.net/

  • DocBook(xsltproc)은 문서를 발행할 때 필요합니다. DocBook은 http://www.docbook.org/ 에서 다운로드할 수 있습니다.

  • DBLatex(dblatex)는 PDF 형식의 문서를 발행할 때 필요합니다. DBLatex는 http://dblatex.sourceforge.net/ 에서 다운로드할 수 있습니다.

  • ImageMagick(convert)은 문서에 사용되는 이미지를 생성하는 데 필요합니다. ImageMagick은 http://www.imagemagick.org/ 에서 다운로드할 수 있습니다.

2.2.3. 설정

대부분의 리눅스 설치에서 첫 번째 단계는 소스 코드를 빌드하는 데 사용할 Makefile을 생성하는 것입니다. 셸 스크립트를 실행해서 Makefile을 작성합니다.

./configure

추가 파라미터 없이 사용하면, 이 명령은 자동적으로 PostGIS 소스코드를 사용자 시스템에 빌드하는 데 필요한 필수 구성 요소들과 라이브러리의 위치를 확인하려 합니다. ./configure 명령어의 가장 흔한 사용법이긴 하지만, 이 스크립트는 비표준적인 위치에 있는 필수 라이브러리와 프로그램들에 대한 몇몇 파라미터를 받습니다.

다음은 가장 많이 사용되는 파라미터들만 나열한 목록입니다. 전체 목록은 --help 또는 --help=short 파라미터를 사용하십시오.

--with-library-minor-version

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.

--prefix=PREFIX

PostGIS 라이브러리와 SQL 스크립트가 설치될 경로입니다. 기본적으로 PostgreSQL가 설치된 경로와 같은 곳에 설치됩니다.

[Caution]

이 파라미터는 현재 작동되지 않습니다. 패키지가 PostgreSQL 설치 경로에만 설치될 것이기 때문입니다. 해당 버그를 추적하려면 http://trac.osgeo.org/postgis/ticket/635 를 참조하십시오.

--with-pgconfig=FILE

PostgreSQL은 PostGIS 같은 확장 프로그램이 PostgreSQL 설치 디렉토리의 위치를 확인하게 해주는 pg_config 라는 유틸리티를 제공합니다. PostGIS 빌드 시 대상이 될 특정 PostgreSQL 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-pgconfig=/path/to/pg_config)를 사용하십시오.

--with-gdalconfig=FILE

GDAL은 래스터 지원을 위한 기능을 제공하는 필수 라이브러리로, GDAL 설치 디렉터리의 위치를 확인하는 소프트웨어 설치를 활성화하기 위한 gdal-config를 지원합니다. PostGIS 빌드 시 대상이 될 특정 GDAL 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-gdalconfig=/path/to/gdal-config)를 사용하십시오.

--with-geosconfig=FILE

GEOS는 필수 도형 라이브러리로, GEOS 설치 디렉터리의 위치를 확인하는 소프트웨어 설치를 활성화하기 위한 geos-config라는 유틸리티를 제공합니다. PostGIS 빌드 시 대상이 될 특정 GEOS 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-geosconfig=/path/to/geos-config)를 사용하십시오.

--with-xml2config=FILE

LibXML은 GeomFromKML/GML 프로세스를 진행하기 위해 필요한 라이브러리입니다. 일반적으로 libxml을 설치하면 찾을 수 있지만, 설치하지 않았거나 특정 버전을 사용하기 바랄 경우 LibXML 설치 디렉터리의 위치를 확인하는 소프트웨어 설치를 활성화하기 위해 xml2-config라는 설정 파일에 PostGIS의 위치를 지정해야 합니다. PostGIS 빌드 시 대상이 될 특정 LibXML 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-xml2config=/path/to/xml2-config)를 사용하십시오.

--with-projdir=DIR

Proj4는 PostGIS 필수 재투영 라이브러리입니다. PostGIS 빌드 시 대상이 될 특정 Proj4 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-projdir=/path/to/projdir)를 사용하십시오.

--with-libiconv=DIR

iconv 설치 경로

--with-jsondir=DIR

JSON-C 는 MIT-라이선스의 JSON 라이브러리로, PostGIS의 ST_GeomFromJSON 지원에 필요합니다. PostGIS 빌드 시 대상이 될 특정 JSON-C 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-jsondir=/path/to/jsondir)를 사용하십시오.

--with-pcredir=DIR

PCRE 는 BSD-라이선스의 펄 호환 가능 정규 표현식 라이브러리로, address_standardizer 확장 프로그램이 필요합니다. PostGIS 빌드 시 대상이 될 특정 PCRE 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-pcredir=/path/to/pcredir)를 사용하십시오.

--with-gui

데이터 임포트 GUI 컴파일(GTK+2.0 필요). shp2pgsql-gui의 shp2pgsql에 대한 그래픽 인테페이스를 생성합니다.

--without-raster

래스터 지원 설치

--without-topology

Disable topology support. There is no corresponding library as all logic needed for topology is in postgis-3.3.6dev library.

--with-gettext=no

기본적으로 PostGIS는 gettext 지원을 감지해서 함께 컴파일하지만, 로더의 파손을 야기하는 비호환성 문제가 발생할 경우 이 명령어로 gettext 지원을 완전히 비활성화시킬 수 있습니다. 이런 방법으로 설정을 변경해서 문제를 해결하는 예는 버그 티켓 http://trac.osgeo.org/postgis/ticket/748 을 참조하십시오. 주의: gettext 지원을 끈다고 해서 별다른 문제는 없습니다. gettext 지원은 아직 문서화되지도 않았고 검증중에 있는 GUI 로더 용 국제 도움말/라벨 지원에 사용됩니다.

--with-sfcgal=PATH

기본적으로 PostGIS는 이 스위치 없이는 sfcgal 지원과 함께 설치되지 않습니다. PATH 는 sfcgal-config를 가리키는 대체 경로를 지정하도록 해주는 선택적인 인자입니다.

--without-phony-revision

Disable updating postgis_revision.h to match current HEAD of the git repository.

[Note]

PostGIS를 SVN 저장소 에서 얻었다면, 먼저 다음 스크립트를 실행하십시오.

./autogen.sh

이 스크립트는 configure 스크립트를 생성하는데, 이 스크립트는 PostGIS의 사용자 지정 설치를 위해 이용됩니다.

만약 tar 파일 형태로 PostGIS를 얻었다면 이미 configure 가 생성되었기 때문에 ./autogen.sh 를 실행할 필요는 없습니다.

2.2.4. 빌드

일단 Makefile이 생성되면 PostGIS 빌드 작업은 실행만큼이나 쉽습니다.

make

산출물의 마지막 줄에 "PostGIS was built successfully. Ready to install."이란 문장이 보여야 합니다.

As of PostGIS v1.4.0, all the functions have comments generated from the documentation. If you wish to install these comments into your spatial databases later, run the command which requires docbook. The postgis_comments.sql and other package comments files raster_comments.sql, topology_comments.sql are also packaged in the tar.gz distribution in the doc folder so no need to make comments if installing from the tar ball. Comments are also included as part of the CREATE EXTENSION install.

make comments

PostGIS 2.0 버전부터 소개되었습니다. 빠른 참조 또는 학습용 유인물에 적합한 참조 자료(cheat sheet) html 파일을 생성합니다. 파일 생성에 xsltproc가 필요하며, doc 폴더 안에 다음topology_cheatsheet.html, tiger_geocoder_cheatsheet.html, raster_cheatsheet.html, postgis_cheatsheet.html 4개의 파일을 생성할 것입니다.

html 및 pdf 형식으로 미리 만들어진 파일들을 PostGIS / PostgreSQL Study Guides 에서 다운로드받을 수 있습니다.

make cheatsheets

2.2.5. PostGIS Extensions 빌드 및 배포

PostgreSQL 9.1 이상을 사용 중이라면 PostGIS extentions은 자동적으로 빌드 및 설치됩니다.

소스 저장소로부터 생성할 경우에는, 먼저 function descriptions 부터 빌드해야 합니다. docbook을 설치하셨다면 빌드할 수 있고, 다음 명령을 통해 수동으로 생성할 수도 있습니다:

make comments

만약 사용자가 tar 파일 배포본을 이용해 빌드한다면 미리 빌드된 것이 tar 파일과 함께 배포됨으로 comments를 따로 빌드할 필요가 없습니다.

만약 PostgreSQL 9.1을 기반으로 빌드 중이라면 extensions은 설치 과정의 일환으로 자동 빌드될 것입니다. 만약 필요하다면 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
[Note]

make check uses psql to run tests and as such can use psql environment variables. Common ones useful to override are PGUSER,PGPORT, and PGHOST. Refer to psql environment variables

extension 파일은 OS에 상관없이 PostGIS버전만 같으면 적용에 문제가 없습니다. 그러므로 PostGIS binaries가 설치된 서버에 확장 파일만 복사해도 문제가 없습니다.

만약 extension을 수동으로 또는 다른 서버에 설치하고 싶으면 다음 파일들을 사용자의 PostgreSQL 설치경로의 PostgreSQL / share / extension 폴더에 있는 extensions 폴더에서 복사하여 PostGIS가 설치되지 않은 서버에 필요한 바이너리 파일들을 넣어 주십시오.

  • 이것들이 지정되지 않은 경우 설치할 수 있는 extension 의 버전 등의 정보를 나타내는 제어 파일입니다. postgis.control, postgis_topology.control.

  • 각 extension의 /sql 폴더에 모든 파일들이 있습니다. 다음 파일들은 postgreSQL의 share/extension 폴더의 루트에 복사 되어야 함에 주의하십시오. extensions/postgis/sql/*.sql, extensions/postgis_topology/sql/*.sql

이렇게 한 다음, 사용자는 사용 가능한 extensions으로 postgis, postgis_topology 을 PgAdmin -> extensions에서 볼 수 있을 것입니다.

만약 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.3.6dev         | 3.3.6dev
 address_standardizer_data_us | 3.3.6dev         | 3.3.6dev
 postgis                      | 3.3.6dev         | 3.3.6dev
 postgis_sfcgal               | 3.3.6dev         |
 postgis_tiger_geocoder       | 3.3.6dev         | 3.3.6dev
 postgis_topology             | 3.3.6dev         |
(6 rows)

만약 사용자가 쿼리하는 데이터베이스에 extension이 설치되어 있다면, 사용자는 installed_version 컬럼에서 이름을 볼 수 있습니다. 만약 아무 레코드도 없다면 서버에 postgis extension이 전혀 설치되어 있지 않음을 뜻합니다. PgAdmin III 1.14이상 버전에서는 데이터베이스 탐색 트리의 extensions에서 마우스 오른쪽 버튼 클릭을 통해 업그레이드 또는 삭제를 허용합니다.

extension이 이용 가능한 상태라면 pgAdmin extension 인터페이스 또는 다음의 sql 명령을 실행함으로써 선택한 데이터베이스 안에 postgis extension을 설치할 수 있습니다:

CREATE EXTENSION postgis;
CREATE EXTENSION postgis_sfcgal;
CREATE EXTENSION fuzzystrmatch; --needed for postgis_tiger_geocoder
--optional used by postgis_tiger_geocoder, or can be used standalone
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.3.6dev
Schema      | public
Description | PostGIS geometry, geography, and raster spat..
-[ RECORD 2 ]-------------------------------------------------
-
Name        | postgis_tiger_geocoder
Version     | 3.3.6dev
Schema      | tiger
Description | PostGIS tiger geocoder and reverse geocoder
-[ RECORD 3 ]-------------------------------------------------
-
Name        | postgis_topology
Version     | 3.3.6dev
Schema      | topology
Description | PostGIS topology spatial types and functions
[Warning]

spatial_ref_sys, layer, topology 확장 테이블은 백업되지 않습니다. 이것들은 postgis 또는 postgis_topology extension이 백업이 될 경우에만 백업이 가능합니다. 이는 전체 데이터베이스가 백업될 때에만 발생한다고 볼 수 있습니다. PosgGIS 2.0.1에서는 데이터베이스 백업시 srid 레코드만이 백업됩니다. 이와 관한 문제를 발견하면 trac 티켓을 발행해주십시오. extension 테이블의 구조들은 CREATE EXTENSION과 함께 생성되기 때문에 백업되지 않습니다. 이러한 방식은 PostgreSQL extension 모델에 적용되기 때문에 조치를 취할 수 있는 방법이 없습니다.

우리의 멋진 확장 프로그램 시스템 없이 3.3.6dev 을 설치했다면, 먼저 다음 업그레이드 스크립트를 실행해서 확장 프로그램 기반 최신 버전으로 변경할 수 있습니다: 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;

2.2.6. 테스트

만약 PostGIS 빌드를 테스트하고 싶다면, 실행하십시오.

make check

위 명령어는 활성 PostgreSQL 데이터베이스 바탕으로 생성된 라이브러리를 이용하여 다양한 확인과 회귀 테스트를 실행할 것입니다.

[Note]

PostgreSQL, GEOS, 또는 Proj4를 표준이 아닌 경로에 설치한 경우, LD_LIBRARY_PATH 환경 변수에 해당 라이브러리 경로를 설정해주어야 합니다.

[Caution]

현재, make check 검사들을 실시할 때에는 PATHPGPORT 환경 변수를 따릅니다. PostgreSQL의 설정 매개변수인 --with-pgconfig에 명시되어 있어도 이것을 적용하지 않습니다. 따라서, PostgreSQL 설치시의 환경설정과 일치하도록 PATH를 수정해주십시오.

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_geocoderaddress_standardizer 확장 프로그램은 현재 표준 PostgreSQL 설치검사(installcheck)만을 지원합니다. 이 확장 프로그램들을 테스트하려면 다음을 실행하십시오. 주의: 이미 PostGIS 코드 폴더의 루트에서 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 지오코딩 도구의 경우, 사용자의 PostgreSQL 인스턴스 안에서 PostGIS 및 fuzzystrmatch 확장 프로그램을 이용할 수 있는지 확인하십시오. address_standardizer 지원이 되도록 PostGIS를 빌드했다면 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.
=====================

2.2.7. 설치

PostGIS 설치를 위해서 다음을 입력하십시오.

make install

이것은 --prefix 설정 파라미터에 정의된 하위 경로에 PostGIS 설치 파일을 복사할 것입니다.

  • 로더(loader)와 덤퍼 바이너리 들은 [prefix]/bin에 설치됩니다.

  • postgis.sql와 같은 SQL 파일들은 [prefix]/share/contrib에 설치됩니다.

  • PostGIS 라이브러리들은 [prefix]/lib에 설치됩니다.

만약 기존에 postgis_comments.sql, raster_comments.sql 파일을 생성하기 위해 make comments 명령어를 실행한 적이 있으시다면, 다음을 실행해 sql 파일을 설치하십시오.

make comments-install

[Note]

xsltproc의 적용 이후 일반적인 설치로부터 postgis_comments.sql, raster_comments.sql, topology_comments.sql는 분리되었습니다.

2.3. 주소 표준화 도구 설치 및 활용

address_standardizer 확장 프로그램은 별도로 다운로드해야 하는 별도의 패키지였습니다. PostGIS 2.2 버전부터는 내장되어 있습니다. 이 확장 프로그램이 무슨 일을 하고 사용자의 필요에 따라 어떻게 설정하는지에 대한 자세한 정보는 Section 14.1, “주소 표준화 도구” 를 참조하십시오.

이 표준화 도구는 Normalize_Address 대신 PostGIS 용으로 패키징된 TIGER 지오코딩 도구(geocoder)와 함께 쓰일 수 있습니다. 이렇게 대신 사용하는 방법은 Section 2.4.3, “주소 표준화 도구를 TIGER 지오코딩 도구와 함께 사용” 을 참조하십시오. 주소 표준화 도구를 사용자의 다른 지오코딩 도구를 위한 구성 요소(building block)로 사용하거나, 주소를 더 쉽게 비교하기 위해 사용자 주소를 표준화하는 데 사용할 수도 있습니다.

주소 표준화 도구는 PCRE에 의존성을 갖습니다. PCRE는 많은 유닉스 파생 시스템에 일반적으로 이미 설치되어 있지만, http://www.pcre.org 에서 최신 버전을 다운로드할 수 있습니다. Section 2.2.3, “설정” 과정에서 PCRE를 찾았다면, 주소 표준화 도구 확장 프로그램을 자동적으로 빌드할 것입니다. 사용자가 사용하고자 하는 PCRE를 따로 설치한 경우, 설정 파라미터 --with-pcredir=/path/to/pcre/path/to/pcre 부분에 사용자의 PCRE include 및 lib 디렉터리의 루트 폴더를 입력하십시오.

윈도우 사용자의 경우 PostGIS 2.1 이상 버전 번들은 이미address_standardizer와 함께 패키징되어 있으므로 컴파일할 필요없이 바로 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

2.3.1. Regex::Assemble 설치

address_standardizer 확장 프로그램을 컴파일하는 데 펄 Regex:Assemble은 더 이상 필요없습니다. 펄 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

또는 우분투/데비안 시스템의 경우 다음 작업을 해야 할 수도 있습니다.

sudo perl -MCPAN -e "install Regexp::Assemble"

2.4. Tiger Geocoder의 설치, 업그레이드 및 데이터 불러오기

Extras like Tiger geocoder may not be packaged in your PostGIS distribution. If you are missing the tiger geocoder extension or want a newer version than what your install comes with, then use the share/extension/postgis_tiger_geocoder.* files from the packages in Windows Unreleased Versions section for your version of PostgreSQL. Although these packages are for windows, the postgis_tiger_geocoder extension files will work on any OS since the extension is an SQL/plpgsql only extension.

2.4.1. TIGER 지오코딩 도구로 사용자의 PostGIS 데이터베이스 활성화: 확장 프로그램 이용

PostgreSQL 9.1 이상 버전과 PostGIS 2.1 이상 버전을 사용중이라면, TIGER 지오코딩 도구를 설치하는 데 새로운 확장 프로그램 모델을 활용할 수 있습니다. 그 방법은 다음과 같습니다.

  1. 먼저 PostGIS 2.1 이상 버전의 바이너리를 다운로드하거나 컴파일해서 일반적인 방법으로 설치하십시오. TIGER 지오코딩 도구는 물론 필수 확장 프로그램도 함께 설치될 것입니다.

  2. PSQL, pgAdmin 또는 다른 도구를 통해 사용자 데이터베이스에 연결해서 다음 SQL 명령어를 실행하십시오. 이미 PostGIS가 설치된 데이터베이스에 설치하는 경우, 첫 번째 단계를 수행할 필요는 없다는 사실을 주의하십시오. 이미 fuzzystrmatch 확장 프로그램이 설치되어 있다면 이 두 번째 단계도 수행할 필요가 없습니다.

    CREATE EXTENSION postgis;
    CREATE EXTENSION fuzzystrmatch;
    CREATE EXTENSION postgis_tiger_geocoder;
    --this one is optional if you want to use the rules based standardizer (pagc_normalize_address)
    CREATE EXTENSION address_standardizer;

    이미 postgis_tiger_geocoder 확장 프로그램을 설치했고 최신 버전으로 업데이트만 하고자 할 경우:

    ALTER EXTENSION postgis UPDATE;
    ALTER EXTENSION postgis_tiger_geocoder UPDATE;

    tiger.loader_platformtiger.loader_variables 에 사용자 지정 항목을 만들었거나 변경한 경우 이 테이블들도 업데이트해야 할 수도 있습니다.

  3. 제대로 설치되었는지 확인하려면 사용자 데이터베이스에 다음 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
  4. tiger.loader_platform 테이블에 사용자의 실행 파일과 서버의 경로를 새 레코드로 생성하십시오.

    예를 들어 sh 규약(convention)을 따르는 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';

    그 다음 debbie의 pg, unzip,shp2pgsql, PSQL 등의 경로 위치에 맞도록 declare_sect 열의 경로를 편집하십시오.

    loader_platform 테이블을 편집하지 않을 경우, 각 항목의 흔히 있는(common case) 위치만을 담게 되며 스크립트가 생생된 후 생성된 스크립트를 직접 편집해야 할 것입니다.

  5. As of PostGIS 2.4.1 the Zip code-5 digit tabulation area zcta5 load step was revised to load current zcta5 data and is part of the Loader_Generate_Nation_Script when enabled. It is turned off by default because it takes quite a bit of time to load (20 to 60 minutes), takes up quite a bit of disk space, and is not used that often.

    To enable it, do the following:

    UPDATE tiger.loader_lookuptables SET load = true WHERE table_name = 'zcta520';

    If present the Geocode function can use it if a boundary filter is added to limit to just zips in that boundary. The Reverse_Geocode function uses it if the returned address is missing a zip, which often happens with highway reverse geocoding.

  6. 서버의 루트, 또는 서버에 충분히 빠른 네트워크로 연결된 경우 사용자 PC의 루트에 gisdata 라는 폴더를 생성하십시오. 이 폴더로 TIGER 파일을 다운로드해서 처리할 것입니다. 서버의 루트에 폴더를 만드는 게 마음에 안 들거나, 또는 단순히 다른 폴더로 변경하고 싶다면, tiger.loader_variables 테이블의 staging_fold 항목을 편집하십시오.

  7. gisdata 폴더 또는 사용자가 staging_fold 에 지정한 폴더 안에 temp라는 폴더를 생성하십시오. 다운로드한 TIGER 데이터를 로더가 이 temp 폴더에 압축해제할 것입니다.

  8. Then run the Loader_Generate_Nation_Script SQL function make sure to use the name of your custom profile and copy the script to a .sh or .bat file. So for example to build the nation load:

    psql -c "SELECT Loader_Generate_Nation_Script('debbie')" -d geocoder -tA > /gisdata/nation_script_load.sh
  9. Run the generated nation load commandline scripts.

    cd /gisdata
    sh nation_script_load.sh
  10. After you are done running the nation script, you should have three tables in your tiger_data schema and they should be filled with data. Confirm you do by doing the following queries from psql or pgAdmin

    SELECT count(*) FROM tiger_data.county_all;
    count
    -------
      3233
    (1 row)
    SELECT count(*) FROM tiger_data.state_all;
    count
    -------
        56
    (1 row)
    
  11. By default the tables corresponding to bg, tract, tabblock are not loaded. These tables are not used by the geocoder but are used by folks for population statistics. If you wish to load them as part of your state loads, run the following statement to enable them.

    UPDATE tiger.loader_lookuptables SET load = true WHERE load = false AND lookup_name IN('tract', 'bg', 'tabblock');

    Alternatively you can load just these tables after loading state data using the Loader_Generate_Census_Script

  12. For each state you want to load data for, generate a state script Loader_Generate_Script.

    [Warning]

    DO NOT Generate the state script until you have already loaded the nation data, because the state script utilizes county list loaded by nation script.

  13. psql -c "SELECT Loader_Generate_Script(ARRAY['MA'], 'debbie')" -d geocoder -tA > /gisdata/ma_load.sh
  14. 생성된 명령어 스크립트를 실행하십시오.

    cd /gisdata
    sh ma_load.sh
  15. 모든 데이터를 로딩한 다음 또는 어떤 정지 지점에서 모든 TIGER 테이블을 분석해서 (상속된 통계를 포함한) 통계(stat)를 업데이트하는 것이 좋습니다.

    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;

2.4.1.1. TIGER 지오코딩 도구 정규 설치를 확장 프로그램 모델로 변환

확장 프로그램 모델을 사용하지 않고 TIGER 지오코딩 도구를 설치했다면, 다음과 같이 확장 프로그램 모델로 변환시킬 수 있습니다:

  1. 확장 프로그램 제외(non-extension) 모델을 업그레이드하려면 Section 2.4.5, “Tiger Geocoder 업그레이드” 의 지침을 따라해보십시오.

  2. PSQL 또는 pgAdmin을 통해 사용자 데이터베이스에 연결하고 다음 명령어를 실행하십시오:

    CREATE EXTENSION postgis_tiger_geocoder FROM unpackaged;

2.4.2. TIGER 지오코딩 도구로 사용자의 PostGIS 데이터베이스 활성화: 확장 프로그램 없이

우선 앞의 설명에 따라 PostGIS를 설치하십시오.

extras 폴더가 없을 경우, http://postgis.net/stuff/postgis-3.3.6dev.tar.gz 에서 다운로드하십시오.

tar xvfz postgis-3.3.6dev.tar.gz

cd postgis-3.3.6dev/extras/tiger_geocoder

tiger_loader_2015.sql (또는 다른 년도를 로드하고자 할 경우, 사용자가 찾을 수 있는 최신 로더)를 사용자의 실행 가능한 서버 등의 경로로 편집하거나, 그 대신 설치 완료 후 loader_platform 테이블을 업데이트할 수도 있습니다. 이 파일 또는 loader_platform 테이블을 편집지 않는다면, 각 항목의 흔히 쓰이는(common case) 위치만 담게 되어 Loader_Generate_Nation_ScriptLoader_Generate_Script SQL 함수를 실행해서 생성된 스크립트를 직접 편집해야 할 것입니다.

TIGER 지오코딩 도구를 처음 설치하는 경우, 윈도우 시스템이라면 create_geocode.bat 스크립트를, Linux/Unix/Mac OSX 시스템이라면 create_geocode.sh 를 사용자의 PostgreSQL에 특화된 설정으로 편집한 다음 명령 프롬프트에서 각각 상응하는 스크립트를 실행하십시오.

tiger 스키마가 데이터베이스에 있는 지와 사용제 데이터베이스 search_path에 해당되는 지를 확인하십시오. 안되어 있다면 아래 명령을 함께 추가하십시오.

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
                        

2.4.3. 주소 표준화 도구를 TIGER 지오코딩 도구와 함께 사용

사용자들의 많은 불평 가운데 하나는 주소 정규화 도구 Normalize_Address 함수가 지오코딩 작업 전 준비 과정에서 주소를 정규화한다는 것입니다. 정규화 도구는 완벽하지 않아 그 불완전함을 수정하려면 막대한 노력이 필요합니다. 그래서 우리는 훨씬 나은 주소 표준화 도구 엔진을 가진 또다른 프로젝트와 통합시켰습니다. 이 새로운 address_standardizer를 이용하려면, Section 2.3, “주소 표준화 도구 설치 및 활용” 에 설명된 대로 확장 프로그램을 컴파일해서 사용자 데이터베이스에 확장 프로그램으로 설치하십시오.

postgis_tiger_geocoder 를 설치했던 데이터베이스에 이 확장 프로그램을 설치했다면, Normalize_Address 대신 Pagc_Normalize_Address 를 이용할 수 있습니다. 이 확장 프로그램은 TIGER 유무와 상관없이 동작하므로, 국제 주소와 같은 다른 데이터 소스와 함께 사용할 수 있습니다. 실제로 TIGER 지오코딩 도구 확장 프로그램은 규칙 테이블 ( tiger.pagc_rules) , 지명 색인 테이블 (tiger.pagc_gaz), 그리고 어휘 목록 테이블 (tiger.pagc_lex) 자체 수정 버전과 함께 패키징되어 있습니다. 사용자 자신의 필요에 따라 이들을 추가하고 업데이트해서 표준화 작업 과정을 향상시킬 수 있습니다.

2.4.4. Tiger Data 불러오기

Tiger 데이터를 로딩하기 위한 보다 자세한 설명은 extras/tiger_geocoder/tiger_2011/README에서 이용 가능합니다. 여기서는 일반적인 과정만 안내해 드립니다.

인구조사 웹사이트에서 필요한 주의 데이터를 다운로드 받습니다. 압축을 풀면 주 단위로 별개의 세트로 이뤄져 있습니다. 각 주 테이블은 tiger스키마 정의에 따라 접속 및 쿼리 할 수 있고, Drop_State_Tables_Generate_Script를 다시 불러오거나 삭제하는 등의 작업을 실시할 수 있습니다.

데이터를 로딩하기 위해서는 다음과 같은 도구들이 필요합니다:

  • 인구조사 웹사이트에서 받은 압축 파일을 풀기 위한 툴

    Unix 계열 시스템에서는 대부분 unzip으로 해제할 수 있습니다.

    윈도우의 경우, 무료 압축/압축해제 툴인 7-zip이 http://www.7-zip.org/에서 다운로드 가능합니다.

  • PostGIS 기본 설치시 설치되는 shp2pgsql 명령

  • 웹 다운로드 툴인 wget은 대부분의Unix/Linux 시스템에 설치되어 있습니다.

    윈도우를 사용 중이면 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.4.5. Tiger Geocoder 업그레이드

PostGIS 2.0 이상 버전과 함께 패키징된 TIGER 지오코딩 도구를 이미 설치했다면, 그리고 사용자가 간절히 바라는 수정 사항이 있다면, 언제라도, 심지어 tar 파일 내부에서도 함수를 업그레이드할 수 있습니다. 이 작업은 확장 프로그램과 함께 설치되지 않은 TIGER 지오코딩 도구라야만 가능합니다.

extras 폴더가 없을 경우, http://postgis.net/stuff/postgis-3.3.6dev.tar.gz 에서 다운로드하십시오.

tar xvfz postgis-3.3.6dev.tar.gz

cd postgis-3.3.6dev/extras/tiger_geocoder/tiger_2011

윈도우 시스템이라면 upgrade_geocoder.bat 스크립트를, Linux/Unix/Mac OSX 시스템이라면 upgrade_geocoder.sh 스크립트를 찾으십시오. 사용자의 PostGIS 데이터베이스 사양에 맞춰 파일을 편집하십시오.

2010이나 2011을 업그레이드하는 경우, 로더 스크립트의 해당 라인을 주석 처리(unremark out)해야 2012 데이터를 로드하기 위한 최신 스크립트를 얻을 수 있다는 점을 기억하십시오.

명령 프롬프트에서 각 플랫폼에 상응하는 스크립트를 실행하십시오.

다음으로 모든 nation 테이블을 drop 하고 새로 불러옵니다. 이 SQL 문장으로 drop 스크립트를 만듭니다. 자세한 내용은 다음을 참고하십시오. Drop_Nation_Tables_Generate_Script

SELECT drop_nation_tables_generate_script();

생성된 drop SQL 문장을 실행하십시오.

이 SELECT 구문으로 nation load 스크립트를 생성합니다. 자세한 내용을 다음을 참고하십시오. Loader_Generate_Nation_Script

윈도우용

SELECT loader_generate_nation_script('windows'); 

unix/linux 용

SELECT loader_generate_nation_script('sh');

생성된 스크립트를 어떻게 실행하는지 배우시려면 Section 2.4.4, “Tiger Data 불러오기”을 참고하십시오. 이것은 단지 한번만 하면 됩니다.

[Note]

사용자는 2010/2011 state 테이블을 합칠 수도 있고 각 state 별로 업그레이드 할 수도 있습니다. state를 2011로 업데이트 하기 전에, Drop_State_Tables_Generate_Script을 이용해 2010 테이블들을 drop 해야 합니다.

2.5. 설치 과정에서 흔히 발생하는 문제들

인스톨이나 업그레이드 시 잘 되지 않을 경우 확인해야 할 몇 가지 사항은 아래와 같습니다.

  1. PostgreSQL 11 또는 그 보다 최신 버전을 설치하셨는지 체크하십시오. 현재 작동하고 계시는 PostgreSQL의 버전과 동일한 PostgreSQL 소스 버전을 바탕으로 컴파일하였는지 확인해주십시오. (Linux) 배포본이 이미 PostgreSQL이 설치된 경우 중복 설치가 될 수 있고, 또는 이전에 설치한 사실을 잊어버렸을 수도 있습니다. PostGIS는 PostgreSQL 11 또는 그 이상 버전에서 작동되므로 구 버전을 이용 시 예상하지 못한 에러들이 발생할 수 있습니다. 어떤 PostgreSQL 버전이 작동하고 있는지 확인하기 위해서는 psql을 통하여 데이터베이스에 접속해 다음의 쿼리를 실행하십시오:

    SELECT version();

    RPM 방식이라면 다음과 같은 rpm 커맨드로 이전 설치 패키지의 존재를 확인할 수 있습니다: rpm -qa | grep postgresql

  2. 만약 업그레이드가 실패하면 기존 PostGIS설치 버전으로 복원하셔야 합니다.

    SELECT postgis_full_version();

또한 PostreSQL, Proj4 라이브러리 및 GEOS 라이브러리에 대한 버전과 경로에 대한 설정이 올바른지 확인하십시오.

  1. 설정은 postgis_config.hh 파일을 생성하기 위해 사용됩니다. POSTGIS_PGSQL_VERSION, POSTGIS_PROJ_VERSION and POSTGIS_GEOS_VERSION 변수가 정확한지 확인하십시오.

Chapter 3. PostGIS Administration

3.1. Performance Tuning

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.23, “PostGIS GUC(Grand Unified Custom Variable)”.

3.1.1. Startup

These settings are configured in postgresql.conf:

constraint_exclusion

  • 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.

shared_buffers

  • 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.

3.1.2. Runtime

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.

3.2. Configuring raster support

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.23, “PostGIS GUC(Grand Unified Custom Variable)”.

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"
[Note]

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/10/main/environment where 10 refers to version of PostgreSQL and main refers to the cluster.

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.

3.3. 공간 데이터베이스 생성

3.3.1. Spatially enable database using EXTENSION

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

3.3.2. Spatially enable database without using EXTENSION (discouraged)

[Note]

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.2/

    # 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

3.3.3. Create a spatially-enabled database from a template

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

3.4. Upgrading spatial databases

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.

3.4.1. Soft 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, you are advised to switch your install to extensions because the script way is no longer supported.

3.4.1.1. Soft Upgrade 9.1+ using extensions

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.

If you are running PostGIS 3 or above, then you should use the PostGIS_Extensions_Upgrade function to upgrade to the latest version you have installed.

SELECT postgis_extensions_upgrade();

If you are running PostGIS 2.5 or lower, then do the following:

ALTER EXTENSION postgis UPDATE;
SELECT postgis_extensions_upgrade();
-- This second call is needed to rebundle postgis_raster extension
SELECT postgis_extensions_upgrade();

If you have multiple versions of PostGIS installed, and you don't want to upgrade to the latest, you can explicitly specify the version as follows:

ALTER EXTENSION postgis UPDATE TO "3.3.6dev";
ALTER EXTENSION postgis_topology UPDATE TO "3.3.6dev";

If you get an error notice something like:

No migration path defined for … to 3.3.6dev

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.3.6dev" 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.3.6devnext";
ALTER EXTENSION postgis_topology UPDATE TO "3.3.6devnext";
[Note]

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 CREATE EXTENSION postgis and thus picks up the newest latest version during restore.

[Note]

If you are upgrading PostGIS extension from a version prior to 3.0.0, you will have a new extension postgis_raster which you can safely drop, if you don't need raster support. You can drop as follows:

DROP EXTENSION postgis_raster;

3.4.1.2. Soft Upgrade Pre 9.1+ or without extensions

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.3.6dev/*_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

You are advised to switch to an extension based install by running

psql -c "SELECT postgis_extensions_upgrade();"
[Note]

If you can't find the postgis_upgrade.sql specific for upgrading your version you are using a version too early for a soft upgrade and need to do a HARD UPGRADE.

The PostGIS_Full_Version function should inform you about the need to run this kind of upgrade using a "procs need upgrade" message.

3.4.2. Hard upgrade

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:

  1. 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
  2. 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.

  3. 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:

  1. 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.

  2. 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

Chapter 4. Data Management

4.1. GIS (벡터) 데이터 로드

4.1.1. OGC Geometry

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, “SPATIAL_REF_SYS 테이블과 공간 참조 시스템”.

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.4, “Geometry Validation”

4.1.1.1. Point

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)

4.1.1.2. LineString

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(0 0,1 1,1 2)

4.1.1.3. LinearRing

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.

CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0)

4.1.1.4. Polygon

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))

4.1.1.5. MultiPoint

A MultiPoint is a collection of Points.

MULTIPOINT((0 0),(1 2))

4.1.1.6. MultiLineString

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))

4.1.1.7. MultiPolygon

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(((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)))

4.1.1.8. GeometryCollection

A GeometryCollection is a heterogeneous (mixed) collection of geometries.

GEOMETRYCOLLECTION(POINT(2 3),LINESTRING(2 3,3 4))

4.1.1.9. PolyhedralSurface

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( ((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)) )

4.1.1.10. Triangle

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))

4.1.1.11. TIN

A TIN is a collection of non-overlapping Triangles representing a Triangulated Irregular Network.

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)) )

4.1.2. SQL-MM Part 3

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.

[Note]

SQL-MM 실행 과정에서 지정된 허용 오차를 기준으로 부동소수점을 비교합니다. 현재 허용 오차는 1E-8입니다.

4.1.2.1. CircularString

CIRCULARSTRING은 기본 곡선 유형으로, 선형계의 LINESTRING과 비슷합니다. 단일 분절에는 시작점과 종단점(첫 번째 및 세 번째) 그리고 곡선 위의 다른 한 점 이렇게 포인트 세 개가 필요합니다. 예외는 닫힌 원으로, 이 경우 시작점과 종단점이 동일합니다. 이 경우 두 번째 포인트는 원호의 중심, 즉 원의 반대편이 되어야만 합니다. 원호를 함께 묶으려면, LINESTRING과 마찬가지로 한 원호의 마지막 포인트가 다음 원호의 첫 번째 포인트가 되어야 합니다. 즉 유효한 원형 스트링은 1을 초과하는 홀수 개수의 포인트들을 가져야만 한다는 뜻입니다.

CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0)

4.1.2.2. CompoundCurve

복심곡선(compound curve)이란 곡선(원호) 분절과 선형 분절이 함께 있는 연속적인 단일 곡선을 말합니다. 즉 구성 요소들이 잘 형성되어야 함은 물론, (마지막을 제외한) 모든 구성 요소의 종단점이 다음 구성 요소의 시작점과 일치해야한 한다는 뜻입니다.

COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))

4.1.2.3. CurvePolygon

CURVEPOLYGON은 일반 폴리곤입니다. 외곽선과 함께 0개 이상의 내곽선을 가지고 있을 뿐입니다. 차이라면 내외곽선이 원형 스트링, 선형 스트링, 또는 복합 스트링 형태를 할 수 있다는 점입니다.

PostGIS는 1.4버전부터 만곡 폴리곤에 대해 복심곡선을 지원합니다.

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) )

4.1.2.4. MultiCurve

MULTICURVE는 원형 스트링, 선형 스트링, 복합 스트링을 포함할 수 있는 곡선 집합입니다.

MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )

4.1.2.5. MultiSurface

MULTISURFACE는 면 집합으로, (선형) 폴리곤일 수도 만곡 폴리곤일 수도 있습니다.

MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0),(1 1, 3 3, 3 1, 1 1)),((10 10, 14 12, 11 10, 10 10),(11 11, 11.5 11, 11 11.5, 11 11)))

4.1.3. OpenGIS WKB 및 WKT

OpenGIS사양서에는 공간 오브젝트들을 나타내는 두 가지 표준 방법이 정의되어 있습니다: Well-Known Text (WKT) 형태와 Well-Known Binary (WKB) 형태. WKT와 WKB 모두 오브젝트 타입과 오브젝트를 구성하는 좌표들에 대한 정보를 포함하고 있습니다.

공간 참조 시스템의 WKT(Well-Known Text) 표현식입니다. 다음은 WKT SRS 표현식의 예입니다:

  • POINT(0 0)

  • POINT(0 0)

  • POINT(0 0)

  • POINT EMPTY

  • LINESTRING(0 0,1 1,1 2)

  • LINESTRING

  • 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((0 0),(1 2))

  • MULTIPOINT

  • 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

Input and output of WKT is provided by the functions ST_AsText and ST_GeomFromText:

bytea WKB = ST_AsBinary(geometry);
text WKT = ST_AsText(geometry);
geometry = ST_GeomFromWKB(bytea WKB, SRID);
geometry = ST_GeometryFromText(text WKT, SRID);

예를 들어 OGC 공간 객체를 생성하고 삽입하기 위한 유효한 삽입 구문은 다음과 같을 것입니다:

INSERT INTO geotable ( the_geom, the_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:

  • POINT(0 0)

    WKB: 0101000000000000000000F03F000000000000F03

  • LINESTRING(0 0,1 1,1 2)

    WKB: 0102000000020000000000000000000040000000000000004000000000000022400000000000002240

Input and output of WKB is provided by the functions ST_AsBinary and ST_GeomFromWKB:

bytea WKB = ST_AsBinary(geometry);
text WKT = ST_AsText(geometry);
geometry = ST_GeomFromWKB(bytea WKB, SRID);
geometry = ST_GeometryFromText(text WKT, SRID);

예를 들어 OGC 공간 객체를 생성하고 삽입하기 위한 유효한 삽입 구문은 다음과 같을 것입니다:

INSERT INTO geotable ( the_geom, the_name )
VALUES ( ST_GeomFromText('POINT(-126.4 45.32)', 312), 'A Place');

4.2. Geometry Data Type

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 도형 유형 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 Reference for the full list of functions.

[Note]

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".

OpenGIS 사양서는 공간 객체의 내부 저장 형식이 공간 참조 시스템 식별자(SRID)를 포함하도록 요구합니다. 데이터베이스에 삽입될 공간 객체 생성시 SRID가 필요합니다.

To make querying geometry efficient PostGIS defines various kinds of spatial indexes, and spatial operators to use them. See Section 4.9, “인덱스 빌드 작업” and Section 5.2, “Using Spatial Indexes” for details.

4.2.1. OpenGIS WKB 및 WKT

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
(1 row)

PostGIS EWKT output has a few differences to OGC WKT:

  • For 3DZ geometries the Z qualifier is omitted:

    POINT(0 0)

    POINT(0 0)

  • For 3DM geometries the M qualifier is included:

    POINT(0 0)

    POINT(0 0)

  • For 4D geometries the ZM qualifier is omitted:

    POINT(0 0)

    POINT(0 0)

EWKT avoids over-specifying dimensionality and the inconsistencies that can occur with the OGC/ISO format, such as:

  • POINT(0 0)

  • POINT(0 0)

  • POINT(0 0)

[Caution]

PostGIS는 현재 OGC 형식의 상위 집합인 형식을 확장합니다(유효한 모든 WKB/WKT는 유효한 EWKB/EWKT가 됩니다). 하지만 향후 달라질 수도 있습니다. 특히 OGC가 PostGIS 확장 프로그램과 상충하는 새 형식을 들고 나온다면 말입니다. 그러므로 이 피처에 의존해서는 안 됩니다!

피쳐들의 공간 오브젝트들의 텍스트 문자열표현들(WKT) 의 예들로는 다음과 같은 것들이 있습니다:

  • 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)) )

다음과 같은 인터페이스를 이용해서 이 형식을 입력/출력할 수 있습니다.

bytea EWKB = ST_AsEWKB(geometry);
text EWKT = ST_AsEWKT(geometry);
geometry = ST_GeomFromEWKB(bytea EWKB);
geometry = ST_GeomFromEWKT(text EWKT);

예를 들어 PostGIS 공간 객체를 생성하고 삽입하기 위한 유효한 삽입 구문은 다음과 같을 것입니다:

INSERT INTO geotable ( the_geom, the_name )
  VALUES ( ST_GeomFromEWKT('SRID=312;POINTM(-126.4 45.32 15)'), 'A Place' )

4.3. PostGIS 지리형 유형

지리형 유형은 (종종 "측지" 좌표, 또는 "위도/경도"나 "경도/위도"라고 불리는) "지리" 좌표로 표현되는 공간 피처를 자체적으로 지원합니다. 지리 좌표는 각도 단위(도)를 사용하는 구면(球面) 좌표입니다.

PostGIS 도형 유형은 평면을 기반으로 합니다. 평면상에서 두 포인트 사이의 가장 짧은 경로는 직선입니다. 즉 데카르트 수학과 직선 벡터를 이용해서 도형에 대해 계산(면적, 거리, 길이, 교차점 등)한다는 뜻입니다.

PostGIS 지리형 유형은 구면을 기반으로 합니다. 구면상에서 두 포인트 사이의 가장 짧은 경로는 대권(大圈; great circle arc)입니다. 즉 지리형에 대한 계산(면적, 거리, 길이, 교차점 등)은 더 복잡한 수학을 이용해서 구면상에서 이루어져야 한다는 뜻입니다. 더 정확하게 측정하려면 지구의 실제 회전타원체(spheroidal shape)를 고려해서 계산해야 하는데, 수학이 아주 복잡해질 수밖에 없습니다.

기저 수학이 훨씬 더 복잡하기 때문에, 지리형 유형을 위해 정의된 함수는 도형 유형의 함수보다 더 적습니다. 시간이 지날수록 새 알고리즘이 추가되어 지리형 유형의 역량은 확장될 것입니다.

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, “SPATIAL_REF_SYS 테이블과 공간 참조 시스템”.

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 ST_DWithin are in meters.

4.3.1. 공간 테이블 생성

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:

  • 유형 변경자가 허용하는 값은 다음과 같습니다. POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON. 또 이 변경자는 Z, M 및 ZM이라는 접미사를 통해 차원수 제약도 지원합니다. 따라서, 예를 들자면 'LINESTRINGM'의 변경자는 3차원 이하의 라인 스트링만을 허용할 것이며, 세 번째 차원을 기준으로 취급할 것입니다. 마찬가지로 'POINTZM'은 네 가지 차원의 데이터를 입력해야 할 것입니다.

  • 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:

  • POINT: 2D 포인트 도형을 담은 테이블 생성:

    CREATE TABLE testgeog(gid serial PRIMARY KEY, the_geog geography(POINT,4326) );
  • POINT: 2D 포인트 도형을 담은 테이블 생성:

    CREATE TABLE testgeog(gid serial PRIMARY KEY, the_geog geography(POINT,4326) );
  • Create a table with 3D (XYZ) POINTs and an explicit SRID of 4326:

    CREATE TABLE testgeog(gid serial PRIMARY KEY, the_geog geography(POINTZ,4326) );
  • Create a table with 2D LINESTRING geography with the default SRID 4326:

    CREATE TABLE testgeog(gid serial PRIMARY KEY, the_geog geography(POINT,4326) );
  • POINT: 2D 포인트 도형을 담은 테이블 생성:

    CREATE TABLE testgeog(gid serial PRIMARY KEY, the_geog geography(POINT,4326) );

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;

도형과 동일한 방법으로 인덱스를 생성합니다. PostGIS가 열 유형이 지리형인 것을 감지하고 일반적인 도형 용 평면 인덱스 대신 적절한 구면 기반 인덱스를 생성할 것입니다.

-- 테스트 테이블에 구면 인덱스 생성
  CREATE INDEX global_points_gix ON global_points USING GIST ( location );

4.3.2. PostGIS 지리형 유형

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.

-- 테스트용 테이블에 데이터를 추가해봅시다
INSERT INTO global_points (name, location) VALUES ('Town', ST_GeographyFromText('SRID=4326;POINT(-110 30)') );
INSERT INTO global_points (name, location) VALUES ('Forest', ST_GeographyFromText('SRID=4326;POINT(-109 29)') );
INSERT INTO global_points (name, location) VALUES ('London', ST_GeographyFromText('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.

=# SELECT 'SRID=4;POINT(0 0)'::geometry;

geometry
----------------------------------------------------
01010000200400000000000000000000000000000000000000
(1 row)
=# SELECT 'SRID=4;POINT(0 0)'::geometry;

geometry
----------------------------------------------------
01010000200400000000000000000000000000000000000000
(1 row)
-- 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.

쿼리 및 측정 함수는 미터 단위를 사용합니다. 따라서 거리 파라미터는 미터로 표현되어야 하고, 반환값도 미터(또는 면적의 경우 평방미터) 단위가 될 것입니다.

-- 다음은 거리 쿼리입니다. 주의: 런던이 허용 범위 1000km 밖에 있습니다
  SELECT name FROM global_points WHERE ST_DWithin(location, ST_GeographyFromText('SRID=4326;POINT(-110 29)'), 1000000);

시애틀에서 런던으로 가는 비행기가(LINESTRING(-122.33 47.606, 0.0 51.5)) 레이캬비크에(POINT(-21.96 64.15)) 얼마나 접근하는지 계산해보면, 실제 계산시 지리형이 얼마나 강력한지 알 수 있습니다.

지리형 유형이 시애틀과 런던을 잇는 대권항로와 레이캬비크 사이의 구면 상 가장 짧은 거리를 실제로 계산할 수 있습니다.

-- 지리형을 이용한 거리 계산(122.2km)
  SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geography, 'POINT(-21.96 64.15)':: geography);

대권 매퍼(Great Circle mapper) 도형 유형은 평면 세계지도 상에서 시애틀과 런던을 직선으로 잇는 경로와 레이캬비크 사이의 아무 의미도 없는 데카르트 거리를 계산합니다. 결과값의 명목상 단위를 "도(degree)"라고 할 수도 있겠지만, 결과값은 세 포인트 사이의 어떤 실제 각도 차이도 반영하지 않기 때문에 "도"라고 하는 것조차 부정확한 일이 됩니다.

-- 도형을 이용한 거리 계산(13.3"도")
  SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geometry, 'POINT(-21.96 64.15)':: geometry);

4.3.3. 도형 데이터 유형과 지리형 데이터 유형을 중첩해서 이용하는 경우

새로운 지리형 유형은 데이터를 경도/위도 좌표로 저장할 수 있도록 해주지만, 단점도 있습니다. 도형을 대상으로 정의된 함수보다 지리형 대상 함수가 더 적고, 그 정의된 함수도 실행하는 데 CPU 시간을 더 많이 잡아먹습니다.

사용자가 선택한 유형은 사용자가 빌드하는 응용 프로그램 영역에서 기대한대로 동작하도록 적합한 조건을 갖춰야 합니다. 사용자 데이터가 전세계 또는 광대한 대륙 지역을 포괄할 예정입니까 아니면 시, 도, 군 또는 그 이하의 지자체에 국한될 예정입니까?

  • 사용자 데이터가 좁은 지역에 국한된다면, 사용 가능한 실행성 및 기능성 관점에서, 적합한 투영을 선택하고 도형을 이용하는 것이 최선의 해결책이 될 수도 있습니다.

  • 사용자 데이터가 전세계 또는 대륙에 걸쳐 있을 경우, 지리형을 이용하면 일일이 어떤 투영법을 이용할지 고민하지 않고 시스템을 빌드할 수도 있습니다. 사용자 데이터를 경도/위도로 저장하고, 지리형을 대상으로 정의된 함수를 이용하십시오.

  • 투영에 대한 이해가 부족하고, 따로 공부하고 싶지도 않으며, 지리형 사용시 기능성이 제한된다는 사실을 받아들일 준비가 되어 있다면, 도형보다 지리형을 사용하는 편이 더 쉬울 수 있습니다. 그냥 사용자 데이터를 경도/위도로 로드한 다음 작업을 시작하십시오.

지리형과 도형을 각각 지원하는 함수를 비교해보려면 Section 15.11, “PostGIS Function Support Matrix” 를 참조하십시오. 지리형 함수의 목록 및 설명을 간단하게 살펴보려면 Section 15.4, “PostGIS Geography Support Functions” 를 참조하십시오.

4.3.4. 지리형 고급 FAQ

4.3.4.1. 계산 작업시 구체 상에서 계산하게 됩니까 회전타원체 상에서 하게 됩니까?
4.3.4.2. 날짜변경선과 남극/북극은 어떻습니까?
4.3.4.3. 공간 처리할 수 있는 가장 긴 원호가 무엇인가요?
4.3.4.4. 유럽이나 러시아의 면적을 계산하거나 또는 광대한 지역을 삽입하는 작업이 이렇게 느린 이유가 뭐지요?

4.3.4.1.

계산 작업시 구체 상에서 계산하게 됩니까 회전타원체 상에서 하게 됩니까?

기본적으로, 모든 거리 및 면적 계산은 회전타원체 상에서 이루어집니다. 좁은 지역을 대상으로 한 계산의 결과와 해당 지역에 적절한 투영법을 적용한 평면 상 계산 결과는 일치할 것입니다. 더 넓은 지역이라면 투영법을 적용한 평면 상 계산보다 회전타원체 상 계산이 언제나 더 정확할 것입니다.

최종 불 파라미터 'FALSE'를 설정하면 모든 지리형 함수가 구체 상 계산을 할 수 있습니다. 이렇게 하면 계산 속도가 조금 빨라질 것입니다. 특히 도형들이 매우 단순한 경우에 말입니다.

4.3.4.2.

날짜변경선과 남극/북극은 어떻습니까?

모든 계산은 날짜변경선이나 양극을 고려하지 않고 이루어집니다. 좌표가 회전타원체(경도/위도)이기 때문에 날짜변경선을 지나는 형상이라도, 계산이라는 관점에서 보면, 다른 어떤 형상과도 다를 바가 없습니다.

4.3.4.3.

공간 처리할 수 있는 가장 긴 원호가 무엇인가요?

두 포인트 사이의 "보간 라인"으로 대권호(great circle arc)를 이용합니다. 즉 대권을 따라 어느 방향으로 이동하느냐에 따라 두 포인트가 실제로는 두 가지 방식으로 만난다는 뜻입니다. 모든 코드는 포인트들이 대권을 따라 가는 두 경로 가운데 '짧은' 경로로 만난다고 가정합니다. 결과적으로, 180도 이상의 원호를 가진다면 정확히 모델링된 형상이 아니게 됩니다.

4.3.4.4.

유럽이나 러시아의 면적을 계산하거나 또는 광대한 지역을 삽입하는 작업이 이렇게 느린 이유가 뭐지요?

폴리곤이 너무나 크기 때문이지요! 광대한 지역은 두 가지 이유로 좋지 않습니다. 먼저 경계가 워낙 길기 때문에 어떤 쿼리를 실행하든 인덱스가 피처 전체를 읽어오는 경향이 있습니다. 그리고 꼭짓점 개수도 너무 많아서 거리, 밀폐 여부 등의 테스트를 할 때 적어도 한 번, 때로는 n번 이상(이때 n은 다른 후보 피처의 꼭짓점 개수) 꼭짓점 목록 전체를 훑어야 하기 때문입니다.

도형의 경우, 대용량 폴리곤을 대상으로 좁은 지역에 대한 쿼리를 할 때 사용자 도형 데이터를 더 작은 덩어리들로 "비정규화"해서 인덱스가 효율적으로 객체의 일부분을 하위 쿼리(subquery)할 수 있도록 만들어 쿼리 시 매번 전체 객체를 읽어올 필요가 없도록 하는 편이 좋습니다. 유럽 전체를 폴리곤 한 개로 저장할 수 있다고 해서 꼭 그렇게 해야 한다는 뜻은 아닙니다.

4.4. Geometry Validation

PostGIS is compliant with the Open Geospatial Consortium’s (OGC) Simple Features specification. That standard defines the concepts of geometry being simple and valid. These definitions allow the Simple Features geometry model to represent spatial objects in a consistent and unambiguous way that supports efficient computation. (Note: the OGC SF and SQL/MM have the same definitions for simple and valid.)

4.4.1. Simple Geometry

A simple geometry is one that has no anomalous geometric points, such as self intersection or self tangency.

POINT 란 0차원 도형 객체로서 상속적으로 단순형 입니다.

MULTIPOINT 는 어떤 두 좌표(POINT)도 동일하지 않은 (동일한 좌표를 공유하지 않는) 단순형 입니다.

A LINESTRING is simple if it does not pass through the same point twice, except for the endpoints. If the endpoints of a simple LineString are identical it is called closed and referred to as a Linear Ring.

(a) and (c) are simple LINESTRINGs. (b) and (d) are not simple. (c) is a closed Linear Ring.

(a)

(b)

(c)

(d)

A MULTILINESTRING is simple only if all of its elements are simple and the only intersection between any two elements occurs at points that are on the boundaries of both elements.

(e) and (f) are simple MULTILINESTRINGs. (g) is not simple.

(e)

(f)

(g)

POLYGONs are formed from linear rings, so valid polygonal geometry is always simple.

To test if a geometry is simple use the ST_IsSimple function:

SELECT
   ST_IsSimple('LINESTRING(0 0, 100 100)') AS straight,
   ST_IsSimple('LINESTRING(0 0, 100 100, 100 0, 0 100)') AS crossing;

 straight | crossing
----------+----------
 t        | f

Generally, PostGIS functions do not require geometric arguments to be simple. Simplicity is primarily used as a basis for defining geometric validity. It is also a requirement for some kinds of spatial data models (for example, linear networks often disallow lines that cross). Multipoint and linear geometry can be made simple using ST_UnaryUnion.

4.4.2. Valid Geometry

Geometry validity primarily applies to 2-dimensional geometries (POLYGONs and MULTIPOLYGONs) . Validity is defined by rules that allow polygonal geometry to model planar areas unambiguously.

A POLYGON is valid if:

  1. the polygon boundary rings (the exterior shell ring and interior hole rings) are simple (do not cross or self-touch). Because of this a polygon cannnot have cut lines, spikes or loops. This implies that polygon holes must be represented as interior rings, rather than by the exterior ring self-touching (a so-called "inverted hole").

  2. boundary rings do not cross

  3. boundary rings may touch at points but only as a tangent (i.e. not in a line)

  4. interior rings are contained in the exterior ring

  5. the polygon interior is simply connected (i.e. the rings must not touch in a way that splits the polygon into more than one part)

(h) and (i) are valid POLYGONs. (j-m) are invalid. (j) can be represented as a valid MULTIPOLYGON.

(h)

(i)

(j)

(k)

(l)

(m)

A MULTIPOLYGON is valid if:

  1. its element POLYGONs are valid

  2. elements do not overlap (i.e. their interiors must not intersect)

  3. elements touch only at points (i.e. not along a line)

(n) is a valid MULTIPOLYGON. (o) and (p) are invalid.

(n)

(o)

(p)

These rules mean that valid polygonal geometry is also simple.

For linear geometry the only validity rule is that LINESTRINGs must have at least two points and have non-zero length (or equivalently, have at least two distinct points.) Note that non-simple (self-intersecting) lines are valid.

SELECT
   ST_IsValid('LINESTRING(0 0, 1 1)') AS len_nonzero,
   ST_IsValid('LINESTRING(0 0, 0 0, 0 0)') AS len_zero,
   ST_IsValid('LINESTRING(10 10, 150 150, 180 50, 20 130)') AS self_int;

 len_nonzero | len_zero | self_int
-------------+----------+----------
 t           | f        | t

POINT and MULTIPOINT geometries have no validity rules.

4.4.3. Managing Validity

PostGIS allows creating and storing both valid and invalid Geometry. This allows invalid geometry to be detected and flagged or fixed. There are also situations where the OGC validity rules are stricter than desired (examples of this are zero-length linestrings and polygons with inverted holes.)

Many of the functions provided by PostGIS rely on the assumption that geometry arguments are valid. For example, it does not make sense to calculate the area of a polygon that has a hole defined outside of the polygon, or to construct a polygon from a non-simple boundary line. Assuming valid geometric inputs allows functions to operate more efficiently, since they do not need to check for topological correctness. (Notable exceptions are that zero-length lines and polygons with inversions are generally handled correctly.) Also, most PostGIS functions produce valid geometry output if the inputs are valid. This allows PostGIS functions to be chained together safely.

If you encounter unexpected error messages when calling PostGIS functions (such as "GEOS Intersection() threw an error!"), you should first confirm that the function arguments are valid. If they are not, then consider using one of the techniques below to ensure the data you are processing is valid.

[Note]

If a function reports an error with valid inputs, then you may have found an error in either PostGIS or one of the libraries it uses, and you should report this to the PostGIS project. The same is true if a PostGIS function returns an invalid geometry for valid input.

To test if a geometry is valid use the ST_IsValid function:

SELECT ST_IsValid('POLYGON ((20 180, 180 180, 180 20, 20 20, 20 180))');
-----------------
 t

Information about the nature and location of an geometry invalidity are provided by the ST_IsValidDetail function:

SELECT valid, reason, ST_AsText(location) AS location
    FROM ST_IsValidDetail('POLYGON ((20 20, 120 190, 50 190, 170 50, 20 20))') AS t;

 valid |      reason       |                  location
-------+-------------------+---------------------------------------------
 f     | Self-intersection | POINT(91.51162790697674 141.56976744186045)

In some situations it is desirable to correct invalid geometry automatically. Use the ST_MakeValid function to do this. (ST_MakeValid is a case of a spatial function that does allow invalid input!)

By default, PostGIS does not check for validity when loading geometry, because validity testing can take a lot of CPU time for complex geometries. If you do not trust your data sources, you can enforce a validity check on your tables by adding a check constraint:

ALTER TABLE mytable
  ADD CONSTRAINT geometry_valid_check
        CHECK (ST_IsValid(the_geom));

4.5. SPATIAL_REF_SYS 테이블과 공간 참조 시스템

A Spatial Reference System (SRS) (also called a Coordinate Reference System (CRS)) defines how geometry is referenced to locations on the Earth's surface. There are three types of SRS:

  • A geodetic SRS uses angular coordinates (longitude and latitude) which map directly to the surface of the earth.

  • A projected SRS uses a mathematical projection transformation to "flatten" the surface of the spheroidal earth onto a plane. It assigns location coordinates in a way that allows direct measurement of quantities such as distance, area, and angle. The coordinate system is Cartesian, which means it has a defined origin point and two perpendicular axes (usually oriented North and East). Each projected SRS uses a stated length unit (usually metres or feet). A projected SRS may be limited in its area of applicability to avoid distortion and fit within the defined coordinate bounds.

  • A local SRS is a Cartesian coordinate system which is not referenced to the earth's surface. In PostGIS this is specified by a SRID value of 0.

There are many different spatial reference systems in use. Common SRSes are standardized in the European Petroleum Survey Group EPSG database. For convenience PostGIS (and many other spatial systems) refers to SRS definitions using an integer identifier called a SRID.

A geometry is associated with a Spatial Reference System by its SRID value, which is accessed by ST_SRID. The SRID for a geometry can be assigned using ST_SetSRID. Some geometry constructor functions allow supplying a SRID (such as ST_Point and ST_MakeEnvelope). The EWKT format supports SRIDs with the SRID=n; prefix.

Spatial functions processing pairs of geometries (such as overlay and relationship functions) require that the input geometries are in the same spatial reference system (have the same SRID). Geometry data can be transformed into a different spatial reference system using ST_Transform. Geometry returned from functions has the same SRS as the input geometries.

4.5.1. SPATIAL_REF_SYS Table

The SPATIAL_REF_SYS table used by PostGIS is an OGC-compliant database table that defines the available spatial reference systems. It holds the numeric SRIDs and textual descriptions of the coordinate systems.

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)
)

다음과 같은 명령행 옵션이 있습니다:

srid

데이터베이스 내부에서 공간 참조 시스템(SRS)을 고유하게 식별하는 정수값입니다.

auth_name

해당 참조 시스템을 위해 인용되는 표준 또는 표준들 본체의 명칭입니다. 예를 들어 "EPSG"는 유효한 AUTH_NAME 이라고 할 수 있습니다.

auth_srid

The ID of the Spatial Reference System as defined by the Authority cited in the auth_name. In the case of EPSG, this is the EPSG code.

srtext

공간 참조 시스템의 WKT(Well-Known Text) 표현식입니다. 다음은 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]
]

For a discussion of SRS WKT, see the OGC standard Well-known text representation of coordinate reference systems.

proj4text

PostGIS는 좌표 변환 기능을 제공하기 위해 proj4 라이브러리를 이용합니다. PROJ4TEXT 열이 특정 SRID에 대응하는 proj4 좌펴 정의 스트링을 담고 있습니다. 다음은 그 예입니다:

+proj=utm +zone=10 +ellps=clrk66 +datum=NAD27 +units=m

이에 대한 자세한 정보는 http://trac.osgeo.org/proj/ 주소의 proj4 웹사이트를 참조하십시오. spatial_ref_sys.sql 파일이 모든 EPSG 투영에 대한 SRTEXTPROJ4TEXT 정의를 담고 있습니다.

When retrieving spatial reference system definitions for use in transformations, PostGIS uses fhe following strategy:

  • If auth_name and auth_srid are present (non-NULL) use the PROJ SRS based on those entries (if one exists).

  • If srtext is present create a SRS using it, if possible.

  • If proj4text is present create a SRS using it, if possible.

4.5.2. SPATIAL_REF_SYS 테이블과 공간 참조 시스템

PostGIS의 SPATIAL_REF_SYS 테이블이 proj 라이브러리가 처리할 수 있는, 좀 더 널리 사용되는 공간 참조 시스템 3000여 개를 담고 있긴 하지만 현재까지 알려진 모든 공간 참조 시스템을 다 담고 있지는 않으며, 사용자가 proj4의 구조를 잘 알고 있다면 자기만의 사용자 지정 투영을 정의할 수도 있습니다. 공간 참조 시스템 대부분은 특정 지역에 특화되어 있으며, 특화된 지역 범위 바깥에서 사용할 경우 어떤 의미도 없다는 점을 명심하십시오.

핵심 SPATIAL_REF_SYS 테이블에 정의되지 않은 공간 참조 시스템은 http://spatialreference.org/ 에 훌륭하게 정리되어 있습니다.

좀 더 널리 사용되는 공간 참조 시스템에는 4326 - WGS 84 Long Lat, 4269 - NAD 83 Long Lat, 3395 - WGS 84 World Mercator, 2163 - US National Atlas Equal Area, 그리고 NAD 83 및 WGS 84 UTM 대(帶; zone)의 공간 참조 시스템이 있습니다. 각 UTM 대는 측정에 가장 이상적인 공간 참조 시스템이지만, 6도 범위의 지역에만 특화되어 있습니다.

미국 여러 주의 평면 공간 참조 시스템(미터 또는 피트 기반)은 각 주마다 보통 한 개 또는 두 개가 존재합니다. 미터 기반 공간 참조 시스템 대부분은 SPATIAL_REF_SYS 테이블에 들어 있지만, 피트 기반 또는 ESRI가 생성한 공간 참조 시스템 중 상당수는 사용자가 spatialreference.org 에서 찾아와야 합니다.

You can even define non-Earth-based coordinate systems, such as Mars 2000 This Mars coordinate system is non-planar (it's in degrees spheroidal), but you can use it with the geography type to obtain length and proximity measurements in meters instead of degrees.

Here is an example of loading a custom coordinate system using an unassigned SRID and the PROJ definition for a US-centric Lambert Conformal projection:

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'
);

4.6. 공간 테이블 생성

4.6.1. 공간 테이블 생성

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 global_points (
    id SERIAL PRIMARY KEY,
    name VARCHAR(64),
    location GEOGRAPHY(POINT,4326)
  );

The geometry type supports two optional type modifiers:

  • 유형 변경자가 허용하는 값은 다음과 같습니다. POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON. 또 이 변경자는 Z, M 및 ZM이라는 접미사를 통해 차원수 제약도 지원합니다. 따라서, 예를 들자면 'LINESTRINGM'의 변경자는 3차원 이하의 라인 스트링만을 허용할 것이며, 세 번째 차원을 기준으로 취급할 것입니다. 마찬가지로 'POINTZM'은 네 가지 차원의 데이터를 입력해야 할 것입니다.

  • 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 testgeog(gid serial PRIMARY KEY, the_geog geography(POINT,4326) );
  • Create a table with 2D POINT geometry with the default SRID:

    CREATE TABLE testgeog(gid serial PRIMARY KEY, the_geog geography(POINT,4326) );
  • Create a table with 3D (XYZ) POINTs and an explicit SRID of 3005:

    CREATE TABLE testgeog(gid serial PRIMARY KEY, the_geog geography(POINT,4326) );
  • Create a table with 4D (XYZM) LINESTRING geometry with the default SRID:

    CREATE TABLE testgeog(gid serial PRIMARY KEY, the_geog geography(POINT,4326) );
  • Create a table with 2D POLYGON geometry with the SRID 4267 (NAD 1927 long lat):

    CREATE TABLE testgeog(gid serial PRIMARY KEY, the_geog geography(POINTZ,4326) );

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);

4.6.2. The GEOMETRY_COLUMNS VIEW

OpenGIS의 "SQL 용 단순 피처 사양서(Simple Features Specification for SQL)"는 표준 GIS 객체 유형, 그 유형들을 다루기 위해 필요한 함수, 그리고 메타데이터 테이블의 집합을 정의합니다. 메타데이터의 일관성을 유지하기 위해 공간 열 생성 및 삭제와 같은 작업은 OpenGIS가 정의한 특별한 과정을 거쳐 이루어집니다.

\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)  |

다음과 같은 명령행 옵션이 있습니다:

f_table_catalog, f_table_schema, f_table_name

도형 열을 담고 있는 피처 테이블의 조건을 완전히 만족하는 명칭입니다. "카탈로그"와 "스키마"가 오라클 용어라는 점을 주목하십시오. "카탈로그"를 대체하는 PostgreSQL 용어가 없기 때문에 해당 열은 공백으로 남게 됩니다. "스키마"의 경우 PostgreSQL 스키마 명칭이 사용됩니다(기본값은 public 입니다).

\d geometry_columns

피처 테이블이 담고 있는 도형 열의 명칭입니다.

coord_dimension

열의 공간 차원(2, 3, 또는 4차원)입니다.

srid

해당 테이블이 담고 있는 도형의 좌표가 사용하는 공간 좌표 시스템의 ID로, SPATIAL_REF_SYS 를 참조하는 외래 키(foreign key)입니다.

type

공간 객체의 유형입니다. 공간 열을 단일 유형으로 제약하려면 다음 유형 가운데 하나를 이용하십시오. POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION 또는 이에 상응하는 XYM 버전의 POINTM, LINESTRINGM, POLYGONM, MULTIPOINTM, MULTILINESTRINGM, MULTIPOLYGONM, GEOMETRYCOLLECTIONM. 혼합 유형 집합을 이용하려면 유형으로 "GEOMETRY"를 이용할 수 있습니다.

4.6.3. geometry_columns에 도형 열을 직접 등록하기

AddGeometryColumn() 함수를 쓸 수 없을 때 이런 일이 발생할 수 있는 두 가지 경우가 있는데, SQL 뷰 그리고 대규모 삽입(bulk insert)의 경우입니다. 이런 경우, 해당 열에 제약 조건을 걸어서 geometry_columns 테이블 등록을 바로잡을 수 있습니다. PostGIS 2.0 이상 버전에서는, 사용자 열이 typmod 기반이라면 생성 과정 중에 정확하게 등록할 것이기 때문에 아무것도 할 필요가 없다는 점을 기억하십시오.

-- 이렇게 생성된 뷰가 있다고 합시다.
CREATE VIEW  public.vwmytablemercator AS
        SELECT gid, ST_Transform(geom,3395) As geom, f_name
        FROM public.mytable;

-- PostGIS 2.0 이상 버전에 정확하게 등록하려면
-- 도형을 형변환해야 합니다.
--
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;

-- 도형 유형이 2D 폴리곤이란 사실을 확실히 알고 있을 경우 다음과 같이 할 수 있습니다.
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);

-- 새 테이블에 2D 인덱스를 생성합니다.
CREATE INDEX idx_myschema_myspecialpois_geom_gist
  ON myschema.my_special_pois USING gist(geom);

-- 사용자 포인트가 3D 또는 3M 포인트일 경우,
-- 2D 인덱스가 아니라 nD 인덱스를 생성하는 편이 좋을 수도 있습니다.
-- 다음처럼 말이죠.
CREATE INDEX my_special_pois_geom_gist_nd
        ON my_special_pois USING gist(geom gist_geometry_ops_nd);

-- 이 새 테이블의 도형 열을 geometry_columns 테이블에 직접 등록하는
-- 다음 방법은 PostGIS 2.0 이후 버전 및 1.4 이후 버전 모두에서 동작합니다.
-- PostGIS 2.0 버전의 경우 열을 typmod 기반으로 만들기 위해
-- 테이블의 기저 구조를 변경할 것입니다.
-- PostGIS 2.0 이전 버전의 경우, 동일한 방법으로 뷰를 등록할 수도 있습니다.
SELECT populate_geometry_columns('myschema.my_special_pois'::regclass);

-- PostGIS 2.0 버전을 사용중이고 어떤 이유에서든
-- 구식 제약조건 기반 정의 동작이 필요한 경우
-- (모든 자식 객체가 동일한 유형과 SRID가 아닌 상속 테이블의 경우 등)
-- 선택적인 새 use_typmod argument 파라미터를 거짓으로 설정하십시오.
SELECT populate_geometry_columns('myschema.my_special_pois'::regclass, false); 

구식 제약조건 기반 방법을 여전히 지원하긴 하지만, 뷰에서 직접적으로 사용되는 제약조건 기반 도형 열은 typmod 기반 열과는 달리 geometry_columns 테이블에 정확하게 등록되지 않을 겁니다. 다음은 typmod를 이용하는 열과 제약조건을 이용하는 또다른 열을 정의하는 예시입니다.

CREATE TABLE pois_ny(gid SERIAL PRIMARY KEY
   , poi_name text, cat varchar(20)
   , geom geometry(POINT,4326) );
SELECT AddGeometryColumn('pois_ny', 'geom_2160', 2160, 'POINT', 2, false);

PSQL에서 실행할 경우

\d pois_ny;

두 열이 서로 다르게 정의되었다는 사실을 알 수 있습니다. 하나는 typmod, 다른 하나는 제약조건으로 정의되었습니다.

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';

typmod 기반 도형 열은 정확하게 등록되지만, 제약조건 기반 도형 열은 정확하게 등록되지 않습니다.

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

4.7. GIS (벡터) 데이터 로드

공간 테이블 생성을 끝냈다면, 사용자가 데이터베이스에 GIS 데이터를 업로드할 준비가 된 것입니다. 현재, 형식화된 SQL 구문을 사용하거나 shapefile 로더/덤퍼를 사용하는 두 가지 방법으로 PostGIS/PostgreSQL 데이터베이스에 데이터를 입력할 수 있습니다.

4.7.1. SQL을 이용해 데이터 가져오기

사용자 데이터를 텍스트 표현식으로 변환할 수 있다면, PostGIS에 사용자 데이터를 입력하는 가장 쉬운 방법은 형식화된(formatted) SQL을 이용하는 것입니다. Oracle이나 다른 SQL 데이터베이스와 마찬가지로, SQL 터미널 모니터에 SQL "INSERT" 선언문으로 가득 찬 대용량 텍스트 파일을 송신하는(piping) 방법으로 데이터를 일괄 로드시킬 수 있습니다.

데이터 업로드 파일(예를 들어 roads.sql)은 다음처럼 보일 것입니다:

BEGIN;
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (1,ST_GeomFromText('LINESTRING(191232 243118,191108 243242)',-1),'Jeff Rd');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (2,ST_GeomFromText('LINESTRING(189141 244158,189265 244817)',-1),'Geordie Rd');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (3,ST_GeomFromText('LINESTRING(192783 228138,192612 229814)',-1),'Paul St');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (4,ST_GeomFromText('LINESTRING(189412 252431,189631 259122)',-1),'Graeme Ave');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (5,ST_GeomFromText('LINESTRING(190131 224148,190871 228134)',-1),'Phil Tce');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (6,ST_GeomFromText('LINESTRING(198231 263418,198213 268322)',-1),'Dave Cres');
COMMIT;

"psql" SQL 터미널 모니터를 이용해서 PostgreSQL로 데이터 파일을 매우 쉽게 송신할 수 있습니다.

psql -d [database] -f roads.sql

4.7.2. shp2pgsql: ESRI shapefile 로더 이용하기

shp2pgsql 데이터 로더는 ESRI shapefile을, 도형 형식이든 지리형 형식이든, PostGIS/PostgreSQL 데이터베이스로 삽입하기에 적합한 SQL로 변환합니다. 이 로더에는 명령행(command line) 플래그로 구별되는 몇 가지 실행 모드가 존재합니다.

shp2pgsql 명령행 로더 외에, 사용자가 PostGIS를 처음 접하는 경우 스크립트를 사용하지 않고 단 한 번 로드하는 데 더 쉽게 사용할 수 있을 뿐만 아니라 명령행 로더가 가진 대부분의 옵션도 가지고 있는 shp2pgsql-gui 그래픽 인터페이스도 있습니다. shp2pgsql-gui를 pgAdmin III의 플러그인으로 설정할 수도 있습니다.

c|a|d|p -- 이들은 상호배타적인 옵션들입니다:

-c

새 테이블을 생성한 다음 shapefile의 데이터로 해당 테이블을 채웁니다. 이것이 기본 모드입니다.

-a

기존 데이터베이스 테이블에 shapefile의 데이터를 추가합니다. 이 옵션을 이용해서 복수의 파일을 로드하려면, 파일들이 동일한 속성 및 동일한 데이터 유형을 담고 있어야 한다는 점을 주의하십시오.

-d

기존 데이터베이스 테이블을 삭제(drop)한 다음 shapefile의 데이터를 가진 새 테이블을 생성합니다.

-p

테이블을 생성하는 SQL 코드만 생성하고, 어떤 실제 데이터도 추가하지 않습니다. 테이블 생성과 데이터 로드 단계를 완전히 분리해야 할 경우 사용할 수 있습니다.

-?

도움말 화면을 표출합니다.

-D

산출물 데이터의 형식으로 PostgreSQL "덤프(dump)" 형식을 사용합니다. 이 옵션은 -a, -c 및 -d와 함께 사용할 수 있습니다. 이 덤프 형식은 기본 "삽입" SQL 형식보다 훨씬 빨리 로드할 수 있습니다. 대용량 데이터셋의 경우 이 옵션을 사용하십시오.

-s [<FROM_SRID%gt;:]<SRID>

도형 테이블을 생성하고 지정된 SRID로 채웁니다. 입력 shapefile이 주어진 FROM_SRID를 쓰도록 설정하는 옵션도 있습니다. 이런 경우 도형이 목표 SRID로 재투영될 것입니다. FROM_SRID는 -D 옵션과 함께 사용될 수 없습니다.

-k

식별자의 대소문자(열, 스키마 및 속성)를 유지합니다. shapefile 안의 속성은 모두 대문자라는 점을 주의하십시오.

-i

DBF 헤더 서명이 64비트 bigint 형식을 보장하더라도, 모든 정수를 표준 32비트 정수로 강제 변환하고 64비트 bigint 형식을 생성하지 않습니다.

-I

도형 열에 GiST 인덱스를 생성합니다.

-m

"-m 파일명" 형식으로 (긴) 열 명칭과 10문자 DBF 열 명칭을 매핑하는 목록을 담은 파일을 지정합니다. 이 파일의 내용은 공백으로 구분된 두 명칭으로 이루어진 하나 이상의 행으로, 행 맨 앞과 맨 뒤에는 공백이 없어야 합니다. 다음은 그 예시입니다:

COLUMNNAME DBFFIELD1
AVERYLONGCOLUMNNAME DBFFIELD2

-S

다중(multi) 도형 대신 단순 도형을 생성합니다. 이 옵션은 모든 도형이 실제로 단일형(예: 단일 외곽선을 가진 다중 폴리곤 또는 단일 꼭짓점을 가진 다중 포인트)일 경우에만 작동합니다.

-t <dimensionality>

산출 도형이 지정된 차원수를 가지도록 강제합니다. 차원수를 지시하는 데 다음 스트링을 사용하십시오: 2D, 3DZ, 3DM, 4D

입력물이 지정된 차원수보다 낮은 차원일 경우, 출력물의 해당 차원은 0으로 채워질 것입니다. 입력물이 지정된 차원수보다 높은 차원일 경우, 필요 없는 차원은 제거될 것입니다.

-w

WKB 대신 WKT 형식으로 출력합니다. 정확도가 부족하기 때문에 좌표가 이동될 가능성이 있다는 점을 주의하십시오.

-e

각 선언문을 상호처리를 이용하지 않고 자체적으로 실행합니다. 오류를 생성하는 몇몇 망가진 도형이 있을 경우 이 옵션을 사용하면 괜찮은 데이터 대다수를 로드할 수 있습니다. "덤프" 형식은 항상 상호처리를 이용하기 때문에 -D 플래그와 함께 사용할 수 없다는 점을 주의하십시오.

-W <encoding>

입력 데이터(DBF 파일)의 인코딩을 지정합니다. 이 옵션을 사용하면, DBF의 모든 속성을 지정된 인코딩에서 UTF8로 변환합니다. 그 결과로 생성되는 SQL 출력물은 SET CLIENT_ENCODING to UTF8 명령어를 담게 되어, 백엔드에서 UTF8을 데이터베이스 내부에서 이용하도록 설정된 어떤 인코딩으로든 재변환할 수 있습니다.

-N <policy>

NULL 도형 처리 방침 -- insert*(상관없이 삽입), skip(건너뛰기), abort(중단)

-n

DBF 파일만 임포트합니다. 사용자 데이터에 대응하는 shapefile이 없다면, 자동적으로 이 모드로 전환하여 DBF만 로드할 것입니다. 따라서 전체 shapefile 집합을 가지고 있지만 도형을 빼고 속성 데이터만 필요한 경우에만 이 플래그를 설정해야 합니다.

-G

(경도/위도가 필요한) 도형 대신 WGS84 경위도(SRID=4326)를 쓰는 지리형을 이용합니다.

-T <tablespace>

새 테이블을 위한 테이블스페이스를 지정합니다. -X 파라미터가 함께 쓰인 경우가 아니라면 여전히 인덱스가 기본 테이블스페이스를 이용할 것입니다. PostgreSQL 문서는 사용자 지정 테이블스페이스가 필요한 경우를 잘 설명하고 있습니다.

-X <tablespace>

새 테이블의 인덱스를 위한 테이블스페이스를 지정합니다. 이 옵션은 기본 키(primary key) 인덱스에 적용되며, -I 플래그를 함께 사용하는 경우 GiST 공간 인덱스에도 적용됩니다.

-c

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 파이프(pipe)를 이용하면 모든 변환 및 업로드 작업을 한 번에 끝낼 수 있습니다:

# shp2pgsql shaperoads.shp myschema.roadstable | psql -d roadsdb

4.8. 공간 테이블 생성

SQL이나 shapefile 로더/덤퍼를 이용해서 데이터베이스로부터 데이터를 추출할 수 있습니다. SQL 단원에서 공간 테이블에 대한 비교 및 쿼리를 할 수 있는 몇몇 연산자에 대해 논의할 것입니다.

4.8.1. 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 문법을 쓰면 됩니다. 공간 제약의 경우, 다음 유용한 연산자들을 쓸 수 있습니다.

ST_Intersects

This function tells whether two geometries share any space.

=

이 연산자는 두 도형이 기하학적으로 동일한지를 테스트합니다.예를 들어, 'POLYGON((0 0,1 1,1 0,0 0))'과 'POLYGON((0 0,1 1,1 0,0 0))'이 동일한지를 말입니다(동일합니다).

다음으로, 이 연산자들을 쿼리에 쓸 수 있습니다. SQL 명령행에 도형과 경계 상자를 지정할 때, "ST_GeomFromText()" 함수를 이용해서 스트링 표현식을 도형으로 정확하게 변환시켜야 합니다. 해당 데이터와 일치하는 가공의 공간 참조 시스템은 312입니다. 다음은 그 예시입니다:

SELECT road_id, road_name
  FROM roads
  WHERE ST_OrderingEquals(roads_geom , ST_GeomFromText('LINESTRING(191232 243118,191108 243242)',312) ) ;

이 쿼리는 해당 값과 동일한 도형을 담고 있는 "ROADS_GEOM" 테이블로부터 단일 레코드를 반환할 것입니다.

To check whether some of the roads passes in the area defined by a polygon:

SELECT road_id, road_name
FROM roads
WHERE roads_geom && ST_GeomFromText('POLYGON((...))',312);

가장 흔한 공간 쿼리는 아마도 데이터 브라우저 또는 웹 매퍼 같은 클라이언트 소프트웨어가 화면 표출을 위해 "맵 프레임(map frame)" 용량에 해당하는 데이터를 가져오기 위해 사용하는 "프레임 기반(frame-based)" 쿼리일 것입니다.

"&&" 연산자 사용시, 비교 피처로 BOX3D 또는 도형을 지정할 수 있습니다. 하지만 도형을 지정했을 경우, 비교 작업에 해당 경계 상자가 사용될 것입니다.

Using a "BOX3D" object for the frame, such a query looks like this:

SELECT ST_AsText(roads_geom) AS geom
FROM roads
WHERE
  roads_geom && ST_MakeEnvelope(191232, 243117,191232, 243119,312);

화면에 해당하는 데이터의 투영체를 지정하는 데 SRID 312를 썼다는 사실에 주의하십시오.

4.8.2. 덤퍼 이용하기

pgsql2shp 테이블 덤퍼는 데이터베이스에 직접 연결되어 (아마도 쿼리가 정의했을) 테이블을 shapefile로 변환합니다. 기본 문법은 다음과 같습니다:

pgsql2shp [<options>] <database> [<schema>.]<table>
pgsql2shp [<options>] <database> <query>

다음과 같은 명령행 옵션이 있습니다:

-f <filename>

특정 파일명으로 출력물을 작성합니다.

-h <host>

연결할 데이터베이스 호스트를 설정합니다.

-p <port>

데이터베이스 호스트 연결시 사용할 포트를 설정합니다.

-P <password>

데이터베이스 연결에 사용할 비밀번호를 설정합니다.

-u <user>

데이터베이스 연결에 사용할 사용자명을 설정합니다.

-g <geometry column>

복수의 도형 열을 가진 테이블일 경우, shapefile 작성에 이용될 도형 열을 설정합니다.

-b

바이너리 커서를 사용하도록 설정합니다. 이 옵션을 쓰면 실행 속도가 빨라지지만, 테이블 안에 있는 비(非) 도형 속성 가운데 하나라도 텍스트로 작성할 캐스트(cast)가 부족할 경우 실행되지 않을 것입니다.

-r

로(raw) 모드입니다. gid 필드를 삭제하거나, 열 명칭을 제외하지 않습니다.

-m filename

식별자를 10문자 명칭으로 다시 매핑(remap)합니다. 해당 파일의 내용은 공백으로 구분된 두 심볼로 이루어진 복수의 행으로, 행 맨 앞과 맨 뒤에는 공백이 없어야 합니다. VERYLONGSYMBOL SHORTONE ANOTHERVERYLONGSYMBOL SHORTER 등과 같은 예가 있습니다.

4.9. 인덱스 빌드 작업

인덱스 덕분에 공간 데이터베이스가 대용량 데이터셋을 사용할 수 있습니다. 인덱스 작업을 하지 않으면, 어떤 피처를 검색하든 데이터베이스 안의 모든 레코드를 "순차 스캔"해야 할 것입니다. 인덱스 작업은 데이터를 특정 레코드를 찾기 위해 빠르게 훑어갈 수 있는 검색 트리로 조직해서 검색 속도를 향상시킵니다. PostgreSQL는 기본적으로 B-Tree, R-Tree, GiST 세 종류의 인덱스를 지원합니다.

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를 써서 GIS 데이터에 인덱스 작업을 한 다음, 해당 데이터에 다시 작업된 R-Tree 인덱스를 이용합니다.

  • BRIN (Block Range Index) indexes operate by summarizing the spatial extent of ranges of table records. Search is done via a scan of the ranges. BRIN is only appropriate for use for some kinds of data (spatially sorted, with infrequent or no update). But it provides much faster index create time, and much smaller index size.

  • SP-GiST (Space-Partitioned Generalized Search Tree) is a generic index method that supports partitioned search trees such as quad-trees, k-d trees, and radix trees (tries).

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.

4.9.1. GiST 인덱스

GiST는 "일반화된 검색 트리"의 줄임말로, 인덱스 작업의 포괄적인 형태입니다. GIS 인덱스 작업 외에도, 일반 B-Tree 인덱스 작업으로는 쓸 수 없는 온갖 종류의 비정규 데이터 구조(정수 배열, 분광 데이터 등등)에 대한 검색 속도를 향상시키는 데 GiST를 이용합니다.

GIS 데이터 테이블이 수천 행을 넘게 되면, 데이터 공간 검색의 속도를 향상시키기 위해 인덱스를 빌드하고 싶게 될 것입니다(사용자의 모든 검색이 속성에 기반하는 경우가 아니라면 말입니다. 그런 경우, 속성 필드에 대해 일반 인덱스를 빌드하면 됩니다).

"도형" 열에 대해 GiST 인덱스를 빌드하는 데 필요한 문법은 다음과 같습니다:

CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] ); 

이 문법은 항상 2D 인덱스를 빌드할 것입니다. 해당 도형 유형에 PostGIS 2.0 이상 버전이 지원하는 n차원 인덱스를 얻으려면, 다음 문법으로 생성할 수 있습니다:

CREATE INDEX [indexname] ON [tablename] USING GIST ([geometryfield] gist_geometry_ops_nd);

Building a spatial index is a computationally intensive exercise. It also blocks write access to your table for the time it creates, so on a production system you may want to do in in a slower CONCURRENTLY-aware way:

CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] ); 

After building an index, it is sometimes helpful to force PostgreSQL to collect table statistics, which are used to optimize query plans:

VACUUM ANALYZE [table_name] [(column_name)];

4.9.2. GiST 인덱스

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.

GIS 데이터 테이블이 수천 행을 넘게 되면, 데이터 공간 검색의 속도를 향상시키기 위해 인덱스를 빌드하고 싶게 될 것입니다(사용자의 모든 검색이 속성에 기반하는 경우가 아니라면 말입니다. 그런 경우, 속성 필드에 대해 일반 인덱스를 빌드하면 됩니다).

A BRIN index stores the bounding box enclosing all the geometries contained in the rows in a contiguous set of table blocks, called a block range. When executing a query using the index the block ranges are scanned to find the ones that intersect the query extent. This is efficient only if the data is physically ordered so that the bounding boxes for block ranges have minimal overlap (and ideally are mutually exclusive). The resulting index is very small in size, but is typically less performant for read than a GiST index over the same data.

Building a BRIN index is much less CPU-intensive than building a GiST index. It's common to find that a BRIN index is ten times faster to build than a GiST index over the same data. And because a BRIN index stores only one bounding box for each range of table blocks, it's common to use up to a thousand times less disk space than a GiST index.

You can choose the number of blocks to summarize in a range. If you decrease this number, the index will be bigger but will probably provide better performance.

For BRIN to be effective, the table data should be stored in a physical order which minimizes the amount of block extent overlap. It may be that the data is already sorted appropriately (for instance, if it is loaded from another dataset that is already sorted in spatial order). Otherwise, this can be accomplished by sorting the data by a one-dimensional spatial key. One way to do this is to create a new table sorted by the geometry values (which in recent PostGIS versions uses an efficient Hilbert curve ordering):

CREATE TABLE table_sorted AS
   SELECT * FROM table  ORDER BY geom;

Alternatively, data can be sorted in-place by using a GeoHash as a (temporary) index, and clustering on that index:

CREATE INDEX idx_temp_geohash ON table
    USING btree (ST_GeoHash( ST_Transform( geom, 4326 ), 20));
CLUSTER table USING idx_temp_geohash;

"도형" 열에 대해 GiST 인덱스를 빌드하는 데 필요한 문법은 다음과 같습니다:

CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] ); 

이 문법은 항상 2D 인덱스를 빌드할 것입니다. 해당 도형 유형에 PostGIS 2.0 이상 버전이 지원하는 n차원 인덱스를 얻으려면, 다음 문법으로 생성할 수 있습니다:

CREATE INDEX [indexname] ON [tablename] USING GIST ([geometryfield] gist_geometry_ops_nd);

You can also get a 4D-dimensional index using the 4D operator class:

CREATE INDEX [indexname] ON [tablename] USING GIST ([geometryfield] gist_geometry_ops_nd);

The above commands use the default number of blocks in a range, which is 128. To specify the number of blocks to summarise in a range, use this syntax

CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] ); 

Keep in mind that a BRIN index only stores one index entry for a large number of rows. If your table stores geometries with a mixed number of dimensions, it's likely that the resulting index will have poor performance. You can avoid this performance penalty by choosing the operator class with the least number of dimensions of the stored geometries

"도형" 열에 대해 GiST 인덱스를 빌드하는 데 필요한 문법은 다음과 같습니다:

CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] ); 

이 문법은 항상 2D 인덱스를 빌드할 것입니다. 해당 도형 유형에 PostGIS 2.0 이상 버전이 지원하는 n차원 인덱스를 얻으려면, 다음 문법으로 생성할 수 있습니다:

Currently, only "inclusion support" is provided, meaning that just the &&, ~ and @ operators can be used for the 2D cases (for both geometry and geography), and just the &&& operator for 3D geometries. There is currently no support for kNN searches.

An important difference between BRIN and other index types is that the database does not maintain the index dynamically. Changes to spatial data in the table are simply appended to the end of the index. This will cause index search performance to degrade over time. The index can be updated by performing a VACUUM, or by using a special function brin_summarize_new_values(regclass). For this reason BRIN may be most appropriate for use with data that is read-only, or only rarely changing. For more information refer to the manual.

To summarize using BRIN for spatial data:

  • Index build time is very fast, and index size is very small.

  • Index query time is slower than GiST, but can still be very acceptable.

  • Requires table data to be sorted in a spatial ordering.

  • Requires manual index maintenance.

  • 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.

4.9.3. GiST 인덱스

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 데이터 테이블이 수천 행을 넘게 되면, 데이터 공간 검색의 속도를 향상시키기 위해 인덱스를 빌드하고 싶게 될 것입니다(사용자의 모든 검색이 속성에 기반하는 경우가 아니라면 말입니다. 그런 경우, 속성 필드에 대해 일반 인덱스를 빌드하면 됩니다).

CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] ); 

이 문법은 항상 2D 인덱스를 빌드할 것입니다. 해당 도형 유형에 PostGIS 2.0 이상 버전이 지원하는 n차원 인덱스를 얻으려면, 다음 문법으로 생성할 수 있습니다:

CREATE INDEX [indexname] ON [tablename] USING GIST ([geometryfield] gist_geometry_ops_nd);

Building a spatial index is a computationally intensive operation. It also blocks write access to your table for the time it creates, so on a production system you may want to do in in a slower CONCURRENTLY-aware way:

CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] ); 

After building an index, it is sometimes helpful to force PostgreSQL to collect table statistics, which are used to optimize query plans:

VACUUM ANALYZE [table_name] [(column_name)];

An SP-GiST index can accelerate queries involving the following operators:

  • <<, &<, &>, >>, <<|, &<|, |&>, |>>, &&, @>, <@, and ~=, for 2-dimensional indexes,

  • &/&, ~==, @>>, and <<@, for 3-dimensional indexes.

There is no support for kNN searches at the moment.

4.9.4. 인덱스 빌드 작업

일반적인 경우라면 인덱스는 눈에 보이지 않게 데이터 접속 속도를 향상시킵니다. 인덱스가 빌드된 후, 쿼리 설계자는 쿼리 설계의 속도를 향상기키는 데 언제 인덱스 정보를 사용할 것인지 투명하게 결정합니다. 안타깝게도 PostgreSQL 쿼리 설계자가 GiST 인덱스의 사용을 제대로 최적화시키지 못 하기 때문에, 종종 공간 인덱스를 활용해야 할 검색이 대신 기본값인 전체 데이터의 순차 스캔을 이용할 때가 있습니다.

사용자의 공간 인덱스가 (또는 사용자의 속성 인덱스가) 활용되지 않고 있다는 사실을 알게 되었다면, 몇 가지 해결 방법이 있습니다:

  • Examine the query plan and check your query actually computes the thing you need. An erroneous JOIN, either forgotten or to the wrong table, can unexpectedly retrieve table records multiple times. To get the query plan, execute with EXPLAIN in front of the query.

  • Make sure statistics are gathered about the number and distributions of values in a table, to provide the query planner with better information to make decisions around index usage. VACUUM ANALYZE will compute both.

    You should regularly vacuum your databases anyways. Many PostgreSQL DBAs run VACUUM as an off-peak cron job on a regular basis.

  • 두 번째, 빈공간 분석으로 해결이 안 될 경우 SET ENABLE_SEQSCAN=OFF 명령어를 통해 강제로 쿼리 설계자가 인덱스 정보를 이용하도록 할 수 있습니다. 이 명령어는 공간 인덱스 쿼리일 경우에 한해 드물게 이용해야 합니다. 일반적으로, 쿼리 설계자는 언제 일반 B-Tree 인덱스를 활용해야 하는지 사용자보다 더 잘 알고 있습니다. 사용자 쿼리 실행 후, 다른 쿼리가 평소처럼 쿼리 설계자를 활용하도록 ENABLE_SEQSCAN 을 다시 켤지 고려해봐야 합니다.

  • 쿼리 설계자가 순차 및 인덱스 스캔의 경중(cost)을 잘못 판단하고 있다면, postgresql.conf 파일의 random_page_cost의 값을 줄여보거나 "SET random_page_cost=#"로 써보십시오. 해당 파라미터의 기본값은 4이지만, 1또는 2로 설정해보십시오. 값을 감소시킬수록 점점 더 쿼리 설계자가 인덱스 스캔을 활용하게 될 것입니다.

  • If SET ENABLE_SEQSCAN TO OFF; does not help your query, the query may be using a SQL construct that the Postgres planner is not yet able to optimize. It may be possible to rewrite the query in a way that the planner is able to handle. For example, a subquery with an inline SELECT may not produce an efficient plan, but could possibly be rewritten using a LATERAL JOIN.

For more information see the Postgres manual section on Query Planning.

Chapter 5. Spatial Queries

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.

5.1. Determining Spatial Relationships

Spatial relationships indicate how two geometries interact with one another. They are a fundamental capability for querying geometry.

5.1.1. Dimensionally Extended 9-Intersection Model

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:

Boundary

The boundary of a geometry is the set of geometries of the next lower dimension. For POINTs, which have a dimension of 0, the boundary is the empty set. The boundary of a LINESTRING is the two endpoints. For POLYGONs, the boundary is the linework of the exterior and interior rings.

Interior

The interior of a geometry are those points of a geometry that are not in the boundary. For POINTs, the interior is the point itself. The interior of a LINESTRING is the set of points between the endpoints. For POLYGONs, the interior is the areal surface inside the polygon.

Exterior

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:

 InteriorBoundaryExterior
Interiordim( I(a) ∩ I(b) )dim( I(a) ∩ B(b) )dim( I(a) ∩ E(b) )
Boundarydim( B(a) ∩ I(b) )dim( B(a) ∩ B(b) )dim( B(a) ∩ E(b) )
Exteriordim( E(a) ∩ I(b) )dim( E(a) ∩ B(b) )dim( E(a) ∩ E(b) )

Visually, for two overlapping polygonal geometries, this looks like:

 

 InteriorBoundaryExterior
Interior

dim( I(a) ∩ I(b) ) = 2

dim( I(a) ∩ B(b) = 1

dim( I(a) ∩ E(b) ) = 2

Boundary

dim( B(a) ∩ I(b) ) = 1

dim( B(a) ∩ B(b) ) = 0

dim( B(a) ∩ E(b) ) = 1

Exterior

dim( E(a) ∩ I(b) ) = 2

dim( E(a) ∩ B(b) ) = 1

dim( E(a) ∩ E(b) = 2

Reading from left to right and top to bottom, the intersection matrix is represented as the text string '212101212'.

For more information, refer to:

5.1.2. Named Spatial Relationships

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 ST_Contains, ST_Crosses, ST_Disjoint, ST_Equals, ST_Intersects, ST_Overlaps, ST_Touches, ST_Within. It also defines the non-standard relationship predicates ST_Covers, ST_CoveredBy, and ST_ContainsProperly.

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.

5.1.3. General Spatial Relationships

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 ST_Crosses does not provide the necessary spatial filter, since for linear features it returns true only where they cross at a point.

A two-step solution would be to first compute the actual intersection (ST_Intersection) of pairs of road lines that spatially intersect (ST_Intersects), and then check if the intersection's ST_GeometryType is 'LINESTRING' (properly dealing with cases that return GEOMETRYCOLLECTIONs of [MULTI]POINTs, [MULTI]LINESTRINGs, etc.).

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 ST_Relate 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 ST_Relate and the ST_RelateMatch 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');

5.2. Using Spatial Indexes

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, “인덱스 빌드 작업”). 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.10.1, “Bounding Box Operators” for the full list) and the distance operators used in nearest-neighbor queries (the most common being <->; see Section 8.10.2, “연산자(operator)” 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 ST_Contains, ST_ContainsProperly, ST_CoveredBy, ST_Covers, ST_Crosses, ST_Intersects, ST_Overlaps, ST_Touches, ST_Within, ST_Within, and ST_3DIntersects, and the distance predicates ST_DWithin, ST_DFullyWithin, ST_3DDFullyWithin, and ST_3DDWithin .)

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 ST_DWithin:

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 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.

5.3. Examples of Spatial SQL

The examples in this section make use of a table of linear roads, and a table of polygonal municipality boundaries. The definition of the bc_roads table is:

Column    | Type              | Description
----------+-------------------+-------------------
gid       | integer           | Unique ID
name      | character varying | Road Name
geom      | geometry          | Location Geometry (Linestring)

The definition of the bc_municipality table is:

Column   | Type              | Description
---------+-------------------+-------------------
gid      | integer           | Unique ID
code     | integer           | Unique ID
name     | character varying | City / Town Name
geom     | geometry          | Location Geometry (Polygon)
5.3.1. What is the total length of all roads, expressed in kilometers?
5.3.2. How large is the city of Prince George, in hectares?
5.3.3. What is the largest municipality in the province, by area?
5.3.4. What is the length of roads fully contained within each municipality?
5.3.5. Create a new table with all the roads within the city of Prince George.
5.3.6. What is the length in kilometers of "Douglas St" in Victoria?
5.3.7. What is the largest municipality polygon that has a hole?

5.3.1.

What is the total length of all roads, expressed in kilometers?

You can answer this question with a very simple piece of SQL:

SELECT sum(ST_Length(geom))/1000 AS km_roads FROM bc_roads;

km_roads
------------------
70842.1243039643

5.3.2.

How large is the city of Prince George, in hectares?

This query combines an attribute condition (on the municipality name) with a spatial calculation (of the polygon area):

SELECT
  ST_Area(geom)/10000 AS hectares
FROM bc_municipality
WHERE name = 'PRINCE GEORGE';

hectares
------------------
32657.9103824927

5.3.3.

What is the largest municipality in the province, by area?

This query uses a spatial measurement as an ordering value. There are several ways of approaching this problem, but the most efficient is below:

SELECT
  name,
  ST_Area(geom)/10000 AS hectares
FROM bc_municipality
ORDER BY hectares DESC
LIMIT 1;

name           | hectares
---------------+-----------------
TUMBLER RIDGE  | 155020.02556131

Note that in order to answer this query we have to calculate the area of every polygon. If we were doing this a lot it would make sense to add an area column to the table that could be indexed for performance. By ordering the results in a descending direction, and them using the PostgreSQL "LIMIT" command we can easily select just the largest value without using an aggregate function like MAX().

5.3.4.

What is the length of roads fully contained within each municipality?

This is an example of a "spatial join", which brings together data from two tables (with a join) using a spatial interaction ("contained") as the join condition (rather than the usual relational approach of joining on a common key):

SELECT
  m.name,
  sum(ST_Length(r.geom))/1000 as roads_km
FROM bc_roads AS r
JOIN bc_municipality AS m
  ON ST_Contains(m.geom, r.geom)
GROUP BY m.name
ORDER BY roads_km;

name                        | roads_km
----------------------------+------------------
SURREY                      | 1539.47553551242
VANCOUVER                   | 1450.33093486576
LANGLEY DISTRICT            | 833.793392535662
BURNABY                     | 773.769091404338
PRINCE GEORGE               | 694.37554369147
...

This query takes a while, because every road in the table is summarized into the final result (about 250K roads for the example table). For smaller datsets (several thousand records on several hundred) the response can be very fast.

5.3.5.

Create a new table with all the roads within the city of Prince George.

This is an example of an "overlay", which takes in two tables and outputs a new table that consists of spatially clipped or cut resultants. Unlike the "spatial join" demonstrated above, this query creates new geometries. An overlay is like a turbo-charged spatial join, and is useful for more exact analysis work:

CREATE TABLE pg_roads as
SELECT
  ST_Intersection(r.geom, m.geom) AS intersection_geom,
  ST_Length(r.geom) AS rd_orig_length,
  r.*
FROM bc_roads AS r
JOIN bc_municipality AS m
  ON ST_Intersects(r.geom, m.geom)
WHERE
  m.name = 'PRINCE GEORGE';

5.3.6.

What is the length in kilometers of "Douglas St" in Victoria?

SELECT
  sum(ST_Length(r.geom))/1000 AS kilometers
FROM bc_roads r
JOIN bc_municipality m
  ON ST_Intersects(m.geom, r.geom
WHERE
  r.name = 'Douglas St'
  AND m.name = 'VICTORIA';

kilometers
------------------
4.89151904172838

5.3.7.

What is the largest municipality polygon that has a hole?

SELECT gid, name, ST_Area(geom) AS area
FROM bc_municipality
WHERE ST_NRings(geom) > 1
ORDER BY area DESC LIMIT 1;

gid  | name         | area
-----+--------------+------------------
12   | SPALLUMCHEEN | 257374619.430216

Chapter 6. 성능 향상 비법

6.1. 대용량 도형을 담은 저용량 테이블

6.1.1. 문제점 설명

현재 PostgreSQL (8.0 포함) 버전들의 쿼리 최적화기(optimizer)에는 TOAST 테이블과 관련된 약점이 있습니다. TOAST 테이블은 일반 데이터 페이지에 적합하지 않은 (긴 텍스트, 큰 이미지 또는 수많은 꼭짓점을 가진 복잡 도형 같은) 대용량(데이터 크기 관점에서) 값을 저장하는 데 쓰이는 일종의 "확장 공간(extension room)"입니다. 자세한 정보는 the PostgreSQL Documentation for TOAST 를 참고하십시오.

상당히 대용량의 도형을 가진 테이블이지만, (전체 유럽 국가들의 고해상도 국경을 담고 있는 테이블처럼) 도형 행이 그렇게 많지 않을 경우 문제가 드러납니다. 이때 테이블 자체는 저용량이지만, 많은 TOAST 공간을 차지합니다. 이번 예제의 경우, 테이블 자체는 약 80행을 담고 있고 데이터 페이지 3장만 사용하지만, TOAST 테이블은 8,225페이지를 차지합니다.

이 테이블의 행 가운데 몇 행과만 일치하는 경계 상자를 검색하기 위한 도형 연산자 &&를 이용하는 쿼리를 전송해봅시다. 이때 쿼리 최적화기는 해당 테이블이 데이터 페이지 3장과 80행만 가지고 있다고 판단합니다. 이런 저용량 테이블에는 인덱스보다 순차 스캔이 훨씬 빠를 거라고 추정할 것입니다. 따라서 GiST 인덱스를 무시하기로 합니다. 일반적인 경우라면 이 추정이 맞습니다. 그러나 이번 예제의 경우, && 연산자가 경계 상자를 비교하기 위해 디스크에서 모든 도형을 불러와야 하기 때문에, 결국 모든 TOAST 페이지도 읽어야 합니다.

사용자 시스템에 이 버그가 있는지 확인하려면, "EXPLAIN ANALYZE" PostgreSQL 명령어를 실행하십시오. 자세한 정보 및 기술적인 세부 사항을 알고 싶다면, PostgreSQL 성능 메일링 리스트에 있는 다음 스레드를 읽어볼 수 있습니다: http://archives.postgresql.org/pgsql-performance/2005-02/msg00030.php

and newer thread on PostGIS https://lists.osgeo.org/pipermail/postgis-devel/2017-June/026209.html

6.1.2. 해결 방법

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의 "일관성"을 유지해야 합니다. 일관성을 유지시키는 가장 명료한 방법은 트리거(trigger)일 것입니다. 물론 사용자 응용 프로그램을 수정해서 bbox 열의 정보를 항상 최신 상태로 유지하도록 하거나, 모든 수정 작업 후 매번 앞에서 나온 UPDATE 쿼리를 실행할 수도 있습니다.

6.2. 도형 인덱스에 대한 클러스터 작업

레코드 대부분이 읽기 전용이고, 쿼리의 대다수가 단일 인덱스를 이용하는 테이블의 경우, PostgreSQL은 CLUSTER 명령어를 제공합니다. 이 명령어는 모든 데이터 행을 인덱스 기준과 동일한 순서로 물리적으로 재정렬합니다. 이렇게 하면 성능 향상 관련 두 가지 장점이 나타납니다. 첫째, 인덱스 범위 스캔을 하는 경우 데이터 테이블에 대한 요청 횟수가 극단적으로 줄어듭니다. 둘째, 사용자가 작업중인 집합이 인덱스 상의 조금 작은 간격에 집중하고 있을 경우 데이터 행이 더 적은 데이터 페이지를 따라 퍼져 있기 때문에 더 효율적인 캐시 작업이 가능합니다. (이 시점에서 PostgreSQL 지침서에 있는 CLUSTER 명령어 문서를 읽어보는 편이 좋습니다.)

하지만, 현재 PostgreSQL은 PostGIS GiST 인덱스에 대한 클러스터 작업을 허용하지 않습니다. 왜냐하면 GiST 인덱스가 NULL 값을 단순히 무시하기 때문에, 다음과 같은 오류 메시지를 보게 될 것입니다:

lwgeom=# CLUSTER my_geom_index ON my_table;
ERROR: cannot cluster when index access method does not handle null values
HINT: You may be able to work around this by marking column "the_geom" NOT NULL.

HINT 메시지의 내용대로, 테이블에 "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 제약조건을 사용하는 방법은 먹히지 않을 겁니다.

6.3. 차원 변환 피하기

때때로 사용자 테이블에 3D 또는 4D 데이터가 있지만, 항상 2D 도형만을 출력하는 OpenGIS 준수 ST_AsText() 또는 ST_AsBinary() 함수를 통해서만 접근하는 경우가 있을 수 있습니다. 이런 경우 내부적으로 ST_Force2D() 함수를 호출하는데, 대용량 도형의 경우 이 함수는 시스템의 자원을 상당히 잡아먹습니다. 이런 자원 낭비를 피하려면, 미리 그 추가적인 차원을 완전히 삭제하는 편이 효율적일 수 있습니다.

UPDATE mytable SET the_geom = ST_Force2D(the_geom);
VACUUM FULL ANALYZE mytable;

AddGeometryColumn() 함수를 통해 사용자 도형 열을 추가했을 경우 도형 차원에 제약조건이 걸려 있다는 사실을 주의하십시오. 이를 우회하려면 제약조건을 삭제해야 합니다. geometry_columns 테이블 내부 항목을 업데이트한 다음 제약조건을 다시 생성하는 걸 잊지 마십시오.

대용량 테이블의 경우, 사용자의 기본 키 또는 또다른 사용 가능한 기준과 함께 WHERE 절을 이용해서 테이블의 일부분만 업데이트하도록 제한한 다음 업데이트마다 간단히 "VACUUM;"을 실행하는 방식으로 이 업데이트를 작은 부분으로 나누는 편이 좋을 수 있습니다. 이렇게 하면 필요한 임시 디스크 공간이 급격히 줄어듭니다. 또한 몇 종류의 차원이 섞인 도형들을 가지고 있을 경우, "WHERE dimension(the_geom)>2"로 업데이트를 제한하면 이미 2D인 도형을 다시 작성하는 일을 건너뛸 수 있습니다.

Chapter 7. PostGIS 도형 활용: 응용 프로그램 빌드

7.1. MapServer 활용

미네소타 맵서버(Minnesota MapServer)는 OpenGIS 웹 매핑 서버 사양서를 준수하는 인터넷 웹 매핑 서버입니다.

7.1.1. 기본 활용

MapServer와 함께 PostGIS를 사용하려면 MapServer 설정법을 알아야 하는데, MapServer 설정은 이 문서의 범위를 벗어납니다. 이 단원에서는 특정 PostGIS 문제점 및 설정 상세 정보를 다룰 것입니다.

MapServer와 함께 PostGIS를 사용하려면 다음 프로그램이 필요합니다:

  • PostGIS 0.6 이상 버전

  • MapServer 3.5 이상 버전

MapServer는 다른 어떤 PostgreSQL 클라이언트와도 동일한 방식으로 -- libpq 인터페이스를 이용해서 PostGIS/PostgreSQL 데이터에 접근합니다. 즉 PostGIS 서버에 네트워크 연결된 어떤 컴퓨터에라도 MapServer를 설치할 수 있고, PostGIS를 데이터 소스로 이용할 수 있다는 뜻입니다. 두 시스템 간의 연결이 빠를수록 좋습니다.

  1. "--with-postgis" 설정 옵션을 포함하는, 사용자가 원하는 옵션으로 MapServer를 컴파일하고 설치하십시오.

  2. 사용자 MapServer의 맵 파일 안에 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에 특화된 지시자(directive)는 다음과 같습니다:

    CONNECTIONTYPE

    PostGIS 레이어의 경우, 언제나 "postgis"입니다.

    CONNECTION

    다음과 같은 표준 키 및 값의 집합인 '연결 스트링(connection string)'이 데이터베이스 연결을 관장합니다(기본값은 <>로 감싸여 있습니다).

    user=<username> password=<password> dbname=<username> hostname=<server> port=<5432>

    비어 있는 연결 스트링도 여전히 유효하며, 어떤 키/값 쌍이라도 생략할 수 있습니다. 최소한, 연결에 필요한 데이터베이스 명 및 사용자명은 보통 제공하기 바랍니다.

    DATA

    이 파라미터의 서식은 유일한 <primary key>"를 이용한 "<geocolumn> from <tablename> using srid=<srid>입니다. 이때 열은 맵에 렌더링될 공간 열을 말하고, SRID는 열이 사용하는 SRID이며 기본 키는 테이블 기본 키(또는 다른 어떤 유일값을 담은, 인덱스를 가진 열)입니다.

    "using srid" 및 "using unique" 절(clause)을 생략할 수 있으며, 이런 경우 가능하다면 MapServer가 자동적으로 정확한 값을 알아낼 것입니다. 그러나 각 맵을 그리기 위해 서버 상에서 어느 정도의 추가 쿼리를 실행하는 일을 감당해야 할 것입니다.

    PROCESSING

    기존 연결을 끊지 않고 재사용하는 복수의 레이어가 있을 경우 CLOSE_CONNECTION=DEFER 절을 삽입하면 속도가 향상됩니다. 더 자세한 설명이 필요한 경우 MapServer PostGIS Performance Tips 를 참조하십시오.

    FILTER

    필터란 일반적으로 SQL 쿼리 안에 있는 "WHERE" 키워드를 따르는 논리에 상응하는 유효한 SQL 스트링이어야 합니다. 따라서, 예를 들어 6개 이상 차선을 가진 도로만을 렌더링하려면 "num_lanes >= 6"라는 필터를 사용하십시오.

  3. 사용자 공간 데이터베이스 안에 사용자가 그리게 될 모든 레이어에 대해 공간(GiST) 인덱스가 빌드되어 있는지 확인하십시오.

    CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometrycolumn] );
  4. MapServer를 이용해서 사용자 레이어를 쿼리하게 될 경우, 사용자의 DATA 구문에 "using unique" 절을 삽입해야 할 것입니다.

    쿼리 실행시 MapServer는 각 공간 레코드에 대해 유일한 식별자를 요구하며, MapServer의 PostGIS 모듈은 이 유일한 식별자를 제공하기 위해 사용자가 설정한 유일값을 이용합니다. 가장 좋은 방법은 테이블 기본 키를 쓰는 것입니다.

7.1.2. FAQ

7.1.2.1. 제 맵 파일 안에 EXPRESSION 을 사용할 때, 제 테이블에 해당 값이 분명히 있는 데도 불구하고, 조건문이 항상 거짓을 반환합니다.
7.1.2.2. 제 shapefile에 사용하는 필터가 동일한 데이터를 가진 제 PostGIS 테이블에 대해서는 동작하지 않습니다.
7.1.2.3. 제 PostGIS 레이어를 그리는 속도가 제 shapefile 레이어보다 훨씬 느린데, 정상인가요?
7.1.2.4. 제 PostGIS 레이어는 잘 그려지는데, 쿼리 속도가 너무 느립니다. 뭐가 문제죠?
7.1.2.5. MapServer 레이어를 위한 소스로 (PostGIS 1.5부터 지원되는) "지리형" 열을 사용할 수 있을까요?

7.1.2.1.

제 맵 파일 안에 EXPRESSION 을 사용할 때, 제 테이블에 해당 값이 분명히 있는 데도 불구하고, 조건문이 항상 거짓을 반환합니다.

shapefile과는 달리, 표현식(expression)에 참조되는 PostGIS 필드명은 소문자 여야 합니다.

EXPRESSION ([numlanes] >= 6)

7.1.2.2.

제 shapefile에 사용하는 필터가 동일한 데이터를 가진 제 PostGIS 테이블에 대해서는 동작하지 않습니다.

shapefile과는 달리, PostGIS 레이어 용 필터는 SQL 문법을 이용합니다(이 필터는 MapServer에서 레이어를 그리기 위해 PostGIS 연결자가 생성하는 SQL 선언문에 추가됩니다).

FILTER "type = 'highway' and numlanes >= 4"

7.1.2.3.

제 PostGIS 레이어를 그리는 속도가 제 shapefile 레이어보다 훨씬 느린데, 정상인가요?

일반적으로, 주어진 맵에 더 많은 피처를 그릴수록 shapefile보다 PostGIS가 느려지게 됩니다. 상대적으로 적은 피처(수백 개)를 가진 맵의 경우, PostGIS가 빠른 편입니다. 고밀도 피처(수천 개)를 가진 맵의 경우, 항상 PostGIS가 더 느릴 것입니다.

그리기 작업 속도에서 상당한 문제가 있을 경우, 사용자 테이블에 공간 인덱스를 빌드하지 않았을 가능성이 있습니다.

postgis# CREATE INDEX geotable_gix ON geotable USING GIST ( geocolumn );
postgis# VACUUM ANALYZE;

7.1.2.4.

제 PostGIS 레이어는 잘 그려지는데, 쿼리 속도가 너무 느립니다. 뭐가 문제죠?

쿼리 속도가 빠르려면 사용자 공간 테이블에 유일 키가 있어야 하며 해당 유일 키에 대해 인덱스가 빌드되어 있어야 합니다.

사용자의 DATA 행에 USING UNIQUE 절을 삽입해서 MapServer가 사용할 유일 키를 설정할 수 있습니다:

DATA "geom FROM geotable USING UNIQUE gid"

7.1.2.5.

MapServer 레이어를 위한 소스로 (PostGIS 1.5부터 지원되는) "지리형" 열을 사용할 수 있을까요?

네! MapServer는 지리형 열을 언제나 SRID 4326을 이용하는 도형 열과 동일하다고 인식합니다. 사용자의 DATA 구문에 "using srid=4326" 절을 삽입했는지만 확인하면 됩니다. 다른 모든 작업은 도형의 경우와 정확히 동일하게 이루어집니다.

DATA "geog FROM geogtable USING SRID=4326 USING UNIQUE gid"

7.1.3. 고급 활용

MapServer가 좀 더 복잡한 쿼리의 결과를 이해하도록 돕기 위한 정보를 추가하는 데 USING 허위(pseudo) SQL 절을 이용합니다. 더 정확하게는, 뷰 또는 하위집합(subselect)을 (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"
USING UNIQUE <uniqueid>

맵 쿼리 실행시 어떤 행인지 식별하기 위해 MapServer가 각 행에 대한 유일 ID를 요구합니다. 일반적으로는 시스템 테이블에서 기본 키를 인식합니다. 하지만, 뷰 및 하위집합은 알려진 유일값 열을 자동적으로 갖추지 않습니다. MapServer의 쿼리 기능성을 활용하고자 한다면, 사용자의 뷰 또는 하위집합이 유일값 열을 포함하는지 확인하고, USING UNIQUE 절을 통해 그 사실을 선언하십시오. 예를 들어, 이런 목적을 위해 명쾌하게 테이블의 기본 키를 선택할 수 있고, 또는 결과 출력물에서 유일할 것이 보장되는 다른 어떤 열이라도 선택할 수 있습니다.

[Note]

"맵 쿼리하기"란 해당 위치의 정보를 구하기 위해 맵을 클릭하는 행위입니다. DATA 정의에 있는 SQL 쿼리를 통한 "맵 쿼리"와 착각하지 마십시오.

USING SRID=<srid>

PostGIS는, MapServer에 정확한 데이터를 반환하기 위해, 도형이 어떤 공간 참조 시스템을 사용하는지 알아야 합니다. 일반적으로 PostGIS 데이터베이스에 있는 "geometry_columns" 테이블에서 이 정보를 찾을 수 있지만, 뷰 및 하위집합과 같이 실시간으로(on the fly) 생성된 테이블에서는 불가능합니다. 따라서 USING SRID= 옵션을 이용하면 DATA 정의 안에 정확한 SRID를 설정할 수 있습니다.

7.1.4. 예제

간단한 예제로 시작해서 단계를 높여 가보도록 합시다. 다음 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

이 레이어는 도로 테이블의 모든 도로 도형을 검정색 라인으로 표출할 것입니다.

이제 최소한 1:100,000 축척으로 확대하기 전까지는 고속도로만 보이도록 하려 한다고 해봅시다. 다음 두 레이어가 이런 효과를 낼 것입니다:

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:100,000을 초과할 경우 첫 번째 레이어를 사용해서 "highway" 유형의 도로만 검정색 라인으로 표출합니다. FILTER 옵션이 "highway" 유형의 도로만 표출되도록 합니다.

축척이 1:100,000 미만일 경우 두 번째 레이어를 사용해서 고속도로를 두 배 너비의 빨강색 라인으로, 다른 도로들을 일반적인 검정색 라인으로 표출 할 것입니다.

따라서, 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

이 주석(annotation) 레이어는 축척이 1:20,000 이하일 경우 모든 도로에 초록색 라벨을 추가합니다. DATA 정의에 어떻게 SQL 연결(join)을 이용하는지도 보여주고 있습니다.

7.2. Java 클라이언트(JDBC)

Java 클라이언트는 텍스트 표현식을 통해 직접 또는 PostGIS 번들에 포함되어 있는 JDBC 확장 프로그램을 이용해 PostgreSQL 데이터베이스 안에 있는 PostGIS "도형" 객체에 접근할 수 있습니다. 확장 프로그램 객체를 이용하려면, 사용자의 CLASSPATH에 "postgresql.jar" JDBC 드라이버 패키지와 함께 "postgis.jar" 파일이 존재해야 합니다.

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", "");
    /*
    * 도형 유형을 연결에 추가합니다. addDataType() 메소드를
    * 호출하기 전에 연결을 pgSQL에 특화된 연결 실행에
    * 지정해야 한다는 점에 주의합니다. 
    */
    ((org.postgresql.PGConnection)conn).addDataType("geometry",Class.forName("org.postgis.PGgeometry"));
    ((org.postgresql.PGConnection)conn).addDataType("box3d",Class.forName("org.postgis.PGbox3d"));
    /*
    * 선언문을 생성해서 선별 쿼리를 실행합니다.
    */
    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();
  }
}
}

"PGgeometry" 객체는 포인트, 라인스트링, 폴리곤, 멀티폴리곤, 멀티라인스트링, 멀티폴리곤 등의 유형에 의존하는 특정 지형 도형 객체(추출 클래스 "도형"의 하위 클래스)를 담고 있는 래퍼(wrapper) 객체입니다.

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은 기하학적 객체의 다양한 데이터 접근자(accessor) 함수에 대한 참조를 제공합니다.

7.3. C 클라이언트(libpq)

...

7.3.1. 텍스트 커서

...

7.3.2. 바이너리 커서

...

Chapter 8. PostGIS Reference

아래의 함수들은 PostGIS 사용자가 필요로 하는 함수들이며, 일반 사용자가 쓰지 않는 PostGIS 객체에 필요한 다른 지원 함수들도 있습니다.

[Note]

PostGIS는 기존 명명 규칙에서 SQL-MM-중심 명명 규칙으로 전환하기 시작했습니다. 그 결과로, 여러분이 알고 있고 좋아하는 대부분의 함수 이름이 표준 Spatial Type (ST) 접두어를 사용한 이름으로 변경되었습니다. 갱신된 함수들이 이전 함수들과 같은 기능을 제공하며, 비록 이 문서에는 나열되어 있지는 않지만 이전 함수도 사용할 수 있습니다. 다음 버전 출시에는 이 문서에 없는 비 ST_ 함수들이 더 이상 사용되지 않을 것이며 제외될 예정이므로 이들 함수의 사용을 중단해 주십시오.

8.1. PostgreSQL PostGIS Geometry/Geography/Box 유형

Abstract

이 섹션에서는 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.
geometry — geography는 지구곡면 좌표계에서 피처를 표현하는데 사용되는 공간 데이터 타입입니다.
geometry_dump — A composite type used to describe the parts of complex geometry.
geography — The type representing spatial features with geodetic (ellipsoidal) coordinate systems.

Name

box2d — The type representing a 2-dimensional bounding box.

설명

box3d 지오메트리 또는 지오메트리 셋의 범위를 표현하는데 사용되는 postgis 공간 데이터 타입입니다. ST_3DExtent는 box3d 객체를 반환합니다.

The representation contains the values xmin, ymin, xmax, ymax. These are the minimum and maximum values of the X and Y extents.

box2d objects have a text representation which looks like BOX(1 2,5 6).

캐스팅 동작

이 섹션에는 자동 형변환 뿐만 아니라 이 데이터 유형에 허용되는 명시적 캐스팅이 나열됩니다.

변환 대상동작
box3d자동적
geometry자동적

Name

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).

캐스팅 동작

이 섹션에는 자동 형변환 뿐만 아니라 이 데이터 유형에 허용되는 명시적 캐스팅이 나열됩니다.

변환 대상동작
box자동적
box2d자동적
geometry자동적

Name

geometry — geography는 지구곡면 좌표계에서 피처를 표현하는데 사용되는 공간 데이터 타입입니다.

설명

geography는 지구곡면 좌표계에서 피처를 표현하는데 사용되는 공간 데이터 타입입니다.

All spatial operations on geometry use the units of the Spatial Reference System the geometry is in.

캐스팅 동작

이 섹션에는 자동 형변환 뿐만 아니라 이 데이터 유형에 허용되는 명시적 캐스팅이 나열됩니다.

변환 대상동작
box자동적
box2d자동적
box3d자동적
bytea자동적
geography자동적
text자동적

Name

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.


Name

geography — The type representing spatial features with geodetic (ellipsoidal) coordinate systems.

설명

geography는 지구곡면 좌표계에서 피처를 표현하는데 사용되는 공간 데이터 타입입니다.

Spatial operations on the geography type provide more accurate results by taking the ellipsoidal model into account.

캐스팅 동작

이 섹션에는 자동 형변환 뿐만 아니라 이 데이터 유형에 허용되는 명시적 캐스팅이 나열됩니다.

변환 대상동작
geometry명시적

8.2. 관리 함수

Abstract

These functions assist in defining tables containing geometry columns.

AddGeometryColumn — 공간 테이블에서 지오메트리 컬럼을 제거합니다.
DropGeometryColumn — 공간 테이블에서 지오메트리 컬럼을 제거합니다.
DropGeometryTable — 테이블 및 geometry_columns의 모든 참조를 삭제합니다.
Find_SRID — Returns the SRID defined for a geometry column.
Populate_Geometry_Columns — Ensures geometry columns are defined with type modifiers or have appropriate spatial constraints.
UpdateGeometrySRID — Updates the SRID of all features in a geometry column, and the table metadata.

Name

AddGeometryColumn — 공간 테이블에서 지오메트리 컬럼을 제거합니다.

Synopsis

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, 지오메트리 타입, 차원 등이 잘못된 경우 오류가 발생됩니다.

[Note]

변경사항: 2.0.0 이 함수는 geometry_columns이 시스템 카테고리에서 읽히는 뷰인 동안 더 이상 geometry_columns을 업데이트 하지 않습니다. 이것은 기본적으로 컨스트레인트를 만들지 않지만, 대신에 PostgreSQL의 내장된 타입 변경 동작이 대신합니다. 그래서 예를 들어 WGS84 POINT 컬럼을 이 함수로 만든다면 이 함수는 다음과 동등합니다: ALTER TABLE some_table ADD COLUMN geom geometry(Point,4326);

변경 사항: 2.0.0 버전. 제약조건의 구식 습성이 필요할 경우, 기본값인 use_typmod 를 이용하되, 거짓으로 설정하십시오.

[Note]

변경 사항: 2.0.0 버전. 더 이상 뷰를 직접 geometry_columns에 등록시킬 수는 없지만, 도형 typmod 테이블 도형을 기반으로 빌드된 , 그리고 래퍼 함수 없이 사용되는 뷰는 자신의 페어런트 테이블 열의 typmod 습성을 상속하기 때문에 스스로를 정확히 등록시킵니다. 이런 뷰 도형 열을 geometry_columns에 정확히 등록시키려면, 다른 도형을 출력하는 도형 함수를 이용하는 뷰를 typmod 도형으로 형변환시켜야 할 것입니다. Section 4.6.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

개선 사항: 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);

-- 예전 제약조건 기반 습성을 이용해서 포인트를 추가
SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom_c',4326,'POINT',2, false);

-- 예전 제약조건 습성을 이용해서 만곡 폴리곤을 추가
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

Name

DropGeometryColumn — 공간 테이블에서 지오메트리 컬럼을 제거합니다.

Synopsis

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

[Note]

변경 사항: 2.0.0 버전. 하위 호환성을 위해 이 함수를 제공합니다. 이제는 geometry_columns이 시스템 카탈로그를 기반으로 하는 뷰이기 때문에, 다른 어떤 테이블 열과도 마찬가지로 도형 열도 ALTER TABLE 을 이용해서 삭제할 수 있습니다.

예제

SELECT DropGeometryColumn ('my_schema','my_spatial_table','geom');
                        -- 결과 출력물 --
                                          dropgeometrycolumn
------------------------------------------------------
 my_schema.my_spatial_table.geom effectively removed.

-- PostGIS 2.0 이상 버전에서 위 쿼리는 표준 대체 테이블과도 동등합니다.
-- 양쪽 모두 geometry_columns로부터 등록 해제될 것입니다.
ALTER TABLE my_schema.my_spatial_table DROP column geom;
                

Name

DropGeometryTable — 테이블 및 geometry_columns의 모든 참조를 삭제합니다.

Synopsis

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에 있는 테이블의 모든 참조를 삭제합니다. 주의: 스키마를 제공하지 않는다면 스키마를 인식하는(schema-aware) pgSQL 설치 상에서 current_schema()를 사용해보십시오.

[Note]

변경 사항: 2.0.0 버전. 하위 호환성을 위해 이 함수를 제공합니다. 이제는 geometry_columns이 시스템 카탈로그를 기반으로 하는 뷰이기 때문에, 다른 어떤 테이블과도 마찬가지로 도형 열을 가진 테이블도 DROP TABLE 을 이용해서 삭제할 수 있습니다.

예제

SELECT DropGeometryTable ('my_schema','my_spatial_table');
-- 결과 출력물 --
my_schema.my_spatial_table dropped.

-- 이제 위 쿼리는 다음과 동등합니다. --
DROP TABLE my_schema.my_spatial_table;
                

Name

Find_SRID — Returns the SRID defined for a geometry column.

Synopsis

integer Find_SRID(varchar a_schema_name, varchar a_table_name, varchar a_geomfield_name);

설명

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.

예제

SELECT Find_SRID('public', 'tiger_us_state_2007', 'geom_4269');
find_srid
----------
4269

관련 정보

ST_SRID


Name

Populate_Geometry_Columns — Ensures geometry columns are defined with type modifiers or have appropriate spatial constraints.

Synopsis

text Populate_Geometry_Columns(boolean use_typmod=true);

int Populate_Geometry_Columns(oid relation_oid, boolean use_typmod=true);

설명

지오메트리 컬럼이 타입 변경자로 정의되거나 적절한 공간 제약을 가지고 있는지 확인합니다. 이 함수는 공간 관련 테이블들이 geometry_columns 뷰에 올바르게 등록되도록 합니다. 기본적으로 유형 변경자를 가지지 않는 모든 지오메트리 컬럼들을 유형 변경자를 가진 지오메트리 컬럼들로 변환시킵니다. 엣날식 동작을 원하면 use_typmod=false으로 설정

하위 호환성 및 각 차일드 테이블이 서로 다른 도형 유형을 가질 수도 있는 테이블 상속 같은 공간 필요성을 위해, 구 버전 확인 제약조건 습성을 계속 지원합니다. 구 버전 습성이 필요하다면, use_typmod=false 처럼 새 선택적 인자를 거짓으로 패스해야 합니다. 이렇게 하면 유형 변경자는 없지만 제약조건 3개가 정의된 도형 열을 생성할 것입니다. 다시 말해, 모든 도형 열이 적어도 3개의 제약조건을 가진 테이블에 종속된다는 뜻입니다:

  • enforce_dims_the_geom - ensures every geometry has the same dimension (see ST_NDims)

  • enforce_geotype_the_geom - ensures every geometry is of the same type (see 도형 유형)

  • enforce_srid_the_geom - ensures every geometry is in the same projection (see ST_SRID)

oid 테이블이 제공될 경우, 이 함수는 테이블에 있는 모든 도형 열의 SRID, 차원, 그리고 도형 유형을 결정하려 하며, 필요한 경우 제약조건을 추가하기도 합니다. 함수가 제대로 작동했다면, 올바른 행이 geometry_columns 테이블에 삽입됩니다. 아닐 경우, 예외가 잡혀 문제점을 설명하는 오류 메시지가 뜹니다.

oid 테이블과 함께 oid 뷰가 제공될 경우, 이 함수는 geometry_columns 테이블에 올바른 항목을 삽입하며 뷰에 있는 모든 도형의 SRID, 차원, 유형을 결정하려 하지만, 제약조건을 강제하지는 않습니다.

이 함수의 파라미터가 없는 변종은, 공간 제약조건을 테이블의 적절한 곳에 추가하며 먼저 데이터베이스 내부의 모든 공간 테이블 및 뷰에 대해 geometry_columns 테이블의 용량을 줄이고(truncate) 다시 채우는 파라미터가 있는 변종을 위한 단순 래퍼입니다. 파라미터가 없는 변종은 데이터베이스 내부에서 감지된 도형 열의 개수 및 geometry_columns 테이블로 삽입된 개수를 요약해서 반환합니다. 파라미터가 있는 버전은 단순히 geometry_columns 테이블로 삽입된 행의 개수를 반환합니다.

유효버전: 1.4.0

변경 사항: 2.0.0 버전. 이제 도형 유형을 제한하기 위해 확인 제약조건 대신 유형 변경자를 이용합니다. 새 use_typmod 를 거짓으로 설정하면, 확인 제약조건 습성을 계속 쓸 수 있습니다.

개선 사항: 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) );
-- 이제 유형 수정자(typ modifier)를 이용할 것입니다. 이 쿼리가 작동하려면, 데이터가 존재해야만 합니다.
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) |
-- 도형 열이 typmod가 아니거나 이미 제약조건을 가지고 있지 않을 경우, 제약조건을 이용하도록 도형 열을 변경할 것입니다.
-- 이 쿼리가 작동하려면, 데이터가 존재해야만 합니다.
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)

Name

UpdateGeometrySRID — Updates the SRID of all features in a geometry column, and the table metadata.

Synopsis

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);

설명

지오메트리 컬럼, geometry_columns 메타데이터 및 srid를 대상으로 모든 피처들의 SRID를 갱신합니다. 주의: 만약 스키마가 지원되지 않으면 schema-aware pgsql installations 설치본에서 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 선언문과 동일합니다:

ALTER TABLE roads
  ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 4326)
    USING ST_SetSRID(geom,4326);

로드 작업 중 투영체를 잘못 (또는 'unknown'으로) 적용했는데 모든 데이터를 한번에 웹 메르카토르로 변환하고 싶다면, DDL을 통해 가능합니다. 하지만 PostGIS 관리 함수 가운데 한번에 이런 작업을 할 수 있는 동일한 함수는 없습니다.

ALTER TABLE roads
 ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 3857) USING ST_Transform(ST_SetSRID(geom,4326),3857) ;

8.3. 도형 작성자(constructor)

ST_GeomCollFromText — Creates a GeometryCollection or Multi* geometry from a set of geometries.
ST_LineFromMultiPoint — 멀티포인트 도형으로부터 라인스트링을 생성합니다.
ST_MakeEnvelope — 주어진 최소값과 최대값으로 형성된 직사각형 폴리곤을 생성합니다. 입력값이 SRID로 지정된 SRS를 가지고 있어야 합니다.
ST_MakeLine — 포인트, 멀티포인트 또는 라인 도형으로부터 라인스트링을 생성합니다.
ST_MakePoint — Creates a 2D, 3DZ or 4D Point.
ST_MakePointM — x, y 좌표 및 단위를 가진 포인트를 생성합니다.
ST_MakePolygon — Creates a Polygon from a shell and optional list of holes.
ST_Point — Creates a Point with X, Y and SRID values.
ST_Point — Creates a Point with X, Y, Z and SRID values.
ST_Point — Creates a Point with X, Y, M and SRID values.
ST_Point — Creates a Point with X, Y, Z, M and SRID values.
ST_Polygon — Creates a Polygon from a LineString with a specified SRID.
ST_MakeEnvelope — Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.
ST_HexagonGrid — Returns a set of hexagons and cell indices that completely cover the bounds of the geometry argument.
ST_Hexagon — Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon grid space.
ST_SquareGrid — Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.
ST_Square — Returns a single square, using the provided edge size and cell coordinate within the square grid space.
ST_Letters — Returns the input letters rendered as geometry with a default start position at the origin and default text height of 100.

Name

ST_GeomCollFromText — Creates a GeometryCollection or Multi* geometry from a set of geometries.

Synopsis

geometry ST_MakeLine(geometry set geoms);

geometry ST_MakeLine(geometry geom1, geometry geom2);

geometry ST_MakeLine(geometry[] geoms_array);

설명

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.

[Note]

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).

[Note]

ST_Collect and ST_Union 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.

1.4.0 버전부터 사용할 수 있습니다. 이 버전부터 ST_MakeLine가 도형 배열을 입력받을 수 있습니다. 더 많은 포인트를 더 빨리 처리하기 위해 ST_MakeLine 합산 함수를 개선했습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves

예시: XLink 사용

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))

예시: 공간 합산 버전

Creating multiple collections by grouping geometries in a table.

SELECT stusps, ST_Collect(f.geom) as geom
         FROM (SELECT stusps, (ST_Dump(geom)).geom As geom
                                FROM
                                somestatetable ) As f
        GROUP BY stusps

Name

ST_LineFromMultiPoint — 멀티포인트 도형으로부터 라인스트링을 생성합니다.

Synopsis

geometry ST_LineFromMultiPoint(geometry aMultiPoint);

설명

멀티포인트 도형으로부터 라인스트링을 생성합니다.

Use ST_MakeLine to create lines from Point or LineString inputs.

This function supports 3d and will not drop the z-index.

예시

멀티포인트 도형으로부터 라인스트링을 생성합니다.

-- 3D 멀티포인트로부터 3D 라인스트링 생성하기
SELECT ST_AsEWKT(ST_LineFromMultiPoint(ST_GeomFromEWKT('MULTIPOINT(1 2 3, 4 5 6, 7 8 9)')));
-- 결과 --
LINESTRING(1 2 3,4 5 6,7 8 9)

Name

ST_MakeEnvelope — 주어진 최소값과 최대값으로 형성된 직사각형 폴리곤을 생성합니다. 입력값이 SRID로 지정된 SRS를 가지고 있어야 합니다.

Synopsis

geometry ST_MakeEnvelope(double precision xmin, double precision ymin, double precision xmax, double precision ymax, integer srid=unknown);

설명

최소값과 최대값으로 형성된 직사각형 폴리곤을 생성합니다. 입력값이 SRID로 지정된 SRS를 가지고 있어야 합니다. 지정된 SRID가 없을 경우 알려지지 않은 공간 참조 시스템을 쓴다고 가정합니다.

1.5 버전부터 사용할 수 있습니다.

개선 사항: 2.0 버전부터 SRID를 지정하지 않고도 직사각형(envelope)을 설정할 수 있는 기능이 추가됐습니다.

예시: 경계 상자 폴리곤을 빌드하기

SELECT ST_AsText(ST_MakeEnvelope(10, 10, 11, 11, 4326));

st_asewkt
-----------
POLYGON((10 10, 10 11, 11 11, 11 10, 10 10))

Name

ST_MakeLine — 포인트, 멀티포인트 또는 라인 도형으로부터 라인스트링을 생성합니다.

Synopsis

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.

2.0.0 버전부터 라인스트링 구성 요소 입력을 지원하기 시작했습니다.

2.0.0 버전부터 라인스트링 구성 요소 입력을 지원하기 시작했습니다.

1.4.0 버전부터 사용할 수 있습니다. 이 버전부터 ST_MakeLine가 도형 배열을 입력받을 수 있습니다. 더 많은 포인트를 더 빨리 처리하기 위해 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));

-- 3D 포인트 3개로 3D 라인 만들기
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)

주어진 3D 포인트 도형 2개로 정의되는 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));

-- 3D 포인트 3개로 3D 라인 만들기
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 포인트들로 이루어진 라인스트링인 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.

SELECT gps.track_id, ST_MakeLine(gps.geom) As geom
        FROM ( SELECT track_id, gps_time, geom
                        FROM gps_points ORDER BY track_id, gps_time ) As gps
        GROUP BY track_id;

Name

ST_MakePoint — Creates a 2D, 3DZ or 4D Point.

Synopsis

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);

설명

주어진 포인트 도형들로 정의되는 BOX2D를 생성합니다.

Use ST_MakePointM to make points with XYM coordinates.

While not OGC-compliant, ST_MakePoint is faster and more precise than ST_GeomFromText and ST_PointFromText. It is also easier to use for numeric coordinate values.

[Note]

For geodetic coordinates, X is longitude and Y is latitude

This function supports 3d and will not drop the z-index.

예시

-- 알려지지 않은 SRID를 가진 포인트를 반환
SELECT ST_MakePoint(-71.1043443253471, 42.3150676015829);

-- WGS84 경위도로 표시된 포인트를 반환
SELECT ST_SetSRID(ST_MakePoint(-71.1043443253471, 42.3150676015829),4326);

-- 3D (예를 들자면 고도를 가진) 포인트를 반환
SELECT ST_MakePoint(1, 2,1.5);

-- 포인트의 z를 얻어오기
SELECT ST_Z(ST_MakePoint(1, 2,1.5));
result
-------
1.5

Name

ST_MakePointM — x, y 좌표 및 단위를 가진 포인트를 생성합니다.

Synopsis

geometry ST_MakePointM(float x, float y, float m);

설명

x, y 좌표 및 단위를 가진 포인트를 생성합니다.

Use ST_MakePoint to make points with XY, XYZ, or XYZM coordinates.

[Note]

For geodetic coordinates, X is longitude and Y is latitude

예시

[Note]

ST_AsEWKT is used for text output because ST_AsText does not support M values.

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 좌표 및 단위를 가진 포인트를 생성합니다.

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

Name

ST_MakePolygon — Creates a Polygon from a shell and optional list of holes.

Synopsis

geometry ST_MakePolygon(geometry linestring);

geometry ST_MakePolygon(geometry outerlinestring, geometry[] interiorlinestrings);

설명

주어진 외부 구조(shell)로 형성된 폴리곤을 생성합니다. 입력 도형이 닫힌 라인스트링이어야 합니다.

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.

[Note]

이 함수에 멀티라인스트링을 입력할 수는 없습니다. 라인스트링을 생성하려면 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.

[Note]

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;

Name

ST_Point — Creates a Point with X, Y and SRID values.

Synopsis

geometry ST_Point(float x_lon, float y_lat);

geometry ST_MakePointM(float x, float y, float m);

설명

Returns a Point with the given X and Y coordinate values. This is the SQL-MM equivalent for ST_MakePoint that takes just X and Y.

[Note]

For geodetic coordinates, X is longitude and Y is latitude

Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.

This method implements the SQL/MM specification. SQL-MM 3: 6.1.2

예시: 도형

SELECT ST_Point( -71.104, 42.315);
SELECT ST_SetSRID(ST_Point( -71.104, 42.315),4326);

New in 3.2.0: With SRID specified

SELECT ST_Point( -71.104, 42.315, 4326);

예시: 지리형

Pre-PostGIS 3.2 syntax

SELECT CAST( ST_SetSRID(ST_Point( -71.104, 42.315), 4326) AS geography);

3.2 and on you can include the srid

SELECT CAST( ST_Point( -71.104, 42.315, 4326) AS geography);

PostgreSQL also provides the :: short-hand for casting

SELECT ST_Point( -71.104, 42.315, 4326)::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);

Name

ST_Point — Creates a Point with X, Y, Z and SRID values.

Synopsis

geometry ST_MakePoint(double precision x, double precision y, double precision z, double precision m);

설명

주어진 좌표값을 가진 ST_Point를 반환합니다. ST_MakePoint와 동일한 OGC 함수입니다.

Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.

예시

SELECT ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326)
SELECT ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326)
SELECT ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326)

Name

ST_Point — Creates a Point with X, Y, M and SRID values.

Synopsis

geometry ST_PointM(float x, float y, float m, integer srid=unknown);

설명

주어진 좌표값을 가진 ST_Point를 반환합니다. ST_MakePoint와 동일한 OGC 함수입니다.

Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.

예시

SELECT ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326)
SELECT ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326)
SELECT ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326)

Name

ST_Point — Creates a Point with X, Y, Z, M and SRID values.

Synopsis

geometry ST_MakeEnvelope(double precision xmin, double precision ymin, double precision xmax, double precision ymax, integer srid=unknown);

설명

주어진 좌표값을 가진 ST_Point를 반환합니다. ST_MakePoint와 동일한 OGC 함수입니다.

Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.

예시

SELECT ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326)
SELECT ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326)
SELECT ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326)

Name

ST_Polygon — Creates a Polygon from a LineString with a specified SRID.

Synopsis

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_SetSRID

[Note]

이 함수에 멀티라인스트링을 입력할 수는 없습니다. 라인스트링을 생성하려면 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))

Name

ST_MakeEnvelope — Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.

Synopsis

geometry ST_MakePoint(double precision x, double precision y, double precision z, double precision m);

설명

Creates a rectangular Polygon giving the extent of a tile in the XYZ tile system. The tile is specifed by the zoom level Z and the XY index of the tile in the grid at that level. Can be used to define the tile bounds required by ST_AsMVTGeom to convert geometry into the MVT tile coordinate space.

By default, the tile envelope is in the Web Mercator coordinate system (SRID:3857) using the standard range of the Web Mercator system (-20037508.342789, 20037508.342789). This is the most common coordinate system used for MVT tiles. The optional bounds parameter can be used to generate tiles in any coordinate system. It is a geometry that has the SRID and extent of the "Zoom Level zero" square within which the XYZ tile system is inscribed.

The optional margin parameter can be used to expand a tile by the given percentage. E.g. margin=0.125 expands the tile by 12.5%, which is equivalent to buffer=512 when the tile extent size 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 the tile rendering. For example, a city name (a point) could be near an edge of a tile, so its label should be rendered on two tiles, even though the point is located in the visible area of just one tile. Using expanded tiles in a query will include the city point in both tiles. Use a negative value to shrink the tile instead. Values less than -0.5 are prohibited because that would eliminate the tile completely. Do not specify a margin when using with ST_AsMVTGeom. See the example for ST_AsMVT.

개선 사항: 2.0.0 버전에서 선택적인 기본 SRID 파라미터가 추가됐습니다.

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))

Name

ST_HexagonGrid — Returns a set of hexagons and cell indices that completely cover the bounds of the geometry argument.

Synopsis

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.

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.

[Note]

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)

Name

ST_Hexagon — Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon grid space.

Synopsis

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 ST_SetSRID to set the SRID to the one you expect.

2.1.0 버전부터 사용할 수 있습니다.

Example: Creating a hexagon at the origin

SELECT ST_AsText(ST_SetSRID(ST_Hexagon(1.0, 0, 0), 3857));

POLYGON((-1 0,-0.5
         -0.866025403784439,0.5
         -0.866025403784439,1
         0,0.5
         0.866025403784439,-0.5
         0.866025403784439,-1 0)) 

Name

ST_SquareGrid — Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.

Synopsis

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.

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

예시: 배열 버전 사용하기

This yields the same result as the first example but will be slower for a large number of points

SELECT COUNT(*), squares.geom
    FROM
    pointtable AS pts
    INNER JOIN
    ST_SquareGrid(
        1000,
       pts.geom
    ) AS squares
    ON ST_Intersects(pts.geom, squares.geom)
    GROUP BY squares.geom

Name

ST_Square — Returns a single square, using the provided edge size and cell coordinate within the square grid space.

Synopsis

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 ST_SetSRID to set the SRID to the one you expect.

2.1.0 버전부터 사용할 수 있습니다.

Example: Creating a square at the origin

SELECT ST_AsText(ST_MakeEnvelope(10, 10, 11, 11, 4326));

st_asewkt
-----------
POLYGON((10 10, 10 11, 11 11, 11 10, 10 10))

Name

ST_Letters — Returns the input letters rendered as geometry with a default start position at the origin and default text height of 100.

Synopsis

geometry ST_Letters(text letters, json font);

설명

Uses a built-in font to render out a string as a multipolygon geometry. The default text height is 100.0, the distance from the bottom of a descender to the top of a capital. The default start position places the start of the baseline at the origin. Over-riding the font involves passing in a json map, with a character as the key, and base64 encoded TWKB for the font shape, with the fonts having a height of 1000 units from the bottom of the descenders to the tops of the capitals.

The text is generated at the origin by default, so to reposition and resize the text, first apply the ST_Scale function and then apply the ST_Translate function.

2.1.0 버전부터 사용할 수 있습니다.

예시: 경계 상자 폴리곤을 빌드하기

SELECT ST_AsText(ST_Letters('Yo'), 1);

Letters generated by ST_Letters

Example: Scaling and moving words

SELECT ST_Translate(ST_Scale(ST_Letters('Yo'), 10, 10), 100,100);

8.4. 도형 접근자(accessor)

도형 유형 — ST_Geometry 값의 도형 유형을 반환합니다.
ST_Boundary — 해당 도형의 결합된 범위의 닫힘 여부를 반환합니다.
ST_BoundingDiagonal — 주어진 도형의 경계 상자의 대각선을 반환합니다.
ST_CoordDim — ST_Geometry 값의 좌표 차원을 반환합니다.
ST_Dimension — ST_Geometry 값의 좌표 차원을 반환합니다.
ST_Dump — Returns a set of geometry_dump rows for the components of a geometry.
ST_NumPoints — 도형의 내용을 요약한 텍스트를 반환합니다.
ST_NumPoints — 도형의 내용을 요약한 텍스트를 반환합니다.
ST_NRings — Returns a set of geometry_dump rows for the exterior and interior rings of a Polygon.
ST_EndPoint — ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.
ST_Envelope — 주어진 도형의 이중 정밀도(double precision; float8) 경계 상자를 표현하는 도형을 반환합니다.
ST_ExteriorRing — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
ST_GeometryN — ST_Geometry 값의 도형 유형을 반환합니다.
ST_GeometryType — ST_Geometry 값의 도형 유형을 반환합니다.
ST_HasArc — Tests if a geometry contains a circular arc
ST_InteriorRingN — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
ST_IsClosedLINESTRING 의 시작점과 종단점이 일치하는 경우 TRUE 를 반환합니다. 다면체 표면이 닫혀 (부피를 가지고) 있는 경우 TRUE 를 반환합니다.
ST_IsCollection — 해당 도형이 텅 빈 도형 집합, 폴리곤, 포인트 등인 경우 TRUE 를 반환합니다.
ST_IsEmpty — Tests if a geometry is empty.
ST_IsPolygonCCW — Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.
ST_IsPolygonCW — Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.
ST_IsRing — Tests if a LineString is closed and simple.
ST_IsSimple — 해당 도형이 자체 교차하거나 자체 접촉하는 이례적인 도형 포인트를 가지고 있지 않을 경우 TRUE 를 반환합니다.
ST_M — Returns the M coordinate of a Point.
ST_MemSize — ST_Geometry 값의 도형 유형을 반환합니다.
ST_NDims — ST_Geometry 값의 좌표 차원을 반환합니다.
ST_NPoints — 도형이 가지고 있는 포인트(꼭짓점)의 개수를 반환합니다.
ST_NRings — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
ST_NumGeometries — 도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.
ST_NumInteriorRings — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
ST_NumInteriorRing — 도형 안에 있는 폴리곤의 내곽 고리의 개수를 반환합니다. ST_NumInteriorRings 함수와 동일합니다.
ST_NumPatches — 다면체 표면 상에 있는 면의 개수를 반환합니다. 다면체 도형이 아닌 경우 NULL을 반환할 것입니다.
ST_NumPoints — ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.
ST_PatchN — ST_Geometry 값의 도형 유형을 반환합니다.
ST_PointN — ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.
ST_Points — 도형의 모든 좌표들을 담고 있는 멀티포인트를 반환합니다.
ST_StartPoint — Returns the first point of a LineString.
ST_Summary — 도형의 내용을 요약한 텍스트를 반환합니다.
ST_X — Returns the X coordinate of a Point.
ST_Y — Returns the Y coordinate of a Point.
ST_Z — Returns the Z coordinate of a Point.
ST_Zmflag — ST_Geometry 값의 좌표 차원을 반환합니다.

Name

도형 유형 — ST_Geometry 값의 도형 유형을 반환합니다.

Synopsis

text GeometryType(geometry geomA);

설명

도형의 유형을 스트링으로 반환합니다. 예: 'LINESTRING', 'POLYGON', 'MULTIPOINT' 등등.

OGC 사양 s2.1.1.1 - 해당 도형 인스턴스가 속해 있는, 인스턴스화할 수 있는 도형 하위 유형의 명칭을 스트링으로 반환합니다.

[Note]

이 함수는 'POINTM' 형식의 스트링을 반환해서 도형에 단위가 적용되었는지 여부도 보여줍니다.

개선 사항: 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    

Name

ST_Boundary — 해당 도형의 결합된 범위의 닫힘 여부를 반환합니다.

Synopsis

geometry ST_Boundary(geometry geomA);

설명

해당 도형의 결합된 범위의 닫힘(closure) 여부를 반환합니다. 결합 범위(combinatorial boundary)는 OGC 사양서의 3.12.3.2 단원이 설명하는대로 정의됩니다. 이 함수의 결과가 닫힘이기 때문에, 즉 위상적(位相的)으로 폐쇄됐기 때문에, OGC 사양서 3.12.2 단원에서 설명한대로 표현적인 도형 원형(primitive)을 이용해서 결과 범위를 표현할 수 있습니다.

GEOS 모듈로 실행

[Note]

2.0.0 미만 버전에서 이 함수를 GEOMETRYCOLLECTION과 함께 사용하면 예외가 발생했습니다. 2.0.0 이후 버전은 대신 (입력을 지원하지 않는다는 의미의) NULL을 반환합니다.

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 IEC 13249-3: 5.1.17

This function supports 3d and will not drop the z-index.

개선 사항: 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 output
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)

--Using a 3d polygon
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)

--Using a 3d multilinestring
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))

Name

ST_BoundingDiagonal — 주어진 도형의 경계 상자의 대각선을 반환합니다.

Synopsis

geometry ST_BoundingDiagonal(geometry geom, boolean fits=false);

설명

주어진 도형의 경계 상자의 대각선을 라인스트링으로 반환합니다. 빈 도형을 입력받은 경우 빈 대각선을 반환하게 됩니다. 빈 도형이 아니라면 포인트 2개 중 시작점이 각 차원의 최소값들을, 종단점이 각 차원의 최대값들을 가진 라인스트링을 반환합니다.

fits 파라미터는 딱 맞는(best fit) 경계 상자가 필요한지 여부를 설정합니다. 거짓으로 설정한다면 조금 넉넉한 경계 상자도 용납할 수 있습니다(수많은 꼭짓점을 가진 도형의 경우 더 빨리 처리할 수 있습니다). 어떤 경우든 반환된 대각선의 경계 상자는 항상 입력 도형을 둘러쌉니다.

반환된 라인스트링 도형은 언제나 입력 도형의 SRID 및 차원수를 유지합니다.

[Note]

차원이 낮은 (입력 도형이 단일 꼭짓점) 경우 반환되는 라인스트링이 위상적으로 유효하지 않을 (내부가 없을) 것입니다. 그렇다고 해서 반환된 도형이 의미론적으로 유효하지 않다는 뜻은 아닙니다.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

예시

-- 포인트를 둘러싼 버퍼에서 X의 최소값을 얻습니다.
SELECT ST_X(ST_StartPoint(ST_BoundingDiagonal(
  ST_Buffer(ST_MakePoint(0,0),10)
)));
 st_x
------
  -10
                

Name

ST_CoordDim — ST_Geometry 값의 좌표 차원을 반환합니다.

Synopsis

integer ST_CoordDim(geometry geomA);

설명

ST_Geometry 값의 좌표 차원을 반환합니다.

이 함수는 MM을 준수하는, ST_NDims 와 동일한 함수합니다.

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).

예시

SELECT ST_CoordDim('CIRCULARSTRING(1 2 3, 1 3 4, 5 6 7, 8 9 10, 11 12 13)');
-- 결과 --
3

SELECT ST_CoordDim(ST_Point(1,2));
-- 결과 --
2

                

참고

ST_NDims


Name

ST_Dimension — ST_Geometry 값의 좌표 차원을 반환합니다.

Synopsis

integer ST_Dimension(geometry g);

설명

좌표 차원과 동등하거나 낮아야 하는, 해당 도형 객체의 내재된 차원을 반환합니다. OGC 사양서 s2.1.1.1 단원을 보면 POINT 는 0, LINESTRING 은 1, POLYGON 은 2, 그리고 GEOMETRYCOLLECTION 의 경우 구성 요소 가운데 가장 높은 차원입니다. 알려지지 않은 (텅 빈) 도형인 경우 null을 반환합니다.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.2

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다. 빈 도형이 주어져도 더 이상 예외가 발생하지 않습니다.

[Note]

2.0.0 미만 버전에서는 빈 도형에 대해 예외를 발생시켰습니다.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

SELECT ST_Dimension('GEOMETRYCOLLECTION(LINESTRING(1 1,0 0),POINT(0 0))');
ST_Dimension
-----------
1

참고

ST_NDims


Name

ST_Dump — Returns a set of geometry_dump rows for the components of a geometry.

Synopsis

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.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

Availability: PostGIS 1.0.0RC1. Requires PostgreSQL 7.3 or higher.

[Note]

1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 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)

다면체 표면, TIN 및 삼각형 예시

-- 다면체 표면 예시
-- 다면체 표면을 각 면으로 분해하기
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))

Name

ST_NumPoints — 도형의 내용을 요약한 텍스트를 반환합니다.

Synopsis

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 POINTs 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.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

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.

Classic Explode a Table of LineStrings into nodes

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)

다면체 표면, TIN 및 삼각형 예시

-- 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))

Name

ST_NumPoints — 도형의 내용을 요약한 텍스트를 반환합니다.

Synopsis

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.

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 및 삼각형 예시

-- 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))

Name

ST_NRings — Returns a set of geometry_dump rows for the exterior and interior rings of a Polygon.

Synopsis

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.

[Note]

이 함수는 멀티폴리곤을 입력받지 못 합니다. 멀티폴리곤의 경우 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))

Name

ST_EndPoint — ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.

Synopsis

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

[Note]

변경 사항: 2.0.0 버전부터 단일 도형 멀티라인스트링을 지원하지 않습니다. PostGIS 예전 버전이라면 단일 라인 멀티라인스트링을 입력받는 경우 시작점을 반환했을 겁니다. 2.0.0 버전은 다른 모든 멀티라인스트링처럼 NULL을 반환할 뿐입니다. 구식 습성은 문서화되지 않은 기능이지만, 사용자 데이터를 라인스트링으로 저장했다고 가정한 사용자의 경우 현재 2.0 버전에서 NULL이 반환될 수도 있습니다.

예시

End point of a LineString

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

End point of a 3D LineString

--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)

Name

ST_Envelope — 주어진 도형의 이중 정밀도(double precision; float8) 경계 상자를 표현하는 도형을 반환합니다.

Synopsis

geometry ST_Envelope(geometry g1);

설명

주어진 도형에 대해 float8 형 최소치 경계 상자를 도형으로 반환합니다. 해당 폴리곤은 경계 상자의 꼭짓점 포인트들로 정의됩니다((MINX, MINY), (MINX, MAXY), (MAXX, MAXY), (MAXX, MINY), (MINX, MINY)). (PostGIS는 ZMIN/ZMAX 좌표도 추가할 것입니다.)

차원이 낮은 (수직 라인, 포인트) 경우 POLYGON 보다 낮은 차원의, 예를 들어 POINT 또는 LINESTRING 도형을 반환할 것입니다.

1.5.0 버전부터 사용할 수 있으며, float4 형 대신 이중 정밀도 형으로 출력하도록 변경되었습니다.

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.19

예시

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;


        

Envelope of a point and linestring.

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))

Name

ST_ExteriorRing — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.

Synopsis

geometry ST_ExteriorRing(geometry a_polygon);

설명

POLYGON 도형의 외곽 고리(exterior ring)를 표현하는 라인스트링을 반환합니다. 도형이 폴리곤이 아닌 경우 NULL을 반환합니다.

[Note]

이 함수는 멀티폴리곤을 입력받지 못 합니다. 멀티폴리곤의 경우 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;

--3d Example
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)

Name

ST_GeometryN — ST_Geometry 값의 도형 유형을 반환합니다.

Synopsis

geometry ST_GeometryN(geometry geomA, integer n);

설명

입력 도형이 도형 집합, (멀티)포인트, (멀티)라인스트링, 멀티커브(multicurve) 또는 (멀티)폴리곤이나 다면체 표면일 경우 1-기반 N번째 도형을 반환하며, 그 외의 경우 NULL을 반환합니다.

[Note]

0.8.0 버전부터 인덱스는 OGC 사양을 따라 1-기반입니다. 예전 버전은 대신 0-기반 인덱스를 시행했습니다.

[Note]

모든 도형들을 추출하고자 한다면 ST_Dump 함수가 더 효율적이며, 단일 도형에 대해서도 작동할 것입니다.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

변경 사항: 2.0.0 미만 버전은 단일 도형에 대해 NULL을 반환했을 겁니다. 2.0.0 버전부터 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).

표준 예시

--Extracting a subset of points from a 3d multipoint
SELECT n, ST_AsEWKT(ST_GeometryN(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(geom)
        CROSS JOIN generate_series(1,100) n
WHERE n <= ST_NumGeometries(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)


--Extracting all geometries (useful when you want to assign an id)
SELECT gid, n, ST_GeometryN(geom, n)
FROM sometable CROSS JOIN generate_series(1,100) n
WHERE n <= ST_NumGeometries(geom);

다면체 표면, TIN 및 삼각형 예시

-- 다면체 표면 예시
-- 다면체 표면을 각 면으로 분해하기
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))

Name

ST_GeometryType — ST_Geometry 값의 도형 유형을 반환합니다.

Synopsis

text ST_GeometryType(geometry g1);

설명

도형의 유형을 'ST_LineString', 'ST_Polygon', 'ST_MultiPolygon' 등과 같은 스트링으로 반환합니다. 이 함수는 도형의 단위가 설정돼 있는지 알려주지 않는 것은 물론, 반환된 결과물이 스트링이며 접두사 ST가 달린다는 점에서도 GeometryType(geometry) 함수와는 다릅니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

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    

Name

ST_HasArc — Tests if a geometry contains a circular arc

Synopsis

boolean ST_IsEmpty(geometry geomA);

설명

해당 도형이 텅 빈 도형 집합, 폴리곤, 포인트 등인 경우 TRUE 를 반환합니다.

1.2.2 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves

예시

SELECT ST_HasArc(ST_Collect('LINESTRING(1 2, 3 4, 5 6)', 'CIRCULARSTRING(1 1, 2 3, 4 5, 6 7, 5 6)'));
                st_hasarc
                --------
                t
                

Name

ST_InteriorRingN — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.

Synopsis

geometry ST_InteriorRingN(geometry a_polygon, integer n);

설명

폴리곤 도형의 N번째 내곽 라인스트링 고리를 반환합니다. 도형이 폴리곤이 아니거나 주어진 N이 범위(range)를 벗어난 경우 NULL을 반환합니다.

[Note]

이 함수는 멀티폴리곤을 입력받지 못 합니다. 멀티폴리곤의 경우 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.

예시

SELECT ST_AsText(ST_InteriorRingN(the_geom, 1)) As the_geom
FROM (SELECT ST_BuildArea(
                ST_Collect(ST_Buffer(ST_Point(1,2), 20,3),
                        ST_Buffer(ST_Point(1, 2), 10,3))) As the_geom
                )  as foo
                

Name

ST_IsClosed — LINESTRING 의 시작점과 종단점이 일치하는 경우 TRUE 를 반환합니다. 다면체 표면이 닫혀 (부피를 가지고) 있는 경우 TRUE 를 반환합니다.

Synopsis

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

[Note]

SQL-MM은 ST_IsClosed(NULL) 의 결과를 0으로 정의하지만, PostGIS는 NULL 을 반환합니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

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_IsRing


Name

ST_IsCollection — 해당 도형이 텅 빈 도형 집합, 폴리곤, 포인트 등인 경우 TRUE 를 반환합니다.

Synopsis

boolean ST_IsCollection(geometry g);

설명

인수의 도형 유형이 다음 가운데 하나일 경우 TRUE 를 반환합니다:

  • GEOMETRYCOLLECTION

  • MULTI{POINT,POLYGON,LINESTRING,CURVE,SURFACE}

  • COMPOUNDCURVE

[Note]

이 함수는 도형의 유형을 분석합니다. 즉 비어 있거나 단일 요소를 담고 있는 집합일 경우에도 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)

Name

ST_IsEmpty — Tests if a geometry is empty.

Synopsis

boolean ST_IsEmpty(geometry geomA);

설명

해당 도형이 텅 빈 도형인 경우 TRUE 를 반환합니다. TRUE 인 경우, 해당 도형이 텅 빈 도형 집합, 폴리곤, 포인트 등을 표현한다는 뜻입니다.

[Note]

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

[Warning]

변경 사항: PostGIS 2.0.0 미만 버전에서는 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)


                

Name

ST_IsPolygonCCW — Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.

Synopsis

boolean ST_IsPolygonCCW ( geometry geom );

설명

Returns true if all polygonal components of the input geometry use a counter-clockwise orientation for their exterior ring, and a clockwise direction for all interior rings.

Returns true if the geometry has no polygonal components.

[Note]

Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single closed linestring no matter its orientation.

[Note]

If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.


Name

ST_IsPolygonCW — Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.

Synopsis

boolean ST_IsPolygonCW ( geometry geom );

설명

Returns true if all polygonal components of the input geometry use a clockwise orientation for their exterior ring, and a counter-clockwise direction for all interior rings.

Returns true if the geometry has no polygonal components.

[Note]

Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single closed linestring no matter its orientation.

[Note]

If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.


Name

ST_IsRing — Tests if a LineString is closed and simple.

Synopsis

boolean ST_IsRing(geometry g);

설명

해당 LINESTRINGST_IsClosed (ST_StartPoint(g) ~= ST_Endpoint(g)) 인 동시에 ST_IsSimple 인 (자체 교차하지 않는) 경우 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

[Note]

SQL-MM은 ST_IsRing(NULL) 의 결과를 0으로 정의하지만, PostGIS는 NULL 을 반환합니다.

예시

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)

Name

ST_IsSimple — 해당 도형이 자체 교차하거나 자체 접촉하는 이례적인 도형 포인트를 가지고 있지 않을 경우 TRUE 를 반환합니다.

Synopsis

boolean ST_IsSimple(geometry geomA);

설명

해당 도형이 자체 교차하거나 자체 접촉하는 이례적인 도형 포인트를 가지고 있지 않을 경우 TRUE 를 반환합니다. 도형 단순성 및 유효성에 대한 OGC의 정의를 더 자세히 알고 싶다면, "OpenGIS의 도형 준수성 확인(Ensuring OpenGIS compliancy of geometries)" 을 참조하십시오.

[Note]

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.

예시

SELECT ST_IsSimple(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))'));
 st_issimple
-------------
 t
(1 row)

 SELECT ST_IsSimple(ST_GeomFromText('LINESTRING(1 1,2 2,2 3.5,1 3,1 2,2 1)'));
 st_issimple
-------------
 f
(1 row)

Name

ST_M — Returns the M coordinate of a Point.

Synopsis

float ST_M(geometry a_point);

설명

포인트의 M 좌표를 반환합니다. M 좌표가 없는 경우 NULL을 반환합니다. 포인트만 입력받을 수 있습니다.

[Note]

이 함수는 (아직) OGC 사양에 들어가지 않지만, 포인트 좌표 추출자(extractor) 함수 목록을 완성하기 위해 이 문서에 작성됐습니다.

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.

예시

SELECT ST_M(ST_GeomFromEWKT('POINT(1 2 3 4)'));
 st_m
------
        4
(1 row)

                

Name

ST_MemSize — ST_Geometry 값의 도형 유형을 반환합니다.

Synopsis

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.

[Note]

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
        

Name

ST_NDims — ST_Geometry 값의 좌표 차원을 반환합니다.

Synopsis

integer ST_NDims(geometry g1);

설명

도형의 좌표 차원을 반환합니다. PostGIS는 2 - 2차원 (x,y), 3 - 3차원 (x,y,z), 3 - 단위를 가진 2차원 (x,y,m), 그리고 4 - 단위를 가진 3차원 공간 (x,y,z,m)을 지원합니다.

This function supports 3d and will not drop the z-index.

예시

SELECT ST_NDims(ST_GeomFromText('POINT(1 1)')) As d2point,
        ST_NDims(ST_GeomFromEWKT('POINT(1 1 2)')) As d3point,
        ST_NDims(ST_GeomFromEWKT('POINTM(1 1 0.5)')) As d2pointm;

         d2point | d3point | d2pointm
---------+---------+----------
           2 |       3 |        3
                        

Name

ST_NPoints — 도형이 가지고 있는 포인트(꼭짓점)의 개수를 반환합니다.

Synopsis

integer ST_NPoints(geometry g1);

설명

도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

[Note]

1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 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.

예시

SELECT ST_NPoints(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'));
-- 결과
4

-- 3차원 공간에 있는 폴리곤
SELECT ST_NPoints(ST_GeomFromEWKT('LINESTRING(77.29 29.07 1,77.42 29.26 0,77.27 29.31 -1,77.29 29.07 3)'))
-- 결과
4

Name

ST_NRings — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.

Synopsis

integer ST_NRings(geometry geomA);

설명

도형이 폴리곤 또는 멀티폴리곤인 경우 고리의 개수를 반환합니다. NumInteriorRings 함수와는 달리, 외곽 고리도 개수에 포함시킵니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves

예시

SELECT ST_NRings(the_geom) As Nrings, ST_NumInteriorRings(the_geom) As ninterrings
                                        FROM (SELECT ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))') As the_geom) As foo;
         nrings | ninterrings
--------+-------------
          1 |           0
(1 row)

Name

ST_NumGeometries — 도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.

Synopsis

integer ST_NumGeometries(geometry geom);

설명

도형의 개수를 반환합니다. 도형 집합 또는 멀티 도형인 경우 도형의 개수를, 단일 도형인 경우 1을 반환하고, 도형 집합도 멀티 도형도 단일 도형도 아닌 경우 NULL을 반환합니다.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

변경 사항: 2.0.0 미만 버전에서 도형이 집합이나 멀티 유형이 아닐 경우 NULL을 반환했습니다. 2.0.0 버전부터 폴리곤, 라인스트링, 포인트 같은 단일 도형에 대해 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).

예시

--Prior versions would have returned NULL for this -- in 2.0.0 this returns 1
SELECT ST_NumGeometries(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'));
--result
1

--Geometry Collection Example - multis count as one geom in a collection
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)))'));
--result
3

Name

ST_NumInteriorRings — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.

Synopsis

integer ST_NumInteriorRings(geometry a_polygon);

설명

폴리곤 도형의 내곽 고리의 개수를 반환합니다. 도형이 폴리곤이 아닐 경우 NULL을 반환합니다.

This method implements the SQL/MM specification. SQL-MM 3: 8.2.5

변경 사항: 2.0.0 미만 버전에서는 멀티폴리곤을 입력하면 첫 번째 폴리곤의 내곽 고리의 개수를 반환받을 수 있었습니다.

예시

-- 정규 폴리곤인 경우
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;
                        

Name

ST_NumInteriorRing — 도형 안에 있는 폴리곤의 내곽 고리의 개수를 반환합니다. ST_NumInteriorRings 함수와 동일합니다.

Synopsis

integer ST_NumInteriorRing(geometry a_polygon);


Name

ST_NumPatches — 다면체 표면 상에 있는 면의 개수를 반환합니다. 다면체 도형이 아닌 경우 NULL을 반환할 것입니다.

Synopsis

integer ST_NumPatches(geometry g1);

설명

다면체 표면 상에 있는 면의 개수를 반환합니다. 다면체 도형이 아닌 경우 NULL을 반환할 것입니다. 이 함수는 ST_NumGeometries와 동일하지만 MM 명명법을 지원합니다. MM 규약을 신경 쓰지 않는다면 ST_NumGeometries가 더 빠릅니다.

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 ISO/IEC 13249-3: 8.5

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
                

Name

ST_NumPoints — ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.

Synopsis

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

예시

SELECT ST_NumPoints(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'));
                -- 결과
                4
                

Name

ST_PatchN — ST_Geometry 값의 도형 유형을 반환합니다.

Synopsis

geometry ST_PatchN(geometry geomA, integer n);

설명

도형이 POLYHEDRALSURFACE, POLYHEDRALSURFACEM 인 경우 1-기반 N번째 도형 (면)을 반환합니다. 그 외의 경우 NULL을 반환합니다. 이 함수는 다면체 표면에 대해 ST_GeometryN과 동일한 답을 반환합니다. ST_GeometryN을 이용하는 편이 더 빠릅니다.

[Note]

인덱스는 1-기반입니다.

[Note]

모든 도형들을 추출하고자 한다면 ST_Dump 함수가 더 효율적입니다.

2.0.0 버전부터 사용할 수 있습니다.

This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3: 8.5

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

예시

-- 다면체 표면의 두 번째 면을 추출합니다.
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))

Name

ST_PointN — ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.

Synopsis

geometry ST_PointN(geometry a_linestring, integer n);

설명

도형 안에 있는 단일 라인스트링 또는 원형 라인스트링의 N번째 포인트를 반환합니다. 음수 값은 라인스트링의 종단점으로부터 반대로 집계되므로, -1이 마지막 포인트입니다. 도형 안에 라인스트링이 없는 경우 NULL을 반환합니다.

[Note]

0.8.0 버전부터 인덱스는 OGC 사양을 따라 1-기반입니다. OGC는 반대 방향 인덱스(음수 인덱스)를 지원하지 않습니다. 예전 버전은 대신 0-기반 인덱스를 도입했습니다.

[Note]

멀티라인스트링 안에 있는 각 라인스트링의 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

[Note]

변경 사항: 2.0.0 버전부터 단일 도형 멀티라인스트링을 지원하지 않습니다. PostGIS 예전 버전이라면 단일 라인 멀티라인스트링을 입력받는 경우 시작점을 반환했을 겁니다. 2.0.0 버전은 다른 모든 멀티라인스트링처럼 NULL을 반환할 뿐입니다.

변경 사항: 2.3.0 버전부터 음수 인덱스(-1이 마지막 포인트)를 이용할 수 있습니다.

예시

-- 라인스트링으로부터 모든 포인트를 추출합니다.
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)

-- 원형 라인스트링 예시
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)"


Name

ST_Points — 도형의 모든 좌표들을 담고 있는 멀티포인트를 반환합니다.

Synopsis

geometry ST_Points( geometry geom );

설명

Returns a MultiPoint containing all the coordinates of a geometry. Duplicate points are preserved, including the start and end points of ring geometries. (If desired, duplicate points can be removed by calling ST_RemoveRepeatedPoints on the result).

To obtain information about the position of each coordinate in the parent geometry use ST_NumPoints.

M and Z coordinates are preserved if present.

This method supports Circular Strings and Curves

This function supports 3d and will not drop the z-index.

2.3.0 버전부터 사용할 수 있습니다.

예시

SELECT ST_AsText(ST_Points('POLYGON Z ((30 10 4,10 30 5,40 40 6, 30 10))'));

--result
MULTIPOINT Z ((30 10 4),(10 30 5),(40 40 6),(30 10 4))
                        

Name

ST_StartPoint — Returns the first point of a LineString.

Synopsis

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

[Note]

Enhanced: 3.2.0 returns a point for all geometries. Prior behavior returns NULLs if input was not a LineString.

변경 사항: 2.0.0 버전부터 단일 도형 멀티라인스트링을 지원하지 않습니다. PostGIS 예전 버전이라면 단일 라인 멀티라인스트링을 입력받는 경우 시작점을 반환했을 겁니다. 2.0.0 버전은 다른 모든 멀티라인스트링처럼 NULL을 반환할 뿐입니다. 구식 습성은 문서화되지 않은 기능이지만, 사용자 데이터를 라인스트링으로 저장했다고 가정한 사용자의 경우 현재 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)

Name

ST_Summary — 도형의 내용을 요약한 텍스트를 반환합니다.

Synopsis

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).

1.2.2 버전부터 사용할 수 있습니다.

개선 사항: 2.0.0 버전부터 지리형을 지원하기 시작했습니다.

개선 사항: 2.1.0 버전. 알려진 공간 참조 시스템을 가진 경우를 나타내는 S 플래그가 추가됐습니다.

개선 사항: 2.2.0 버전부터 TIN 및 만곡 도형(curve)을 지원하기 시작했습니다.

예시

=# 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)


Name

ST_X — Returns the X coordinate of a Point.

Synopsis

float ST_X(geometry a_point);

설명

포인트의 X 좌표를 반환합니다. X 좌표가 없는 경우 NULL을 반환합니다. 포인트만 입력받을 수 있습니다.

[Note]

To get the minimum and maximum X value of geometry coordinates use the functions ST_XMin and ST_XMax.

This method implements the SQL/MM specification. SQL-MM 3: 6.1.3

This function supports 3d and will not drop the z-index.

예시

SELECT ST_X(ST_GeomFromEWKT('POINT(1 2 3 4)'));
 st_x
------
        1
(1 row)

SELECT ST_Y(ST_Centroid(ST_GeomFromEWKT('LINESTRING(1 2 3 4, 1 1 1 1)')));
 st_y
------
  1.5
(1 row)

                

Name

ST_Y — Returns the Y coordinate of a Point.

Synopsis

float ST_Y(geometry a_point);

설명

포인트의 Y 좌표를 반환합니다. Y 좌표가 없는 경우 NULL을 반환합니다. 포인트만 입력받을 수 있습니다.

[Note]

To get the minimum and maximum Y value of geometry coordinates use the functions ST_YMin and ST_YMax.

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.

예시

SELECT ST_Y(ST_GeomFromEWKT('POINT(1 2 3 4)'));
 st_y
------
        2
(1 row)

SELECT ST_Y(ST_Centroid(ST_GeomFromEWKT('LINESTRING(1 2 3 4, 1 1 1 1)')));
 st_y
------
  1.5
(1 row)


                

Name

ST_Z — Returns the Z coordinate of a Point.

Synopsis

float ST_Z(geometry a_point);

설명

포인트의 Z 좌표를 반환합니다. Z 좌표가 없는 경우 NULL을 반환합니다. 포인트만 입력받을 수 있습니다.

[Note]

To get the minimum and maximum Z value of geometry coordinates use the functions ST_ZMin and ST_ZMax.

This method implements the SQL/MM specification.

This function supports 3d and will not drop the z-index.

예시

SELECT ST_Z(ST_GeomFromEWKT('POINT(1 2 3 4)'));
 st_z
------
        3
(1 row)

                

Name

ST_Zmflag — ST_Geometry 값의 좌표 차원을 반환합니다.

Synopsis

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

8.5. 도형 편집자(editor)

Abstract

These functions create modified geometries by changing type, structure or vertices.

ST_AddPoint — 라인스트링에 포인트를 추가합니다.
ST_CollectionExtract — Given a geometry collection, returns a multi-geometry containing only elements of a specified type.
ST_CollectionHomogenize — Returns the simplest representation of a geometry collection.
ST_CurveToLine — Converts a geometry containing curves to a linear geometry.
ST_Scroll — Change start point of a closed LineString.
ST_FlipCoordinates — Returns a version of a geometry with X and Y axis flipped.
ST_Force2D — 도형을 "2차원 모드"로 강제합니다.
ST_Force3D — 도형을 XYZ 모드로 강제합니다. ST_Force3DZ라고도 합니다.
ST_Force3DZ — 도형을 XYZ 모드로 강제합니다.
ST_Force3DM — 도형을 XYM 모드로 강제합니다.
ST_Force4D — 도형을 XYZM 모드로 강제합니다.
ST_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.
ST_ForceCollection — 도형을 도형 집합으로 변환합니다.
ST_ForcePolygonCW — Orients all exterior rings clockwise and all interior rings counter-clockwise.
ST_ForceSFS — 도형이 SFS 1.1 도형 유형만을 쓰도록 강제합니다.
ST_ForceRHR — 폴리곤 안에 있는 꼭짓점들의 방향(orientation)이 오른손 법칙(Right-Hand Rule)을 따르도록 강제합니다.
ST_ForceCurve — 적용이 가능한 경우, 도형을 해당 도형의 만곡 유형으로 상위 형변환(upcast)합니다.
ST_LineToCurve — Converts a linear geometry to a curved geometry.
ST_Multi — 도형을 멀티 유형 도형으로 반환합니다.
ST_Normalize — 도형을 해당 도형의 기본형으로 반환합니다.
ST_QuantizeCoordinates — Sets least significant bits of coordinates to zero
ST_RemovePoint — Remove a point from a linestring.
ST_RemoveRepeatedPoints — Returns a version of a geometry with duplicate points removed.
ST_Reverse — 꼭짓점들의 순서가 반대인 도형을 반환합니다.
ST_Segmentize — 주어진 거리보다 더 긴 구간이 없도록 수정된 도형/지리형을 반환합니다.
ST_SetPoint — 라인스트링의 포인트를 주어진 포인트로 대체합니다.
ST_ShiftLongitude — Shifts the longitude coordinates of a geometry between -180..180 and 0..360.
ST_WrapX — X값 근처에서 도형을 래핑합니다.
ST_SnapToGrid — 입력 도형의 모든 포인트를 정규 그리드로 스냅(snap)시킵니다.
ST_Snap — 입력 도형의 분절 구간과 꼭짓점을 참조 도형의 꼭짓점으로 스냅시킵니다.
ST_SwapOrdinates — 입력 도형을 좌표값을 뒤바꾼 상태로 반환합니다.

Name

ST_AddPoint — 라인스트링에 포인트를 추가합니다.

Synopsis

geometry ST_AddPoint(geometry linestring, geometry point);

geometry ST_AddPoint(geometry linestring, geometry point, integer position = -1);

설명

Adds a point to a LineString before the index position (using a 0-based index). If the position parameter is omitted or is -1 the point is appended to the end of the LineString.

1.1.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

Add a point to the end of a 3D line

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)

Guarantee all lines in a table are closed by adding the start point of each line to the end of the line only for those that are not closed.

UPDATE sometable
SET geom = ST_AddPoint(geom, ST_StartPoint(geom))
FROM sometable
WHERE ST_IsClosed(geom) = false;

Name

ST_CollectionExtract — Given a geometry collection, returns a multi-geometry containing only elements of a specified type.

Synopsis

geometry ST_CollectionExtract(geometry collection);

geometry ST_CollectionExtract(geometry collection, integer type);

설명

Given a geometry collection, returns a homogeneous multi-geometry.

If the type is not specified, returns a multi-geometry containing only geometries of the highest dimension. So polygons are preferred over lines, which are preferred over points.

If the type is specified, returns a multi-geometry containing only that type. If there are no sub-geometries of the right type, an EMPTY geometry is returned. Only points, lines and polygons are supported. The type numbers are:

  • 1 == POINT

  • 2 == LINESTRING

  • 3 == POLYGON

For atomic geometry inputs, the geometry is retured unchanged if the input type matches the requested type. Otherwise, the result is an EMPTY geometry of the specified type. If required, these can be converted to multi-geometries using ST_Multi.

[Warning]

MultiPolygon results are not checked for validity. If the polygon components are adjacent or overlapping the result will be invalid. (For example, this can occur when applying this function to an ST_Split result.) This situation can be checked with ST_IsValid and repaired with ST_MakeValid.

1.5.0 버전부터 사용할 수 있습니다.

[Note]

Prior to 1.5.3 this function returned atomic inputs unchanged, no matter type. In 1.5.3 non-matching single geometries returned a NULL result. In 2.0.0 non-matching single geometries return an EMPTY result of the requested type.

예시

Extract highest-dimension type:

SELECT ST_AsText(ST_CollectionExtract(
        'GEOMETRYCOLLECTION( POINT(0 0), LINESTRING(1 1, 2 2) )'));
    st_astext
    ---------------
    MULTILINESTRING((1 1, 2 2))

Extract points (type 1 == POINT):

SELECT ST_AsText(ST_CollectionExtract(
        'GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(POINT(0 0)))',
        1 ));
    st_astext
    ---------------
    MULTIPOINT((0 0))

Extract lines (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))

Name

ST_CollectionHomogenize — Returns the simplest representation of a geometry collection.

Synopsis

geometry ST_CollectionHomogenize(geometry collection);

설명

도형 집합을 입력받아 해당 내용의 "가장 단순한" 표현식을 반환합니다.

  • Homogeneous (uniform) collections are returned as the appropriate multi-geometry.

  • Heterogeneous (mixed) collections are flattened into a single GeometryCollection.

  • Collections containing a single atomic element are returned as that element.

  • Atomic geometries are returned unchanged. If required, these can be converted to a multi-geometry using ST_Multi.

[Warning]

This function does not ensure that the result is valid. In particular, a collection containing adjacent or overlapping Polygons will create an invalid MultiPolygon. This situation can be checked with ST_IsValid and repaired with ST_MakeValid.

2.0.0 버전부터 사용할 수 있습니다.

예시

Single-element collection converted to an atomic geometry

SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0))'));

        st_astext
        ------------
        POINT(0 0)

Nested single-element collection converted to an atomic geometry:

SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(MULTIPOINT((0 0)))'));

        st_astext
        ------------
        POINT(0 0)

Collection converted to a multi-geometry:

SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0),POINT(1 1))'));

        st_astext
        ---------------------
        MULTIPOINT((0 0),(1 1))

Nested heterogeneous collection flattened to a GeometryCollection:

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))

Collection of Polygons converted to an (invalid) MultiPolygon:

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)))

Name

ST_CurveToLine — Converts a geometry containing curves to a linear geometry.

Synopsis

geometry ST_CurveToLine(geometry curveGeom, float tolerance, integer tolerance_type, integer flags);

설명

Converts a CIRCULAR STRING to regular LINESTRING or CURVEPOLYGON to POLYGON or MULTISURFACE to MULTIPOLYGON. Useful for outputting to devices that can't support CIRCULARSTRING geometry types

Converts a given geometry to a linear geometry. Each curved geometry or segment is converted into a linear approximation using the given `tolerance` and options (32 segments per quadrant and no options by default).

The 'tolerance_type' argument determines interpretation of the `tolerance` argument. It can take the following values:

  • 0 (default): Tolerance is max segments per quadrant.

  • 1: Tolerance is max-deviation of line from curve, in source units.

  • 2: Tolerance is max-angle, in radians, between generating radii.

The 'flags' argument is a bitfield. 0 by default. Supported bits are:

  • 1: Symmetric (orientation idependent) output.

  • 2: Retain angle, avoids reducing angles (segment lengths) when producing symmetric output. Has no effect when Symmetric flag is off.

Availability: 1.3.0

Enhanced: 2.4.0 added support for max-deviation and max-angle tolerance, and for symmetric output.

Enhanced: 3.0.0 implemented a minimum number of segments per linearized arc to prevent topological collapse.

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)


        

Name

ST_Scroll — Change start point of a closed LineString.

Synopsis

geometry ST_Scroll(geometry linestring, geometry point);

설명

Changes the start/end point of a closed LineString to the given vertex point.

Availability: 3.2.0

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

예시

Make e closed line start at its 3rd vertex

SELECT ST_AsEWKT(ST_Scroll('SRID=4326;LINESTRING(0 0 0 1, 10 0 2 0, 5 5 4 2,0 0 0 1)', 'POINT(5 5 4 2)'));

st_asewkt
----------
SRID=4326;LINESTRING(5 5 4 2,0 0 0 1,10 0 2 0,5 5 4 2)

Name

ST_FlipCoordinates — Returns a version of a geometry with X and Y axis flipped.

Synopsis

geometry ST_FlipCoordinates(geometry geom);

설명

Returns a version of the given geometry with X and Y axis flipped. Useful for fixing geometries which contain coordinates expressed as latitude/longitude (Y,X).

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).

예시

SELECT ST_AsEWKT(ST_FlipCoordinates(GeomFromEWKT('POINT(1 2)')));
 st_asewkt
------------
POINT(2 1)
         

Name

ST_Force2D — 도형을 "2차원 모드"로 강제합니다.

Synopsis

geometry ST_Force2D(geometry geomA);

설명

도형을 "2차원 모드"로 강제해서 출력 표현식이 X 및 Y 좌표만을 가지도록 합니다. 이 함수는 (OGC가 사양에 2차원 도형만 있기 때문에) OGC 준수 출력물을 강제하는 데 유용합니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

변경 사항: 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))

                

Name

ST_Force3D — 도형을 XYZ 모드로 강제합니다. ST_Force3DZ라고도 합니다.

Synopsis

geometry ST_Force3D(geometry geomA, float Zvalue = 0.0);

설명

Forces the geometries into XYZ mode. This is an alias for ST_Force3DZ. If a geometry has no Z component, then a Zvalue Z coordinate is tacked on.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_3D였습니다.

Changed: 3.1.0. Added support for supplying a non-zero Z value.

This function supports Polyhedral surfaces.

This method supports Circular Strings and Curves

This function supports 3d and will not drop the z-index.

예시

-- 기존 3D 도형은 변경되지 않습니다.
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))
                

Name

ST_Force3DZ — 도형을 XYZ 모드로 강제합니다.

Synopsis

geometry ST_Force3DZ(geometry geomA, float Zvalue = 0.0);

설명

Forces the geometries into XYZ mode. If a geometry has no Z component, then a Zvalue Z coordinate is tacked on.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_3DZ였습니다.

Changed: 3.1.0. Added support for supplying a non-zero Z value.

This function supports Polyhedral surfaces.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves

예시

-- 기존 3D 도형은 변경되지 않습니다.
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))
                

Name

ST_Force3DM — 도형을 XYM 모드로 강제합니다.

Synopsis

geometry ST_Force3DM(geometry geomA, float Mvalue = 0.0);

설명

Forces the geometries into XYM mode. If a geometry has no M component, then a Mvalue M coordinate is tacked on. If it has a Z component, then Z is removed

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_3DM이었습니다.

Changed: 3.1.0. Added support for supplying a non-zero M value.

This method supports Circular Strings and Curves

예시

-- 기존 3D 도형은 변경되지 않습니다.
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))

                

Name

ST_Force4D — 도형을 XYZM 모드로 강제합니다.

Synopsis

geometry ST_Force4D(geometry geomA, float Zvalue = 0.0, float Mvalue = 0.0);

설명

Forces the geometries into XYZM mode. Zvalue and Mvalue is tacked on for missing Z and M dimensions, respectively.

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_4D였습니다.

Changed: 3.1.0. Added support for supplying non-zero Z and M values.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves

예시

-- 기존 3D 도형은 변경되지 않습니다.
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))

                

Name

ST_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.

Synopsis

geometry ST_ForcePolygonCCW ( geometry geom );

설명

Forces (Multi)Polygons to use a counter-clockwise orientation for their exterior ring, and a clockwise orientation for their interior rings. Non-polygonal geometries are returned unchanged.

Availability: 2.4.0

This function supports 3d and will not drop the z-index.

This function supports M coordinates.


Name

ST_ForceCollection — 도형을 도형 집합으로 변환합니다.

Synopsis

geometry ST_ForceCollection(geometry geomA);

설명

도형을 도형 집합으로 변환합니다. 이 함수는 WKB 표현식을 단순화하는 데 유용합니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

1.2.2 버전부터 사용할 수 있습니다. 1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 1.3.4 버전부터 이 버그가 해결됐습니다.

변경 사항: 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))
)
                

Name

ST_ForcePolygonCW — Orients all exterior rings clockwise and all interior rings counter-clockwise.

Synopsis

geometry ST_ForcePolygonCW ( geometry geom );

설명

Forces (Multi)Polygons to use a clockwise orientation for their exterior ring, and a counter-clockwise orientation for their interior rings. Non-polygonal geometries are returned unchanged.

Availability: 2.4.0

This function supports 3d and will not drop the z-index.

This function supports M coordinates.


Name

ST_ForceSFS — 도형이 SFS 1.1 도형 유형만을 쓰도록 강제합니다.

Synopsis

geometry ST_ForceSFS(geometry geomA);

geometry ST_ForceSFS(geometry geomA, text version);

설명

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This method supports Circular Strings and Curves

This function supports 3d and will not drop the z-index.


Name

ST_ForceRHR — 폴리곤 안에 있는 꼭짓점들의 방향(orientation)이 오른손 법칙(Right-Hand Rule)을 따르도록 강제합니다.

Synopsis

geometry ST_ForceRHR(geometry g);

설명

Forces the orientation of the vertices in a polygon to follow a Right-Hand-Rule, in which the area that is bounded by the polygon is to the right of the boundary. In particular, the exterior ring is orientated in a clockwise direction and the interior rings in a counter-clockwise direction. This function is a synonym for ST_ForcePolygonCW

[Note]

The above definition of the Right-Hand-Rule conflicts with definitions used in other contexts. To avoid confusion, it is recommended to use ST_ForcePolygonCW.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

예시

SELECT ST_AsEWKT(
  ST_ForceRHR(
        'POLYGON((0 0 2, 5 0 2, 0 5 2, 0 0 2),(1 1 2, 1 3 2, 3 1 2, 1 1 2))'
  )
);
st_asewkt
--------------------------------------------------------------
 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))
(1 row)

Name

ST_ForceCurve — 적용이 가능한 경우, 도형을 해당 도형의 만곡 유형으로 상위 형변환(upcast)합니다.

Synopsis

geometry ST_ForceCurve(geometry g);

설명

적용이 가능한 경우, 도형을 해당 도형의 만곡 표현식으로 바꿉니다. 라인을 복합 곡선(compoundcurve)으로, 멀티라인을 멀티커브로, 폴리곤을 커브폴리곤으로, 멀티폴리곤을 멀티서페이스(multisurface)로 변환합니다. 입력 폴리곤이 이미 만곡된 표현식인 경우 입력 표현식을 그대로 반환합니다.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves

예시

SELECT ST_AsText(
  ST_ForceCurve(
        'POLYGON((0 0 2, 5 0 2, 0 5 2, 0 0 2),(1 1 2, 1 3 2, 3 1 2, 1 1 2))'::geometry
  )
);
st_astext
----------------------------------------------------------------------
 CURVEPOLYGON Z ((0 0 2,5 0 2,0 5 2,0 0 2),(1 1 2,1 3 2,3 1 2,1 1 2))
(1 row)

Name

ST_LineToCurve — Converts a linear geometry to a curved geometry.

Synopsis

geometry ST_LineToCurve(geometry geomANoncircular);

설명

Converts plain LINESTRING/POLYGON to CIRCULAR STRINGs and Curved Polygons. Note much fewer points are needed to describe the curved equivalent.

[Note]

If the input LINESTRING/POLYGON is not curved enough to clearly represent a curve, the function will return the same input geometry.

Availability: 1.3.0

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves

예시

-- 2D Example
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))

--3D example
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)

Name

ST_Multi — 도형을 멀티 유형 도형으로 반환합니다.

Synopsis

geometry ST_Multi(geometry geom);

설명

Returns the geometry as a MULTI* geometry collection. If the geometry is already a collection, it is returned unchanged.

예시

SELECT ST_AsText(ST_Multi('POLYGON ((10 30, 30 30, 30 10, 10 10, 10 30))'));
                    st_astext
    -------------------------------------------------
    MULTIPOLYGON(((10 30,30 30,30 10,10 10,10 30)))

참고

ST_AsText


Name

ST_Normalize — 도형을 해당 도형의 기본형으로 반환합니다.

Synopsis

geometry ST_Normalize(geometry geom);

설명

도형을 해당 도형의 정규화된/기본 형태로 반환합니다. 폴리곤 고리, 폴리곤 내부 고리에 있는 꼭짓점, 멀티 유형 도형 집합체의 요소를 재정렬할 수도 있습니다.

대부분의 경우, 테스트 작업 목적으로만 쓸모가 있습니다(기대한 결과물과 반환된 결과물의 비교 등).

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_Equals,


Name

ST_QuantizeCoordinates — Sets least significant bits of coordinates to zero

Synopsis

geometry ST_QuantizeCoordinates ( geometry g , int prec_x , int prec_y , int prec_z , int prec_m );

설명

ST_QuantizeCoordinates determines the number of bits (N) required to represent a coordinate value with a specified number of digits after the decimal point, and then sets all but the N most significant bits to zero. The resulting coordinate value will still round to the original value, but will have improved compressiblity. This can result in a significant disk usage reduction provided that the geometry column is using a compressible storage type. The function allows specification of a different number of digits after the decimal point in each dimension; unspecified dimensions are assumed to have the precision of the x dimension. Negative digits are interpreted to refer digits to the left of the decimal point, (i.e., prec_x=-2 will preserve coordinate values to the nearest 100.

The coordinates produced by ST_QuantizeCoordinates are independent of the geometry that contains those coordinates and the relative position of those coordinates within the geometry. As a result, existing topological relationships between geometries are unaffected by use of this function. The function may produce invalid geometry when it is called with a number of digits lower than the intrinsic precision of the geometry.

Availability: 2.5.0

Technical Background

PostGIS stores all coordinate values as double-precision floating point integers, which can reliably represent 15 significant digits. However, PostGIS may be used to manage data that intrinsically has fewer than 15 significant digits. An example is TIGER data, which is provided as geographic coordinates with six digits of precision after the decimal point (thus requiring only nine significant digits of longitude and eight significant digits of latitude.)

When 15 significant digits are available, there are many possible representations of a number with 9 significant digits. A double precision floating point number uses 52 explicit bits to represent the significand (mantissa) of the coordinate. Only 30 bits are needed to represent a mantissa with 9 significant digits, leaving 22 insignificant bits; we can set their value to anything we like and still end up with a number that rounds to our input value. For example, the value 100.123456 can be represented by the floating point numbers closest to 100.123456000000, 100.123456000001, and 100.123456432199. All are equally valid, in that ST_AsText(geom, 6) will return the same result with any of these inputs. As we can set these bits to any value, ST_QuantizeCoordinates sets the 22 insignificant bits to zero. For a long coordinate sequence this creates a pattern of blocks of consecutive zeros that is compressed by PostgreSQL more effeciently.

[Note]

Only the on-disk size of the geometry is potentially affected by ST_QuantizeCoordinates. ST_MemSize, which reports the in-memory usage of the geometry, will return the the same value regardless of the disk space used by a geometry.

예시

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)

Name

ST_RemovePoint — Remove a point from a linestring.

Synopsis

geometry ST_RemovePoint(geometry linestring, integer offset);

설명

Removes a point from a LineString, given its index (0-based). Useful for turning a closed line (ring) into an open linestring.

Enhanced: 3.2.0

1.1.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

Guarantees no lines are closed by removing the end point of closed lines (rings). Assumes geom is of type LINESTRING

UPDATE sometable
        SET geom = ST_RemovePoint(geom, ST_NPoints(geom) - 1)
        FROM sometable
        WHERE ST_IsClosed(geom);

Name

ST_RemoveRepeatedPoints — Returns a version of a geometry with duplicate points removed.

Synopsis

geometry ST_RemoveRepeatedPoints(geometry geom, float8 tolerance);

설명

Returns a version of the given geometry with duplicate consecutive points removed. The function processes only (Multi)LineStrings, (Multi)Polygons and MultiPoints but it can be called with any kind of geometry. Elements of GeometryCollections are processed individually. The endpoints of LineStrings are preserved.

If the tolerance parameter is provided, vertices within the tolerance distance of one another are considered to be duplicates.

Enhanced: 3.2.0

2.2.0 버전부터 사용할 수 있습니다.

This function supports Polyhedral surfaces.

This function supports 3d and will not drop the z-index.

예시

SELECT ST_AsText( ST_RemoveRepeatedPoints( 'MULTIPOINT ((1 1), (2 2), (3 3), (2 2))'));
-------------------------
 MULTIPOINT(1 1,2 2,3 3)
SELECT ST_AsText( ST_RemoveRepeatedPoints( 'LINESTRING (0 0, 0 0, 1 1, 0 0, 1 1, 2 2)'));
---------------------------------
 LINESTRING(0 0,1 1,0 0,1 1,2 2)

Example: Collection elements are processed individually.

SELECT ST_AsText( ST_RemoveRepeatedPoints( 'GEOMETRYCOLLECTION (LINESTRING (1 1, 2 2, 2 2, 3 3), POINT (4 4), POINT (4 4), POINT (5 5))'));
------------------------------------------------------------------------------
 GEOMETRYCOLLECTION(LINESTRING(1 1,2 2,3 3),POINT(4 4),POINT(4 4),POINT(5 5))

Example: Repeated point removal with a distance tolerance.

SELECT ST_AsText( ST_RemoveRepeatedPoints( 'LINESTRING (0 0, 0 0, 1 1, 5 5, 1 1, 2 2)', 2));
-------------------------
 LINESTRING(0 0,5 5,2 2)

Name

ST_Reverse — 꼭짓점들의 순서가 반대인 도형을 반환합니다.

Synopsis

geometry ST_Reverse(geometry g1);

설명

어떤 도형도 입력받을 수 있으며, 꼭짓점들의 순서를 반전시킵니다.

Enhanced: 2.4.0 support for curves was introduced.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

예시

SELECT ST_AsText(geom) as line, ST_AsText(ST_Reverse(geom)) As reverseline
FROM
(SELECT ST_MakeLine(ST_Point(1,2),
                ST_Point(1,10)) As geom) as foo;
--result
                line         |     reverseline
---------------------+----------------------
LINESTRING(1 2,1 10) | LINESTRING(1 10,1 2)

Name

ST_Segmentize — 주어진 거리보다 더 긴 구간이 없도록 수정된 도형/지리형을 반환합니다.

Synopsis

geometry ST_Segmentize(geometry geom, float max_segment_length);

geography ST_Segmentize(geography geog, float max_segment_length);

설명

주어진 max_segment_length보다 긴 구간이 없도록 수정된 도형을 반환합니다. 거리 계산은 2D로만 수행됩니다. 도형의 경우, 길이 단위는 공간 참조의 단위입니다. 지리형의 경우, 미터 단위를 씁니다.

1.2.2 버전부터 사용할 수 있습니다.

Enhanced: 3.0.0 Segmentize geometry now uses equal length segments

Enhanced: 2.3.0 Segmentize geography now uses equal length segments

개선 사항: 2.1.0 버전부터 지리형을 지원하기 시작했습니다.

변경 사항: 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);를 통해 도형/지리형 같은 객체의 유형을 적절히 지정해야 합니다.

[Note]

이 함수는 분절 구간(segment)의 개수를 늘리기만 할 뿐입니다. 최대 길이보다 짧은 분절 구간의 길이가 늘어나지는 않습니다.

예시

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)

                        

Name

ST_SetPoint — 라인스트링의 포인트를 주어진 포인트로 대체합니다.

Synopsis

geometry ST_SetPoint(geometry linestring, integer zerobasedposition, geometry point);

설명

라인스트링의 N번째 포인트를 주어진 포인트로 대체합니다. 인덱스는 0-기반입니다. 음수 인덱스는 반대로 세기 때문에, -1이 마지막 포인트가 됩니다. 꼭짓점 하나가 움직였을 때 연결 관계를 유지하려는 경우 이 함수가 트리거 역할로 특히 유용합니다.

1.1.0 버전부터 사용할 수 있습니다.

업데이트 사항: 2.3.0 버전에서 음수 인덱스를 지원하기 시작했습니다.

This function supports 3d and will not drop the z-index.

예시

--Change first point in line string from -1 3 to -1 1
SELECT ST_AsText(ST_SetPoint('LINESTRING(-1 2,-1 3)', 0, 'POINT(-1 1)'));
           st_astext
-----------------------
 LINESTRING(-1 1,-1 3)

---Change last point in a line string (lets play with 3d linestring this time)
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)

                        

Name

ST_ShiftLongitude — Shifts the longitude coordinates of a geometry between -180..180 and 0..360.

Synopsis

geometry ST_ShiftLongitude(geometry geom);

설명

Reads every point/vertex in a geometry, and shifts its longitude coordinate from -180..0 to 180..360 and vice versa if between these ranges. This function is symmetrical so the result is a 0..360 representation of a -180..180 data and a -180..180 representation of a 0..360 data.

[Note]

This is only useful for data with coordinates in longitude/latitude; e.g. SRID 4326 (WGS 84 geographic)

[Warning]

1.3.4 미만 버전에서는 버그 때문에 멀티포인트를 입력받지 못 했습니다. 1.3.4 버전부터 멀티포인트도 입력할 수 있습니다.

This function supports 3d and will not drop the z-index.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다.

주의: 2.2.0 미만 버전에서, 이 함수의 명칭은 "ST_Shift_Longitude"였습니다.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

--single point forward transformation
SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;POINT(270 0)'::geometry))

st_astext
----------
POINT(-90 0)


--single point reverse transformation
SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;POINT(-90 0)'::geometry))

st_astext
----------
POINT(270 0)


--for linestrings the functions affects only to the sufficient coordinates
SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;LINESTRING(174 12, 182 13)'::geometry))

st_astext
----------
LINESTRING(174 12,-178 13)
        

참고

ST_WrapX


Name

ST_WrapX — X값 근처에서 도형을 래핑합니다.

Synopsis

geometry ST_WrapX(geometry geom, float8 wrap, float8 move);

설명

This function splits the input geometries and then moves every resulting component falling on the right (for negative 'move') or on the left (for positive 'move') of given 'wrap' line in the direction specified by the 'move' parameter, finally re-unioning the pieces together.

[Note]

이 함수는 경위도 입력물이 한 편에서 다른 편으로 걸쳐 있지 않은 관심 피처를 갖도록 하는 데 유용합니다.

Availability: 2.3.0 requires GEOS

This function supports 3d and will not drop the z-index.

예시

-- Move all components of the given geometries whose bounding box
-- falls completely on the left of x=0 to +360
select ST_WrapX(geom, 0, 360);

-- Move all components of the given geometries whose bounding box
-- falls completely on the left of x=-30 to +360
select ST_WrapX(geom, -30, 360);
        

Name

ST_SnapToGrid — 입력 도형의 모든 포인트를 정규 그리드로 스냅(snap)시킵니다.

Synopsis

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: 입력 도형의 모든 포인트를 원점과 셀(cell) 크기로 정의된 그리드로 스냅(snap)시킵니다. 동일한 셀에 떨어지는 연속된 포인트들을 제거하며, 출력 포인트들이 주어진 유형의 도형을 정의하기에 부족할 경우 결국 NULL을 반환합니다. 도형 집합 안에서 이렇게 붕괴된 도형은 집합에서 제외됩니다. 정확도를 낮추는 데 유용합니다.

변종 4: 1.1.0 버전에서 추가되었습니다. 입력 도형의 모든 포인트를 원점(두 번째 인수, 포인트여야 합니다) 및 셀 크기로 정의된 그리드로 스냅시킵니다. 사용자가 그리드로 스냅시키고 싶지 않은 차원의 경우, 셀 크기를 0으로 설정하십시오.

[Note]

반환되는 도형이 단순성을 잃을 수도 있습니다(ST_IsSimple 참조).

[Note]

1.1.0 버전 배포 전에는 이 함수가 항상 2차원 도형을 반환했습니다. 1.1.0 버전부터 반환되는 도형이, 더 높은 차원값은 건드리지 않은 채, 입력 도형과 동일한 차원수를 가지게 됐습니다. 모든 그리드 차원을 정의하려면 두 번째 도형 인자를 입력받는 버전을 이용하십시오.

1.0.0RC1 버전부터 사용할 수 있습니다.

1.1.0 버전부터 Z 및 M을 지원합니다.

This function supports 3d and will not drop the z-index.

예시

--Snap your geometries to a precision grid of 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)
 --Snap a 4d geometry
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)


--With a 4d geometry - the ST_SnapToGrid(geom,size) only touches x and y coords but keeps m and z the same
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)

                

Name

ST_Snap — 입력 도형의 분절 구간과 꼭짓점을 참조 도형의 꼭짓점으로 스냅시킵니다.

Synopsis

geometry ST_Snap(geometry input, geometry reference, float tolerance);

설명

Snaps the vertices and segments of a geometry to another Geometry's vertices. A snap distance tolerance is used to control where snapping is performed. The result geometry is the input geometry with the vertices snapped. If no snapping occurs then the input geometry is returned unchanged.

한 도형을 또다른 도형으로 스냅시키면, (노드 및 교차점 계산 과정에서 문제를 일으킬 수 있는) 거의 일치하는 경계선을 제거함으로써 오버레이 연산을 강력하게 향상시킬 수 있습니다.

스냅을 너무 많이 하면 유효하지 않은 지형을 생성하는 결과를 가져올 수 있기 때문에, 경험식(heuristics)을 통해 어떤 경우 안전하게 스냅시킬 수 있는지 알아내서 스냅시킬 꼭짓점의 개수 및 위치를 결정합니다. 하지만 이런 방식은 몇몇 가능할 수도 있는 스냅 작업을 제외하게 될 수도 있습니다.

[Note]

반환되는 도형이 단순성(ST_IsSimple 참조) 및 유효성(ST_IsValid 참조)을 잃을 수도 있습니다.

GEOS 모듈로 실행

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)
                                

Name

ST_SwapOrdinates — 입력 도형을 좌표값을 뒤바꾼 상태로 반환합니다.

Synopsis

geometry ST_SwapOrdinates(geometry geom, cstring ords);

설명

입력 도형을 좌표값을 뒤바꾼 상태로 반환합니다.

ords 파라미터는 뒤바꿀 좌표를 명명하는 문자 2개 길이의 스트링입니다. 유효한 명칭은 x, y, z, 그리고 m입니다.

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).

예시

-- M값을 2배로 만듭니다.
SELECT ST_AsText(
  ST_SwapOrdinates(
    ST_Scale(
      ST_SwapOrdinates(g,'xm'),
      2, 1
    ),
  'xm')
) FROM ( SELECT 'POINT ZM (0 0 0 2)'::geometry g ) foo;
     st_astext
--------------------
 POINT ZM (0 0 0 4)
                 

8.6. Geometry Validation

Abstract

These functions test whether geometries are valid according to the OGC SFS standard. They also provide information about the nature and location of invalidity. There is also a function to create a valid geometry out of an invalid one.

ST_IsValid — Tests if a geometry is well-formed in 2D.
ST_IsValidDetail — Returns a valid_detail row stating if a geometry is valid or if not a reason and a location.
ST_IsValidReason — Returns text stating if a geometry is valid, or a reason for invalidity.
ST_MakeValid — Attempts to make an invalid geometry valid without losing vertices.

Name

ST_IsValid — Tests if a geometry is well-formed in 2D.

Synopsis

boolean ST_IsValid(geometry g);

boolean ST_IsValid(geometry g, integer flags);

Description

Tests if an ST_Geometry value is well-formed and valid in 2D according to the OGC rules. For geometries with 3 and 4 dimensions, the validity is still only tested in 2 dimensions. For geometries that are invalid, a PostgreSQL NOTICE is emitted providing details of why it is not valid.

For the version with the flags parameter, supported values are documented in ST_IsValidDetail This version does not print a NOTICE explaining invalidity.

For more information on the definition of geometry validity, refer to Section 4.4, “Geometry Validation”

[Note]

SQL-MM defines the result of ST_IsValid(NULL) to be 0, while PostGIS returns NULL.

Performed by the GEOS module.

The version accepting flags is available starting with 2.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: 5.1.9

[Note]

Neither OGC-SFS nor SQL-MM specifications include a flag argument for ST_IsValid. The flag is a PostGIS extension.

Examples

SELECT ST_IsValid(ST_GeomFromText('LINESTRING(0 0, 1 1)')) As good_line,
        ST_IsValid(ST_GeomFromText('POLYGON((0 0, 1 1, 1 2, 1 1, 0 0))')) As bad_poly
--results
NOTICE:  Self-intersection at or near point 0 0
 good_line | bad_poly
-----------+----------
 t         | f

Name

ST_IsValidDetail — Returns a valid_detail row stating if a geometry is valid or if not a reason and a location.

Synopsis

valid_detail ST_IsValidDetail(geometry geom, integer flags);

Description

Returns a valid_detail row, containing a boolean (valid) stating if a geometry is valid, a varchar (reason) stating a reason why it is invalid and a geometry (location) pointing out where it is invalid.

Useful to improve on the combination of ST_IsValid and ST_IsValidReason to generate a detailed report of invalid geometries.

The optional flags parameter is a bitfield. It can have the following values:

  • 0: Use usual OGC SFS validity semantics.

  • 1: Consider certain kinds of self-touching rings (inverted shells and exverted holes) as valid. This is also known as "the ESRI flag", since this is the validity model used by those tools. Note that this is invalid under the OGC model.

Performed by the GEOS module.

Availability: 2.0.0

Examples

--First 3 Rejects from a successful quintuplet experiment
SELECT gid, reason(ST_IsValidDetail(geom)), ST_AsText(location(ST_IsValidDetail(geom))) as location
FROM
(SELECT ST_MakePolygon(ST_ExteriorRing(e.buff), array_agg(f.line)) As geom, gid
FROM (SELECT ST_Buffer(ST_Point(x1*10,y1), z1) As buff, x1*10 + y1*100 + z1*1000 As gid
        FROM generate_series(-4,6) x1
        CROSS JOIN generate_series(2,5) y1
        CROSS JOIN generate_series(1,8) z1
        WHERE x1 > y1*0.5 AND z1 < x1*y1) As e
        INNER JOIN (SELECT ST_Translate(ST_ExteriorRing(ST_Buffer(ST_Point(x1*10,y1), z1)),y1*1, z1*2) As line
        FROM generate_series(-3,6) x1
        CROSS JOIN generate_series(2,5) y1
        CROSS JOIN generate_series(1,10) z1
        WHERE x1 > y1*0.75 AND z1 < x1*y1) As f
ON (ST_Area(e.buff) > 78 AND ST_Contains(e.buff, f.line))
GROUP BY gid, e.buff) As quintuplet_experiment
WHERE ST_IsValid(geom) = false
ORDER BY gid
LIMIT 3;

 gid  |      reason       |  location
------+-------------------+-------------
 5330 | Self-intersection | POINT(32 5)
 5340 | Self-intersection | POINT(42 5)
 5350 | Self-intersection | POINT(52 5)

 --simple example
SELECT * FROM ST_IsValidDetail('LINESTRING(220227 150406,2220227 150407,222020 150410)');

 valid | reason | location
-------+--------+----------
 t     |        |

                

Name

ST_IsValidReason — Returns text stating if a geometry is valid, or a reason for invalidity.

Synopsis

text ST_IsValidReason(geometry geomA);

text ST_IsValidReason(geometry geomA, integer flags);

Description

Returns text stating if a geometry is valid, or if invalid a reason why.

Useful in combination with ST_IsValid to generate a detailed report of invalid geometries and reasons.

Allowed flags are documented in ST_IsValidDetail.

Performed by the GEOS module.

Availability: 1.4

Availability: 2.0 version taking flags.

Examples

-- invalid bow-tie polygon
SELECT ST_IsValidReason(
    'POLYGON ((100 200, 100 100, 200 200,
     200 100, 100 200))'::geometry) as validity_info;
validity_info
--------------------------
Self-intersection[150 150]
        
--First 3 Rejects from a successful quintuplet experiment
SELECT gid, ST_IsValidReason(geom) as validity_info
FROM
(SELECT ST_MakePolygon(ST_ExteriorRing(e.buff), array_agg(f.line)) As geom, gid
FROM (SELECT ST_Buffer(ST_Point(x1*10,y1), z1) As buff, x1*10 + y1*100 + z1*1000 As gid
        FROM generate_series(-4,6) x1
        CROSS JOIN generate_series(2,5) y1
        CROSS JOIN generate_series(1,8) z1
        WHERE x1 > y1*0.5 AND z1 < x1*y1) As e
        INNER JOIN (SELECT ST_Translate(ST_ExteriorRing(ST_Buffer(ST_Point(x1*10,y1), z1)),y1*1, z1*2) As line
        FROM generate_series(-3,6) x1
        CROSS JOIN generate_series(2,5) y1
        CROSS JOIN generate_series(1,10) z1
        WHERE x1 > y1*0.75 AND z1 < x1*y1) As f
ON (ST_Area(e.buff) > 78 AND ST_Contains(e.buff, f.line))
GROUP BY gid, e.buff) As quintuplet_experiment
WHERE ST_IsValid(geom) = false
ORDER BY gid
LIMIT 3;

 gid  |      validity_info
------+--------------------------
 5330 | Self-intersection [32 5]
 5340 | Self-intersection [42 5]
 5350 | Self-intersection [52 5]

 --simple example
SELECT ST_IsValidReason('LINESTRING(220227 150406,2220227 150407,222020 150410)');

 st_isvalidreason
------------------
 Valid Geometry

                

Name

ST_MakeValid — Attempts to make an invalid geometry valid without losing vertices.

Synopsis

geometry ST_MakeValid(geometry input);

geometry ST_MakeValid(geometry input, text params);

Description

The function attempts to create a valid representation of a given invalid geometry without losing any of the input vertices. Valid geometries are returned unchanged.

Supported inputs are: POINTS, MULTIPOINTS, LINESTRINGS, MULTILINESTRINGS, POLYGONS, MULTIPOLYGONS and GEOMETRYCOLLECTIONS containing any mix of them.

In case of full or partial dimensional collapses, the output geometry may be a collection of lower-to-equal dimension geometries, or a geometry of lower dimension.

Single polygons may become multi-geometries in case of self-intersections.

The params argument can be used to supply an options string to select the method to use for building valid geometry. The options string is in the format "method=linework|structure keepcollapsed=true|false".

The "method" key has two values.

  • "linework" is the original algorithm, and builds valid geometries by first extracting all lines, noding that linework together, then building a value output from the linework.

  • "structure" is an algorithm that distinguishes between interior and exterior rings, building new geometry by unioning exterior rings, and then differencing all interior rings.

The "keepcollapsed" key is only valid for the "structure" algorithm, and takes a value of "true" or "false". When set to "false", geometry components that collapse to a lower dimensionality, for example a one-point linestring would be dropped.

Performed by the GEOS module.

Availability: 2.0.0

Enhanced: 2.0.1, speed improvements

Enhanced: 2.1.0, added support for GEOMETRYCOLLECTION and MULTIPOINT.

Enhanced: 3.1.0, added removal of Coordinates with NaN values.

Enhanced: 3.2.0, added algorithm options, 'linework' and 'structure' which requires GEOS >= 3.10.0.

This function supports 3d and will not drop the z-index.

Examples

before_geom: MULTIPOLYGON of 2 overlapping polygons

after_geom: MULTIPOLYGON of 4 non-overlapping polygons

after_geom_structure: MULTIPOLYGON of 1 non-overlapping polygon

SELECT f.geom AS before_geom, ST_MakeValid(f.geom) AS after_geom, ST_MakeValid(f.geom, 'method=structure') AS after_geom_structure
FROM (SELECT 'MULTIPOLYGON(((186 194,187 194,188 195,189 195,190 195,
191 195,192 195,193 194,194 194,194 193,195 192,195 191,
195 190,195 189,195 188,194 187,194 186,14 6,13 6,12 5,11 5,
10 5,9 5,8 5,7 6,6 6,6 7,5 8,5 9,5 10,5 11,5 12,6 13,6 14,186 194)),
((150 90,149 80,146 71,142 62,135 55,128 48,119 44,110 41,100 40,
90 41,81 44,72 48,65 55,58 62,54 71,51 80,50 90,51 100,
54 109,58 118,65 125,72 132,81 136,90 139,100 140,110 139,
119 136,128 132,135 125,142 118,146 109,149 100,150 90)))'::geometry AS geom) AS f;

before_geom: MULTIPOLYGON of 6 overlapping polygons

after_geom: MULTIPOLYGON of 14 Non-overlapping polygons

after_geom_structure: MULTIPOLYGON of 1 Non-overlapping polygon

SELECT c.geom AS before_geom,
                    ST_MakeValid(c.geom) AS after_geom,
                    ST_MakeValid(c.geom, 'method=structure') AS after_geom_structure
        FROM (SELECT 'MULTIPOLYGON(((91 50,79 22,51 10,23 22,11 50,23 78,51 90,79 78,91 50)),
                  ((91 100,79 72,51 60,23 72,11 100,23 128,51 140,79 128,91 100)),
                  ((91 150,79 122,51 110,23 122,11 150,23 178,51 190,79 178,91 150)),
                  ((141 50,129 22,101 10,73 22,61 50,73 78,101 90,129 78,141 50)),
                  ((141 100,129 72,101 60,73 72,61 100,73 128,101 140,129 128,141 100)),
                  ((141 150,129 122,101 110,73 122,61 150,73 178,101 190,129 178,141 150)))'::geometry AS geom) AS c;

Examples

SELECT ST_AsText(ST_MakeValid(
    'LINESTRING(0 0, 0 0)',
    'method=structure keepcollapsed=true'
    ));

 st_astext
------------
 POINT(0 0)


SELECT ST_AsText(ST_MakeValid(
    'LINESTRING(0 0, 0 0)',
    'method=structure keepcollapsed=false'
    ));

    st_astext
------------------
 LINESTRING EMPTY

8.7. Spatial Reference System Functions

Abstract

These functions work with the Spatial Reference System of geometries as defined in the spatial_ref_sys table.

ST_SetSRID — Set the SRID on a geometry.
ST_SRID — Returns the spatial reference identifier for a geometry.
ST_Transform — Return a new geometry with coordinates transformed to a different spatial reference system.

Name

ST_SetSRID — Set the SRID on a geometry.

Synopsis

geometry ST_SetSRID(geometry geom, integer srid);

Description

Sets the SRID on a geometry to a particular integer value. Useful in constructing bounding boxes for queries.

[Note]

This function does not transform the geometry coordinates in any way - it simply sets the meta data defining the spatial reference system the geometry is assumed to be in. Use ST_Transform if you want to transform the geometry into a new projection.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method supports Circular Strings and Curves

Examples

-- Mark a point as WGS 84 long lat --

SELECT ST_SetSRID(ST_Point(-123.365556, 48.428611),4326) As wgs84long_lat;
-- the ewkt representation (wrap with ST_AsEWKT) -
SRID=4326;POINT(-123.365556 48.428611)
                        

-- Mark a point as WGS 84 long lat and then transform to web mercator (Spherical Mercator) --

SELECT ST_Transform(ST_SetSRID(ST_Point(-123.365556, 48.428611),4326),3785) As spere_merc;
-- the ewkt representation (wrap with ST_AsEWKT) -
SRID=3785;POINT(-13732990.8753491 6178458.96425423)
                        

Name

ST_SRID — Returns the spatial reference identifier for a geometry.

Synopsis

integer ST_SRID(geometry g1);

Description

Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. Section 4.5, “SPATIAL_REF_SYS 테이블과 공간 참조 시스템”

[Note]

spatial_ref_sys table is a table that catalogs all spatial reference systems known to PostGIS and is used for transformations from one spatial reference system to another. So verifying you have the right spatial reference system identifier is important if you plan to ever transform your geometries.

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.5

This method supports Circular Strings and Curves

Examples

SELECT ST_SRID(ST_GeomFromText('POINT(-71.1043 42.315)',4326));
                --result
                4326
                

Name

ST_Transform — Return a new geometry with coordinates transformed to a different spatial reference system.

Synopsis

geometry ST_Transform(geometry g1, integer srid);

geometry ST_Transform(geometry geom, text to_proj);

geometry ST_Transform(geometry geom, text from_proj, text to_proj);

geometry ST_Transform(geometry geom, text from_proj, integer to_srid);

Description

Returns a new geometry with its coordinates transformed to a different spatial reference system. The destination spatial reference to_srid may be identified by a valid SRID integer parameter (i.e. it must exist in the spatial_ref_sys table). Alternatively, a spatial reference defined as a PROJ.4 string can be used for to_proj and/or from_proj, however these methods are not optimized. If the destination spatial reference system is expressed with a PROJ.4 string instead of an SRID, the SRID of the output geometry will be set to zero. With the exception of functions with from_proj, input geometries must have a defined SRID.

ST_Transform is often confused with ST_SetSRID. ST_Transform actually changes the coordinates of a geometry from one spatial reference system to another, while ST_SetSRID() simply changes the SRID identifier of the geometry.

[Note]

Requires PostGIS be compiled with PROJ support. Use PostGIS_Full_Version to confirm you have PROJ support compiled in.

[Note]

If using more than one transformation, it is useful to have a functional index on the commonly used transformations to take advantage of index usage.

[Note]

Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+

Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.

Enhanced: 2.3.0 support for direct PROJ.4 text was introduced.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.6

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Examples

Change Massachusetts state plane US feet geometry to WGS 84 long lat

SELECT ST_AsText(ST_Transform(ST_GeomFromText('POLYGON((743238 2967416,743238 2967450,
        743265 2967450,743265.625 2967416,743238 2967416))',2249),4326)) As wgs_geom;

 wgs_geom
---------------------------
 POLYGON((-71.1776848522251 42.3902896512902,-71.1776843766326 42.3903829478009,
-71.1775844305465 42.3903826677917,-71.1775825927231 42.3902893647987,-71.177684
8522251 42.3902896512902));
(1 row)

--3D Circular String example
SELECT ST_AsEWKT(ST_Transform(ST_GeomFromEWKT('SRID=2249;CIRCULARSTRING(743238 2967416 1,743238 2967450 2,743265 2967450 3,743265.625 2967416 3,743238 2967416 4)'),4326));

                                 st_asewkt
--------------------------------------------------------------------------------------
 SRID=4326;CIRCULARSTRING(-71.1776848522251 42.3902896512902 1,-71.1776843766326 42.3903829478009 2,
 -71.1775844305465 42.3903826677917 3,
 -71.1775825927231 42.3902893647987 3,-71.1776848522251 42.3902896512902 4)

                

Example of creating a partial functional index. For tables where you are not sure all the geometries will be filled in, its best to use a partial index that leaves out null geometries which will both conserve space and make your index smaller and more efficient.

CREATE INDEX idx_geom_26986_parcels
  ON parcels
  USING gist
  (ST_Transform(geom, 26986))
  WHERE geom IS NOT NULL;
                

Examples of using PROJ.4 text to transform with custom spatial references.

-- Find intersection of two polygons near the North pole, using a custom Gnomic projection
-- See http://boundlessgeo.com/2012/02/flattening-the-peel/
 WITH data AS (
   SELECT
     ST_GeomFromText('POLYGON((170 50,170 72,-130 72,-130 50,170 50))', 4326) AS p1,
     ST_GeomFromText('POLYGON((-170 68,-170 90,-141 90,-141 68,-170 68))', 4326) AS p2,
     '+proj=gnom +ellps=WGS84 +lat_0=70 +lon_0=-160 +no_defs'::text AS gnom
 )
 SELECT ST_AsText(
   ST_Transform(
     ST_Intersection(ST_Transform(p1, gnom), ST_Transform(p2, gnom)),
   gnom, 4326))
 FROM data;
                                          st_astext
 --------------------------------------------------------------------------------
  POLYGON((-170 74.053793645338,-141 73.4268621378904,-141 68,-170 68,-170 74.053793645338))
                

Configuring transformation behavior

Sometimes coordinate transformation involving a grid-shift can fail, for example if PROJ.4 has not been built with grid-shift files or the coordinate does not lie within the range for which the grid shift is defined. By default, PostGIS will throw an error if a grid shift file is not present, but this behavior can be configured on a per-SRID basis either by testing different to_proj values of PROJ.4 text, or altering the proj4text value within the spatial_ref_sys table.

For example, the proj4text parameter +datum=NAD87 is a shorthand form for the following +nadgrids parameter:

+nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat

The @ prefix means no error is reported if the files are not present, but if the end of the list is reached with no file having been appropriate (ie. found and overlapping) then an error is issued.

If, conversely, you wanted to ensure that at least the standard files were present, but that if all files were scanned without a hit a null transformation is applied you could use:

+nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat,null

The null grid shift file is a valid grid shift file covering the whole world and applying no shift. So for a complete example, if you wanted to alter PostGIS so that transformations to SRID 4267 that didn't lie within the correct range did not throw an ERROR, you would use the following:

UPDATE spatial_ref_sys SET proj4text = '+proj=longlat +ellps=clrk66 +nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat,null +no_defs' WHERE srid = 4267;

8.8. Geometry Input

Abstract

These functions create geometry objects from various textual or binary formats.

8.8.1. Well-Known Text (WKT)

ST_BdPolyFromText — 멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 폴리곤을 작성합니다.
ST_BdMPolyFromText — 멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 멀티폴리곤을 작성합니다.
ST_GeogFromText — WKT (확장) 표현식으로부터 지정된 지리형 값을 반환합니다.
ST_GeographyFromText — WKT (확장) 표현식으로부터 지정된 지리형 값을 반환합니다.
ST_GeomCollFromText — Makes a collection Geometry from collection WKT with the given SRID. If SRID is not given, it defaults to 0.
ST_GeomFromEWKT — EWKT(Extended Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다.
ST_GeomFromMARC21 — Takes MARC21/XML geographic data as input and returns a PostGIS geometry object.
ST_GeometryFromText — WKT(Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다. 이 함수는 ST_GeomFromText 함수와 동일합니다.
ST_GeomFromText — WKT 표현식으로부터 지정된 ST_Geometry 값을 반환합니다.
ST_LineFromText — 주어진 SRID와 함께 WKT 표현식으로부터 도형을 만듭니다. SRID가 주어지지 않은 경우, 기본값인 0을 씁니다.
ST_MLineFromText — WKT 표현식으로부터 지정된 ST_MultiLineString 값을 반환합니다.
ST_MPointFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
ST_MPolyFromText — Makes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
ST_PointFromText — 주어진 SRID와 함께 WKT 표현식으로부터 포인트 도형을 만듭니다. SRID가 주어지지 않은 경우, 기본값인 0을 씁니다.
ST_PolygonFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
ST_WKTToSQL — WKT(Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다. 이 함수는 ST_GeomFromText 함수와 동일합니다.

Name

ST_BdPolyFromText — 멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 폴리곤을 작성합니다.

Synopsis

geometry ST_BdPolyFromText(text WKT, integer srid);

설명

멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 폴리곤을 작성합니다.

[Note]

WKT가 멀티라인스트링이 아닐 경우 오류가 발생합니다. 출력물이 멀티폴리곤일 경우 오류가 발생하는데 이런 경우 ST_BdMPolyFromText를 사용하거나, 또는 PostGIS 특화 접근법을 사용하려면 ST_BuildArea()를 참조하십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

GEOS 모듈로 실행

1.1.0 버전부터 사용할 수 있습니다.


Name

ST_BdMPolyFromText — 멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 멀티폴리곤을 작성합니다.

Synopsis

geometry ST_BdMPolyFromText(text WKT, integer srid);

설명

멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 멀티폴리곤을 작성합니다.

[Note]

WKT가 멀티라인스트링이 아닐 경우 오류가 발생합니다. 출력물이 단일 폴리곤으로 이루어졌을 경우에도 멀티폴리곤으로 강제합니다. 해당 연산시 단일 폴리곤을 출력할 것이라고 확신한다면 ST_BdPolyFromText 를 사용하거나, 또는 PostGIS 특화 접근법을 사용하려 할 경우 ST_BuildArea() 를 참조하십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

GEOS 모듈로 실행

1.1.0 버전부터 사용할 수 있습니다.


Name

ST_GeogFromText — WKT (확장) 표현식으로부터 지정된 지리형 값을 반환합니다.

Synopsis

geography ST_GeogFromText(text EWKT);

설명

WKT 표현식 또는 확장 WKT 표현식으로부터 지리형 객체를 반환합니다. 투영체를 따로 설정하지 않은 경우 SRID 4326으로 가정합니다. 이 함수는 ST_GeographyFromText와 동일합니다. 포인트는 항상 경위도 형식으로 표현됩니다.

예시

--- 경위도 좌표를 지리형으로 변환하기
ALTER TABLE sometable ADD COLUMN geog geography(POINT,4326);
UPDATE sometable SET geog = ST_GeogFromText('SRID=4326;POINT(' || lon || ' ' || lat || ')');

--- EPSG:4267, NAD27을 이용해서 지리형 포인트를 지정하기
SELECT ST_AsEWKT(ST_GeogFromText('SRID=4267;POINT(-77.0092 38.889588)'));
                        

Name

ST_GeographyFromText — WKT (확장) 표현식으로부터 지정된 지리형 값을 반환합니다.

Synopsis

geography ST_GeographyFromText(text EWKT);

설명

WKT 표현식으로부터 지리형 객체를 반환합니다. 투영체를 따로 설정하지 않은 경우 SRID 4326으로 가정합니다.


Name

ST_GeomCollFromText — Makes a collection Geometry from collection WKT with the given SRID. If SRID is not given, it defaults to 0.

Synopsis

geometry ST_GeomCollFromText(text WKT, integer srid);

geometry ST_GeomCollFromText(text WKT);

설명

Makes a collection Geometry from the Well-Known-Text (WKT) representation with the given SRID. If SRID is not given, it defaults to 0.

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

WKT가 도형 집합(GEOMETRYCOLLECTION)이 아닌 경우 null을 반환합니다.

[Note]

사용자 WKT 도형이 모두 집합이라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification.

예시

SELECT ST_GeomCollFromText('GEOMETRYCOLLECTION(POINT(1 2),LINESTRING(1 2, 3 4))');

관련 정보

ST_GeomFromText, ST_SRID


Name

ST_GeomFromEWKT — EWKT(Extended Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다.

Synopsis

geometry ST_GeomFromEWKT(text EWKT);

설명

OGC EWKT(Extended Well-Known Text) 표현식으로부터 PostGIS ST_Geometry 객체를 작성합니다.

[Note]

EWKT 형식이 OGC 표준은 아니지만, SRID(공간 참조 시스템 식별자)를 포함하는 PostGIS 특화 형식입니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 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_GeomFromEWKT('SRID=4269;LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)');
SELECT ST_GeomFromEWKT('SRID=4269;MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))');

SELECT ST_GeomFromEWKT('SRID=4269;POINT(-71.064544 42.28787)');

SELECT ST_GeomFromEWKT('SRID=4269;POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239,
-71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))');

SELECT ST_GeomFromEWKT('SRID=4269;MULTIPOLYGON(((-71.1031880899493 42.3152774590236,
-71.1031627617667 42.3152960829043,-71.102923838298 42.3149156848307,
-71.1023097974109 42.3151969047397,-71.1019285062273 42.3147384934248,
-71.102505233663 42.3144722937587,-71.10277487471 42.3141658254797,
-71.103113945163 42.3142739188902,-71.10324876416 42.31402489987,
-71.1033002961013 42.3140393340215,-71.1033488797549 42.3139495090772,
-71.103396240451 42.3138632439557,-71.1041521907712 42.3141153348029,
-71.1041411411543 42.3141545014533,-71.1041287795912 42.3142114839058,
-71.1041188134329 42.3142693656241,-71.1041112482575 42.3143272556118,
-71.1041072845732 42.3143851580048,-71.1041057218871 42.3144430686681,
-71.1041065602059 42.3145009876017,-71.1041097995362 42.3145589148055,
-71.1041166403905 42.3146168544148,-71.1041258822717 42.3146748022936,
-71.1041375307579 42.3147318674446,-71.1041492906949 42.3147711126569,
-71.1041598612795 42.314808571739,-71.1042515013869 42.3151287620809,
-71.1041173835118 42.3150739481917,-71.1040809891419 42.3151344119048,
-71.1040438678912 42.3151191367447,-71.1040194562988 42.3151832057859,
-71.1038734225584 42.3151140942995,-71.1038446938243 42.3151006300338,
-71.1038315271889 42.315094347535,-71.1037393329282 42.315054824985,
-71.1035447555574 42.3152608696313,-71.1033436658644 42.3151648370544,
-71.1032580383161 42.3152269126061,-71.103223066939 42.3152517403219,
-71.1031880899493 42.3152774590236)),
((-71.1043632495873 42.315113108546,-71.1043583974082 42.3151211109857,
-71.1043443253471 42.3150676015829,-71.1043850704575 42.3150793250568,-71.1043632495873 42.315113108546)))');
-- 3D 원형 스트링
SELECT ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)');
-- 다면체 표면 예시
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))
)');

Name

ST_GeomFromMARC21 — Takes MARC21/XML geographic data as input and returns a PostGIS geometry object.

Synopsis

geometry ST_GeomFromMARC21 ( text marcxml );

설명

This function creates a PostGIS geometry from a MARC21/XML record, which can contain a POINT or a POLYGON. In case of multiple geographic data entries in the same MARC21/XML record, a MULTIPOINT or MULTIPOLYGON will be returned. If the record contains mixed geometry types, a GEOMETRYCOLLECTION will be returned. It returns NULL if the MARC21/XML record does not contain any geographic data (datafield:034).

LOC MARC21/XML versions supported:

Availability: 3.3.0, requires libxml2 2.6+

[Note]

The MARC21/XML Coded Cartographic Mathematical Data currently does not provide any means to describe the Spatial Reference System of the encoded coordinates, so this function will always return a geometry with SRID 0.

[Note]

Returned POLYGON geometries will always be clockwise oriented.

예시

Converting MARC21/XML geographic data containing a single POINT encoded as hddd.dddddd

SELECT
                ST_AsText(
                    ST_GeomFromMARC21('
                        <record xmlns="http://www.loc.gov/MARC21/slim">
                            <leader>00000nz a2200000nc 4500</leader>
                            <controlfield tag="001">040277569</controlfield>
                            <datafield tag="034" ind1=" " ind2=" ">
                                <subfield code="d">W004.500000</subfield>
                                <subfield code="e">W004.500000</subfield>
                                <subfield code="f">N054.250000</subfield>
                                <subfield code="g">N054.250000</subfield>
                            </datafield>
                        </record>'));

                st_astext
                -------------------
                POINT(-4.5 54.25)
                (1 row)

            

Converting MARC21/XML geographic data containing a single POLYGON encoded as hdddmmss

SELECT
                ST_AsText(
                    ST_GeomFromMARC21('
                        <record xmlns="http://www.loc.gov/MARC21/slim">
                            <leader>01062cem a2200241 a 4500</leader>
                            <controlfield tag="001">   84696781 </controlfield>
                            <datafield tag="034" ind1="1" ind2=" ">
                                <subfield code="a">a</subfield>
                                <subfield code="b">50000</subfield>
                                <subfield code="d">E0130600</subfield>
                                <subfield code="e">E0133100</subfield>
                                <subfield code="f">N0523900</subfield>
                                <subfield code="g">N0522300</subfield>
                            </datafield>
                        </record>'));

                st_astext
                -----------------------------------------------------------------------------------------------------------------------
                POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65))
                (1 row)

            

Converting MARC21/XML geographic data containing a POLYGON and a POINT:

SELECT
                ST_AsText(
                    ST_GeomFromMARC21('
                <record xmlns="http://www.loc.gov/MARC21/slim">
                    <datafield tag="034" ind1="1" ind2=" ">
                        <subfield code="a">a</subfield>
                        <subfield code="b">50000</subfield>
                        <subfield code="d">E0130600</subfield>
                        <subfield code="e">E0133100</subfield>
                        <subfield code="f">N0523900</subfield>
                        <subfield code="g">N0522300</subfield>
                    </datafield>
                    <datafield tag="034" ind1=" " ind2=" ">
                        <subfield code="d">W004.500000</subfield>
                        <subfield code="e">W004.500000</subfield>
                        <subfield code="f">N054.250000</subfield>
                        <subfield code="g">N054.250000</subfield>
                    </datafield>
                </record>'));
                                                                                        st_astext
                -------------------------------------------------------------------------------------------------------------------------------------------------------------
                GEOMETRYCOLLECTION(POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65)),POINT(-4.5 54.25))
                (1 row)
            

관련 정보

ST_AsMARC21


Name

ST_GeometryFromText — WKT(Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다. 이 함수는 ST_GeomFromText 함수와 동일합니다.

Synopsis

geometry ST_GeometryFromText(text WKT);

geometry ST_GeometryFromText(text WKT, integer srid);

설명

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.40

관련 정보

ST_GeomFromText


Name

ST_GeomFromText — WKT 표현식으로부터 지정된 ST_Geometry 값을 반환합니다.

Synopsis

geometry ST_GeomFromText(text WKT);

geometry ST_GeomFromText(text WKT, integer srid);

설명

OGC WKT(Well-Known Text) 표현식으로부터 PostGIS ST_Geometry 객체를 작성합니다.

[Note]

ST_GeomFromText 함수의 변종이 2개 있는데, 첫 번째는 SRID를 입력받지 않고 공간 참조 시스템이 정의되지 않은(SRID=0) 도형을 반환합니다. 두 번째는 SRID를 두 번째 인수로 입력받아 해당 SRID를 자체 메타데이터의 일부로 포함하는 도형을 반환합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.40

This method supports Circular Strings and Curves

[Note]

While not OGC-compliant, ST_MakePoint is faster than ST_GeomFromText and ST_PointFromText. It is also easier to use for numeric coordinate values. ST_Point is another option similar in speed to ST_MakePoint and is OGC-compliant, but doesn't support anything but 2D points.

[Warning]

변경 사항: PostGIS 2.0.0 미만 버전에서는 ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') 를 사용할 수 있었습니다. PostGIS 2.0.0 버전부터, SQL/MM 표준을 더 잘 준수하기 위해 이런 사용법은 금지됐습니다. 이제는 ST_GeomFromText('GEOMETRYCOLLECTION EMPTY') 라고 작성해야 합니다.

예시

SELECT ST_GeomFromText('LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)');
SELECT ST_GeomFromText('LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)',4269);

SELECT ST_GeomFromText('MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))');

SELECT ST_GeomFromText('POINT(-71.064544 42.28787)');

SELECT ST_GeomFromText('POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239,
-71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))');

SELECT ST_GeomFromText('MULTIPOLYGON(((-71.1031880899493 42.3152774590236,
-71.1031627617667 42.3152960829043,-71.102923838298 42.3149156848307,
-71.1023097974109 42.3151969047397,-71.1019285062273 42.3147384934248,
-71.102505233663 42.3144722937587,-71.10277487471 42.3141658254797,
-71.103113945163 42.3142739188902,-71.10324876416 42.31402489987,
-71.1033002961013 42.3140393340215,-71.1033488797549 42.3139495090772,
-71.103396240451 42.3138632439557,-71.1041521907712 42.3141153348029,
-71.1041411411543 42.3141545014533,-71.1041287795912 42.3142114839058,
-71.1041188134329 42.3142693656241,-71.1041112482575 42.3143272556118,
-71.1041072845732 42.3143851580048,-71.1041057218871 42.3144430686681,
-71.1041065602059 42.3145009876017,-71.1041097995362 42.3145589148055,
-71.1041166403905 42.3146168544148,-71.1041258822717 42.3146748022936,
-71.1041375307579 42.3147318674446,-71.1041492906949 42.3147711126569,
-71.1041598612795 42.314808571739,-71.1042515013869 42.3151287620809,
-71.1041173835118 42.3150739481917,-71.1040809891419 42.3151344119048,
-71.1040438678912 42.3151191367447,-71.1040194562988 42.3151832057859,
-71.1038734225584 42.3151140942995,-71.1038446938243 42.3151006300338,
-71.1038315271889 42.315094347535,-71.1037393329282 42.315054824985,
-71.1035447555574 42.3152608696313,-71.1033436658644 42.3151648370544,
-71.1032580383161 42.3152269126061,-71.103223066939 42.3152517403219,
-71.1031880899493 42.3152774590236)),
((-71.1043632495873 42.315113108546,-71.1043583974082 42.3151211109857,
-71.1043443253471 42.3150676015829,-71.1043850704575 42.3150793250568,-71.1043632495873 42.315113108546)))',4326);

SELECT ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)');
        

Name

ST_LineFromText — 주어진 SRID와 함께 WKT 표현식으로부터 도형을 만듭니다. SRID가 주어지지 않은 경우, 기본값인 0을 씁니다.

Synopsis

geometry ST_LineFromText(text WKT);

geometry ST_LineFromText(text WKT, integer srid);

설명

Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. If WKT passed in is not a LINESTRING, then null is returned.

[Note]

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

[Note]

사용자 도형이 모두 라인스트링이란 걸 알고 있다면, 그냥 ST_GeomFromText 함수를 쓰는 편이 더 효율적입니다. 이 함수는 ST_GeomFromText만 호출하고, 라인스트링을 반환한다는 유효성 검사를 추가합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 7.2.8

예시

SELECT ST_LineFromText('LINESTRING(1 2, 3 4)') AS aline, ST_LineFromText('POINT(1 2)') AS null_return;
aline                            | null_return
------------------------------------------------
010200000002000000000000000000F ... | t
                

관련 정보

ST_GeomFromText


Name

ST_MLineFromText — WKT 표현식으로부터 지정된 ST_MultiLineString 값을 반환합니다.

Synopsis

geometry ST_MLineFromText(text WKT, integer srid);

geometry ST_MLineFromText(text WKT);

설명

Makes a Geometry from Well-Known-Text (WKT) with the given SRID. If SRID is not given, it defaults to 0.

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

WKT가 멀티라인스트링이 아닌 경우 null을 반환합니다.

[Note]

사용자 WKT 도형이 모두 포인트라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification.SQL-MM 3: 9.4.4

예시

SELECT ST_MLineFromText('MULTILINESTRING((1 2, 3 4), (4 5, 6 7))');

관련 정보

ST_GeomFromText


Name

ST_MPointFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.

Synopsis

geometry ST_MPointFromText(text WKT, integer srid);

geometry ST_MPointFromText(text WKT);

설명

Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

WKT가 멀티포인트가 아닌 경우 null을 반환합니다.

[Note]

사용자 WKT 도형이 모두 포인트라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. 3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 9.2.4

예시

SELECT ST_MPointFromText('MULTIPOINT((1 2),(3 4))');
SELECT ST_MPointFromText('MULTIPOINT((-70.9590 42.1180),(-70.9611 42.1223))', 4326);

관련 정보

ST_GeomFromText


Name

ST_MPolyFromText — Makes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.

Synopsis

geometry ST_MPolyFromText(text WKT, integer srid);

geometry ST_MPolyFromText(text WKT);

설명

Makes a MultiPolygon from WKT with the given SRID. If SRID is not given, it defaults to 0.

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

WKT가 멀티폴리곤이 아닌 경우 오류가 발생합니다.

[Note]

사용자 WKT 도형이 모두 멀티폴리곤이라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 9.6.4

예시

SELECT ST_MPolyFromText('MULTIPOLYGON(((0 0 1,20 0 1,20 20 1,0 20 1,0 0 1),(5 5 3,5 7 3,7 7 3,7 5 3,5 5 3)))');
SELECt ST_MPolyFromText('MULTIPOLYGON(((-70.916 42.1002,-70.9468 42.0946,-70.9765 42.0872,-70.9754 42.0875,-70.9749 42.0879,-70.9752 42.0881,-70.9754 42.0891,-70.9758 42.0894,-70.9759 42.0897,-70.9759 42.0899,-70.9754 42.0902,-70.9756 42.0906,-70.9753 42.0907,-70.9753 42.0917,-70.9757 42.0924,-70.9755 42.0928,-70.9755 42.0942,-70.9751 42.0948,-70.9755 42.0953,-70.9751 42.0958,-70.9751 42.0962,-70.9759 42.0983,-70.9767 42.0987,-70.9768 42.0991,-70.9771 42.0997,-70.9771 42.1003,-70.9768 42.1005,-70.977 42.1011,-70.9766 42.1019,-70.9768 42.1026,-70.9769 42.1033,-70.9775 42.1042,-70.9773 42.1043,-70.9776 42.1043,-70.9778 42.1048,-70.9773 42.1058,-70.9774 42.1061,-70.9779 42.1065,-70.9782 42.1078,-70.9788 42.1085,-70.9798 42.1087,-70.9806 42.109,-70.9807 42.1093,-70.9806 42.1099,-70.9809 42.1109,-70.9808 42.1112,-70.9798 42.1116,-70.9792 42.1127,-70.979 42.1129,-70.9787 42.1134,-70.979 42.1139,-70.9791 42.1141,-70.9987 42.1116,-71.0022 42.1273,
        -70.9408 42.1513,-70.9315 42.1165,-70.916 42.1002)))',4326);

관련 정보

ST_GeomFromText, ST_SRID


Name

ST_PointFromText — 주어진 SRID와 함께 WKT 표현식으로부터 포인트 도형을 만듭니다. SRID가 주어지지 않은 경우, 기본값인 0을 씁니다.

Synopsis

geometry ST_PointFromText(text WKT);

geometry ST_PointFromText(text WKT, integer srid);

설명

Constructs a PostGIS ST_Geometry point object from the OGC Well-Known text representation. If SRID is not given, it defaults to unknown (currently 0). If geometry is not a WKT point representation, returns null. If completely invalid WKT, then throws an error.

[Note]

ST_PointFromText 함수의 변종이 2개 있는데, 첫 번째는 SRID를 입력받지 않고 공간 참조 시스템이 정의되지 않은 도형을 반환합니다. 두 번째는 SRID를 두 번째 인수로 입력받아 자체 메타데이터의 일부로 해당 SRID를 포함하는 ST_Geometry를 반환합니다. spatial_ref_sys 테이블에 정의되어 있는 SRID여야 합니다.

[Note]

사용자 WKT 도형이 모두 포인트라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다. 사용자가 경위도 좌표로부터 포인트를 빌드하고 OGC 준수 여부보다 성능 및 정확도에 더 관심이 있다면, ST_MakePoint 또는 OGC를 준수하는 동일한 ST_Point 함수를 이용하십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

This method implements the SQL/MM specification. SQL-MM 3: 6.1.8

예시

SELECT ST_PointFromText('POINT(-71.064544 42.28787)');
SELECT ST_PointFromText('POINT(-71.064544 42.28787)', 4326);
        

Name

ST_PolygonFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.

Synopsis

geometry ST_PolygonFromText(text WKT);

geometry ST_PolygonFromText(text WKT, integer srid);

설명

Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. Returns null if WKT is not a polygon.

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

[Note]

사용자 WKT 도형이 모두 폴리곤이라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 8.3.6

예시

SELECT ST_PolygonFromText('POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239,
-71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))');
st_polygonfromtext
------------------
010300000001000000050000006...


SELECT ST_PolygonFromText('POINT(1 2)') IS NULL as point_is_notpoly;

point_is_not_poly
----------
t

관련 정보

ST_GeomFromText


Name

ST_WKTToSQL — WKT(Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다. 이 함수는 ST_GeomFromText 함수와 동일합니다.

Synopsis

geometry ST_WKTToSQL(text WKT);

설명

This method implements the SQL/MM specification. SQL-MM 3: 5.1.34

관련 정보

ST_GeomFromText

8.8.2. Well-Known Binary (WKB)

ST_GeogFromWKB — WKB 도형 표현식 또는 EWKB(확장 WKB)로부터 지리형 인스턴스를 생성합니다.
ST_GeomFromEWKB — EWKB(Extended Well-Known Binary)로부터 지정된 ST_Geometry 값을 반환합니다.
ST_GeomFromWKB — WKB(Well-Known Binary) 도형 표현식과 선택적인 SRID로부터 도형 인스턴스를 생성합니다.
ST_LineFromWKB — 주어진 SRID와 함께 WKB로부터 LINESTRING 을 만듭니다.
ST_LinestringFromWKB — 주어진 SRID와 함께 WKB로부터 도형을 만듭니다.
ST_PointFromWKB — 주어진 SRID와 함께 WKB로부터 도형을 만듭니다.
ST_WKBToSQL — WKB(Well-Known Binary) 표현식으로부터 지정된 ST_Geometry 값을 반환합니다. 이 함수는 SRID를 입력받지 않는 ST_GeomFromWKB 함수와 동일합니다.

Name

ST_GeogFromWKB — WKB 도형 표현식 또는 EWKB(확장 WKB)로부터 지리형 인스턴스를 생성합니다.

Synopsis

geography ST_GeogFromWKB(bytea wkb);

설명

ST_GeogFromWKB 함수는 도형의 WKB 표현식 또는 PostGIS 확장 WKB를 받아 적절한 지리형 유형의 인스턴스를 생성합니다. 이 함수는 SQL에서 도형 공장(Geometry Factory) 역할을 합니다.

SRID를 설정하지 않은 경우, 기본값으로 4326(WGS84 경위도)을 씁니다.

This method supports Circular Strings and Curves

예시

-- bytea 표현식이 단일한 역슬래시(\)를 포함하긴 해도, 테이블 삽입시에는 빼놓아야 합니다.
SELECT ST_AsText(
ST_GeogFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@')
);
                                          st_astext
------------------------------------------------------
 LINESTRING(-113.98 39.198,-113.981 39.195)
(1 row)


Name

ST_GeomFromEWKB — EWKB(Extended Well-Known Binary)로부터 지정된 ST_Geometry 값을 반환합니다.

Synopsis

geometry ST_GeomFromEWKB(bytea EWKB);

설명

OGC EWKB(Extended Well-Known Binary) 표현식으로부터 PostGIS ST_Geometry 객체를 작성합니다.

[Note]

EWKB 형식이 OGC 표준은 아니지만, SRID(공간 참조 시스템 식별자)를 포함하는 PostGIS 특화 형식입니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 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).

예시

NAD83 경위도(SRID 4269)로 투영된 LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)의 라인스트링 바이너리 표현식

[Note]

주의: 바이트 배열이 역슬래시(\)로 구분되고 작은따옴표(')를 가지고 있을 수도 있지만, standard_conforming_strings가 비활성화돼 있을 경우 \ 및 " 둘 다 빼놓아야 합니다. 그래야만 AsEWKB 표현식과 똑같이 보이지 않기 때문입니다.

SELECT ST_GeomFromEWKB(E'\\001\\002\\000\\000 \\255\\020\\000\\000\\003\\000\\000\\000\\344J=
\\013B\\312Q\\300n\\303(\\010\\036!E@''\\277E''K
\\312Q\\300\\366{b\\235*!E@\\225|\\354.P\\312Q
\\300p\\231\\323e1!E@');
[Note]

In PostgreSQL 9.1+ - standard_conforming_strings is set to on by default, where as in past versions it was set to off. You can change defaults as needed for a single query or at the database or server level. Below is how you would do it with standard_conforming_strings = on. In this case we escape the ' with standard ansi ', but slashes are not escaped

set standard_conforming_strings = on;
SELECT ST_GeomFromEWKB('\001\002\000\000 \255\020\000\000\003\000\000\000\344J=\012\013B
\312Q\300n\303(\010\036!E@''\277E''K\012\312Q\300\366{b\235*!E@\225|\354.P\312Q\012\300p\231\323e1')

Name

ST_GeomFromWKB — WKB(Well-Known Binary) 도형 표현식과 선택적인 SRID로부터 도형 인스턴스를 생성합니다.

Synopsis

geometry ST_GeomFromWKB(bytea geom);

geometry ST_GeomFromWKB(bytea geom, integer srid);

설명

ST_GeogFromWKB 함수는 도형의 WKB 표현식과 SRID(공간 참조 시스템 ID)를 받아 적절한 도형 유형의 인스턴스를 생성합니다. 이 함수는 SQL에서 도형 공장(Geometry Factory) 역할을 합니다. 이 함수는 ST_WKBToSQL 함수를 대체할 수 있습니다.

SRID를 설정하지 않은 경우, 기본값으로 0(unkown)을 씁니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.7.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.41

This method supports Circular Strings and Curves

예시

-- standard_conforming_strings이 활성화돼 있지 않은 경우
                -- bytea 표현식이 단일한 역슬래시(\)를 포함하긴 해도, 테이블 삽입시에는 빼놓아야 합니다.
SELECT ST_AsEWKT(
ST_GeomFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@',4326)
);
                                          st_asewkt
------------------------------------------------------
 SRID=4326;LINESTRING(-113.98 39.198,-113.981 39.195)
(1 row)

SELECT
  ST_AsText(
        ST_GeomFromWKB(
          ST_AsEWKB('POINT(2 5)'::geometry)
        )
  );
 st_astext
------------
 POINT(2 5)
(1 row)

Name

ST_LineFromWKB — 주어진 SRID와 함께 WKB로부터 LINESTRING 을 만듭니다.

Synopsis

geometry ST_LineFromWKB(bytea WKB);

geometry ST_LineFromWKB(bytea WKB, integer srid);

설명

ST_LineFromWKB 함수는 도형의 WKB 표현식과 SRID(공간 참조 시스템 ID)를 받아 적절한 도형 유형의 인스턴스 - 이 경우, LINESTRING 도형 - 를 생성합니다. 이 함수는 SQL에서 도형 공장(Geometry Factory) 역할을 합니다.

SRID를 설정하지 않은 경우, 기본값인 0을 씁니다. 입력된 bytea가 라인스트링이 아닌 경우, NULL을 반환합니다.

[Note]

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

[Note]

사용자 도형이 모두 LINESTRING이란 걸 알고 있다면, 그냥 ST_GeomFromWKB 함수를 쓰는 편이 더 효율적입니다. 이 함수는 ST_GeomFromWKB 만 호출하고, 라인스트링을 반환한다는 유효성 검사를 추가합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 7.2.9

예시

SELECT ST_LineFromWKB(ST_AsBinary(ST_GeomFromText('LINESTRING(1 2, 3 4)'))) AS aline,
                ST_LineFromWKB(ST_AsBinary(ST_GeomFromText('POINT(1 2)'))) IS NULL AS null_return;
aline                            | null_return
------------------------------------------------
010200000002000000000000000000F ... | t
                

Name

ST_LinestringFromWKB — 주어진 SRID와 함께 WKB로부터 도형을 만듭니다.

Synopsis

geometry ST_LinestringFromWKB(bytea WKB);

geometry ST_LinestringFromWKB(bytea WKB, integer srid);

설명

ST_LinestringFromWKB 함수는 도형의 WKB 표현식과 SRID(공간 참조 시스템 ID)를 받아 적절한 도형 유형의 인스턴스 - 이 경우, LINESTRING 도형 - 를 생성합니다. 이 함수는 SQL에서 도형 공장(Geometry Factory) 역할을 합니다.

SRID를 설정하지 않은 경우, 기본값인 0을 씁니다. 입력된 byteaLINESTRING 도형이 아닌 경우, NULL을 반환합니다.

[Note]

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

[Note]

사용자 도형이 모두 LINESTRING이란 걸 알고 있다면, 그냥 ST_GeomFromWKB 함수를 쓰는 편이 더 효율적입니다. 이 함수는 ST_GeomFromWKB 만 호출하고, LINESTRING을 반환한다는 유효성 검사를 추가합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 7.2.9

예시

SELECT
  ST_LineStringFromWKB(
        ST_AsBinary(ST_GeomFromText('LINESTRING(1 2, 3 4)'))
  ) AS aline,
  ST_LinestringFromWKB(
        ST_AsBinary(ST_GeomFromText('POINT(1 2)'))
  ) IS NULL AS null_return;
   aline                            | null_return
------------------------------------------------
010200000002000000000000000000F ... | t

Name

ST_PointFromWKB — 주어진 SRID와 함께 WKB로부터 도형을 만듭니다.

Synopsis

geometry ST_GeomFromWKB(bytea geom);

geometry ST_GeomFromWKB(bytea geom, integer srid);

설명

ST_PointFromWKB 함수는 도형의 WKB 표현식과 SRID(공간 참조 시스템 ID)를 받아 적절한 도형 유형의 인스턴스 - 이 경우, POINT 도형 - 를 생성합니다. 이 함수는 SQL에서 도형 공장(Geometry Factory) 역할을 합니다.

SRID를 설정하지 않은 경우, 기본값인 0을 씁니다. 입력된 bytea가 포인트가 아닌 경우, NULL을 반환합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.7.2

This method implements the SQL/MM specification. SQL-MM 3: 6.1.9

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves

예시

SELECT
  ST_AsText(
        ST_PointFromWKB(
          ST_AsEWKB('POINT(2 5)'::geometry)
        )
  );
 st_astext
------------
 POINT(2 5)
(1 row)

SELECT
  ST_AsText(
        ST_PointFromWKB(
          ST_AsEWKB('LINESTRING(2 5, 2 6)'::geometry)
        )
  );
 st_astext
-----------

(1 row)

Name

ST_WKBToSQL — WKB(Well-Known Binary) 표현식으로부터 지정된 ST_Geometry 값을 반환합니다. 이 함수는 SRID를 입력받지 않는 ST_GeomFromWKB 함수와 동일합니다.

Synopsis

geometry ST_WKBToSQL(bytea WKB);

설명

This method implements the SQL/MM specification. SQL-MM 3: 5.1.36

관련 정보

ST_GeomFromWKB

8.8.3. Other Formats

ST_Box2dFromGeoHash — GeoHash 스트링으로부터 BOX2D를 반환합니다.
ST_GeomFromGeoHash — GeoHash 스트링으로부터 도형을 반환합니다.
ST_GeomFromGML — 도형의 GML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
ST_GeomFromGeoJSON — GeoJSON 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
ST_GeomFromKML — 도형의 KML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
ST_GeomFromTWKB — TWKB("Tiny Well-Known Binary") 도형 표현식으로부터 도형 인스턴스를 생성합니다.
ST_GMLToSQL — GML로부터 지정된 ST_Geometry 값을 반환합니다. 이 함수는 ST_GeomFromGML 함수와 동일합니다.
ST_LineFromEncodedPolyline — 인코딩된 폴리라인(polyline)으로부터 라인스트링을 생성합니다.
ST_PointFromGeoHash — GeoHash 스트링으로부터 포인트를 반환합니다.
ST_FromFlatGeobufToTable — Creates a table based on the structure of FlatGeobuf data.
ST_FromFlatGeobuf — Reads FlatGeobuf data.

Name

ST_Box2dFromGeoHash — GeoHash 스트링으로부터 BOX2D를 반환합니다.

Synopsis

box2d ST_Box2dFromGeoHash(text geohash, integer precision=full_precision_of_geohash);

설명

GeoHash 스트링으로부터 BOX2D를 반환합니다.

If no precision is specified ST_Box2dFromGeoHash returns a BOX2D based on full precision of the input GeoHash string.

precision 을 설정한 경우, ST_Box2dFromGeoHash가 GeoHash에서 나온 그만큼의 문자를 이용해서 BOX2D를 생성합니다. 정확도 값이 낮을수록 BOX2D의 용량이 커지고 값이 높을수록 정확도가 올라갑니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0');

                st_geomfromgeohash
--------------------------------------------------
 BOX(-115.172816 36.114646,-115.172816 36.114646)

SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 0);

 st_box2dfromgeohash
----------------------
 BOX(-180 -90,180 90)

 SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10);
                            st_box2dfromgeohash
---------------------------------------------------------------------------
 BOX(-115.17282128334 36.1146408319473,-115.172810554504 36.1146461963654)
                
                

Name

ST_GeomFromGeoHash — GeoHash 스트링으로부터 도형을 반환합니다.

Synopsis

geometry ST_GeomFromGeoHash(text geohash, integer precision=full_precision_of_geohash);

설명

GeoHash 스트링으로부터 도형을 반환합니다. 해당 도형은 GeoHash 범위를 표현하는 폴리곤이 될 것입니다.

precision 을 설정하지 않은 경우, ST_GeomFromGeoHash가 입력 GeoHash 스트링의 전체 정확도를 기반으로 폴리곤을 반환합니다.

precision 을 설정한 경우, ST_GeomFromGeoHash가 GeoHash에서 나온 그만큼의 문자를 이용해서 폴리곤을 생성합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

SELECT ST_AsText(ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0'));
                                                        st_astext
--------------------------------------------------------------------------------------------------------------------------
 POLYGON((-115.172816 36.114646,-115.172816 36.114646,-115.172816 36.114646,-115.172816 36.114646,-115.172816 36.114646))

SELECT ST_AsText(ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 4));
                                                          st_astext
------------------------------------------------------------------------------------------------------------------------------
 POLYGON((-115.3125 36.03515625,-115.3125 36.2109375,-114.9609375 36.2109375,-114.9609375 36.03515625,-115.3125 36.03515625))

SELECT ST_AsText(ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10));
                                                                                       st_astext
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 POLYGON((-115.17282128334 36.1146408319473,-115.17282128334 36.1146461963654,-115.172810554504 36.1146461963654,-115.172810554504 36.1146408319473,-115.17282128334 36.1146408319473))
                
                

Name

ST_GeomFromGML — 도형의 GML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.

Synopsis

geometry ST_GeomFromGML(text geomgml);

geometry ST_GeomFromGML(text geomgml, integer srid);

설명

OGC GML 표현식으로부터 PostGIS ST_Geometry 객체를 작성합니다.

ST_GeomFromGML은 GML 도형 조각(geometry fragment)에 대해서만 작동합니다. 완전한 GML 문서를 사용하려 할 경우 오류가 발생합니다.

지원하는 OGC GML 버전은 다음과 같습니다:

  • GML 3.2.1 네임스페이스

  • GML 3.1.1 단순 피처 프로파일 SF-2 (GML 3.1.0 및 3.0.0 하위 호환)

  • GML 2.1.2

OGC GML 표준: http://www.opengeospatial.org/standards/gml

1.5 버전부터 사용할 수 있습니다. LibXML2 1.6 이상 버전이 필요합니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다.

개선 사항: 2.0.0 버전에서 선택적인 기본 SRID 파라미터가 추가됐습니다.

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).

GML은 혼합 차원을 (예를 들어 동일한 멀티 도형(MultiGeometry) 안에서 2D와 3D를 함께) 쓸 수 있습니다. PostGIS 도형은 그렇지 않기 때문에, 사라진 Z 차원을 찾은 경우 ST_GeomFromGML이 전체 도형을 2D로 변환합니다.

GML은 동일한 멀티 도형 안에서 혼합 SRS를 지원합니다. PostGIS 도형은 그렇지 않기 때문에, 이 경우 ST_GeomFromGML이 모든 하위 도형들을 SRS 루트 노드로 재투영합니다. GML 루트 노드로 쓸 수 있는 srsName 속성이 없을 경우, 오류가 발생합니다.

ST_GeomFromGML은 분명한 GML 네임스페이스를 꼼꼼히 따지지 않습니다. 일반적인 사용시에는 네임스페이스를 명시적으로 언급하지 않아도 됩니다. 하지만 GML 내부에 XLink 피처를 사용하고 싶다면 그래야 합니다.

[Note]

ST_GeomFromGML 함수는 SQL/MM 만곡 도형을 지원하지 않습니다.

예시: srsName을 가진 단일 도형

SELECT ST_GeomFromGML('
                <gml:LineString srsName="EPSG:4269">
                        <gml:coordinates>
                                -71.16028,42.258729 -71.160837,42.259112 -71.161143,42.25932
                        </gml:coordinates>
                </gml:LineString
>');
                

예시: XLink 사용

SELECT ST_GeomFromGML('
                <gml:LineString xmlns:gml="http://www.opengis.net/gml"
                                xmlns:xlink="http://www.w3.org/1999/xlink"
                                srsName="urn:ogc:def:crs:EPSG::4269">
                        <gml:pointProperty>
                                <gml:Point gml:id="p1"
><gml:pos
>42.258729 -71.16028</gml:pos
></gml:Point>
                        </gml:pointProperty>
                        <gml:pos
>42.259112 -71.160837</gml:pos>
                        <gml:pointProperty>
                                <gml:Point xlink:type="simple" xlink:href="#p1"/>
                        </gml:pointProperty>
                </gml:LineString
>'););
                

예시: 다면체 표면

SELECT ST_AsEWKT(ST_GeomFromGML('
<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
>'));

-- 결과 --
 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)))
                

Name

ST_GeomFromGeoJSON — GeoJSON 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.

Synopsis

geometry ST_GeomFromGeoJSON(text geomjson);

geometry ST_GeomFromGeoJSON(json geomjson);

geometry ST_GeomFromGeoJSON(jsonb geomjson);

설명

GeoJSON 표현식으로부터 PostGIS 도형 객체를 작성합니다.

ST_GeomFromGML은 JSON 도형 조각(geometry fragment)에 대해서만 작동합니다. 완전한 JSON 문서를 사용하려 할 경우 오류가 발생합니다.

Enhanced: 3.0.0 parsed geometry defaults to SRID=4326 if not specified otherwise.

Enhanced: 2.5.0 can now accept json and jsonb as inputs.

2.0.0 버전부터 사용할 수 있습니다. JSON-C 0.9 이상 버전이 필요합니다.

[Note]

JSON-C 지원을 활성화시키지 않았다면, 출력물 대신 오류 메시지를 보게 될 것입니다. JSON-C를 활성화하려면, "--with-jsondir=/path/to/json-c" 인자와 함께 설정하십시오. 자세한 내용은 Section 2.2.3, “설정” 을 참조하십시오.

This function supports 3d and will not drop the z-index.

예시

SELECT ST_AsText(ST_GeomFromGeoJSON('{"type":"Point","coordinates":[-48.23456,20.12345]}')) As wkt;
wkt
------
POINT(-48.23456 20.12345)
-- a 3D linestring
SELECT ST_AsText(ST_GeomFromGeoJSON('{"type":"LineString","coordinates":[[1,2,3],[4,5,6],[7,8,9]]}')) As wkt;

wkt
-------------------
LINESTRING(1 2,4 5,7 8)

Name

ST_GeomFromKML — 도형의 KML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.

Synopsis

geometry ST_GeomFromKML(text geomkml);

설명

OGC KML 표현식으로부터 PostGIS ST_Geometry 객체를 작성합니다.

ST_GeomFromKML은 KML 도형 조각(geometry fragment)에 대해서만 작동합니다. 완전한 KML 문서를 사용하려 할 경우 오류가 발생합니다.

지원하는 OGC KML 버전은 다음과 같습니다:

  • KML 2.2.0 네임스페이스

OGC KML 표준: http://www.opengeospatial.org/standards/kml

Availability: 1.5, requires libxml2 2.6+

This function supports 3d and will not drop the z-index.

[Note]

ST_GeomFromKML 함수는 SQL/MM 만곡 도형을 지원하지 않습니다.

예시: srsName을 가진 단일 도형

SELECT ST_GeomFromKML('
                <LineString>
                        <coordinates
>-71.1663,42.2614
                                -71.1667,42.2616</coordinates>
                </LineString
>');
                

Name

ST_GeomFromTWKB — TWKB("Tiny Well-Known Binary") 도형 표현식으로부터 도형 인스턴스를 생성합니다.

Synopsis

geometry ST_GeomFromTWKB(bytea twkb);

설명

ST_GeomFromTWKB 함수는 TWKB("Tiny Well-Known Binary") 도형 표현식(WKB)을 받아 적절한 도형 유형의 인스턴스를 생성합니다.

예시

SELECT ST_AsText(ST_GeomFromTWKB(ST_AsTWKB('LINESTRING(126 34, 127 35)'::geometry)));

         st_astext
-----------------------------
 LINESTRING(126 34, 127 35)
(1 row)


SELECT ST_AsEWKT(
  ST_GeomFromTWKB(E'\\x620002f7f40dbce4040105')
);
                                          st_asewkt
------------------------------------------------------
LINESTRING(-113.98 39.198,-113.981 39.195)
(1 row)

관련 정보

ST_AsTWKB


Name

ST_GMLToSQL — GML로부터 지정된 ST_Geometry 값을 반환합니다. 이 함수는 ST_GeomFromGML 함수와 동일합니다.

Synopsis

geometry ST_GMLToSQL(text geomgml);

geometry ST_GMLToSQL(text geomgml, integer srid);

설명

This method implements the SQL/MM specification. SQL-MM 3: 5.1.50 (만곡 도형 지원 제외)

1.5 버전부터 사용할 수 있습니다. LibXML2 1.6 이상 버전이 필요합니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다.

개선 사항: 2.0.0 버전에서 선택적인 기본 SRID 파라미터가 추가됐습니다.


Name

ST_LineFromEncodedPolyline — 인코딩된 폴리라인(polyline)으로부터 라인스트링을 생성합니다.

Synopsis

geometry ST_LineFromEncodedPolyline(text polyline, integer precision=5);

설명

인코딩된 폴리라인 스트링으로부터 라인스트링을 생성합니다.

Optional precision specifies how many decimal places will be preserved in Encoded Polyline. Value should be the same on encoding and decoding, or coordinates will be incorrect.

참조: http://developers.google.com/maps/documentation/utilities/polylinealgorithm

2.2.0 버전부터 사용할 수 있습니다.

예시

-- Create a line string from a polyline
SELECT ST_AsEWKT(ST_LineFromEncodedPolyline('_p~iF~ps|U_ulLnnqC_mqNvxq`@'));
-- result --
SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)

-- Select different precision that was used for polyline encoding
SELECT ST_AsEWKT(ST_LineFromEncodedPolyline('_p~iF~ps|U_ulLnnqC_mqNvxq`@',6));
-- result --
SRID=4326;LINESTRING(-12.02 3.85,-12.095 4.07,-12.6453 4.3252)

    

Name

ST_PointFromGeoHash — GeoHash 스트링으로부터 포인트를 반환합니다.

Synopsis

point ST_PointFromGeoHash(text geohash, integer precision=full_precision_of_geohash);

설명

GeoHash 스트링으로부터 포인트를 반환합니다. 해당 포인트는 GeoHash의 중심점입니다.

precision 을 설정하지 않은 경우, ST_PointFromGeoHash가 입력 GeoHash 스트링의 전체 정확도를 기반으로 포인트를 반환합니다.

precision 을 설정한 경우, ST_PointFromGeoHash가 GeoHash에서 나온 그만큼의 문자를 이용해서 포인트를 생성합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0'));
          st_astext
------------------------------
 POINT(-115.172816 36.114646)

SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 4));
             st_astext
-----------------------------------
 POINT(-115.13671875 36.123046875)

SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10));
                 st_astext
-------------------------------------------
 POINT(-115.172815918922 36.1146435141563)
                
                

Name

ST_FromFlatGeobufToTable — Creates a table based on the structure of FlatGeobuf data.

Synopsis

geometry ST_BdPolyFromText(text WKT, integer srid);

설명

Creates a table based on the structure of FlatGeobuf data. (http://flatgeobuf.org).

schema Schema name.

table Table name.

data Input FlatGeobuf data.

Availability: 3.2.0


Name

ST_FromFlatGeobuf — Reads FlatGeobuf data.

Synopsis

setof anyelement ST_FromFlatGeobuf(anyelement Table reference, bytea FlatGeobuf input data);

설명

Reads FlatGeobuf data (http://flatgeobuf.org). NOTE: PostgreSQL bytea cannot exceed 1GB.

tabletype reference to a table type.

data input FlatGeobuf data.

Availability: 3.2.0

8.9. Geometry Output

Abstract

These functions convert geometry objects into various textual or binary formats.

8.9.1. Well-Known Text (WKT)

ST_AsEWKT — 도형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터와 함께 반환합니다.
ST_AsText — 도형/지리형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터 없이 반환합니다.

Name

ST_AsEWKT — 도형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터와 함께 반환합니다.

Synopsis

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 ST_GeomFromEWKT.

[Warning]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

[Note]

The WKT spec does not include the SRID. To get the OGC WKT format use ST_AsText.

[Warning]

WKT format does not maintain precision so to prevent floating truncation, use ST_AsBinary or ST_AsEWKB format for transport.

Enhanced: 3.1.0 support for optional precision parameter.

개선 사항: 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)

Name

ST_AsText — 도형/지리형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터 없이 반환합니다.

Synopsis

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);

설명

Returns the OGC Well-Known Text (WKT) representation of the geometry/geography. The optional maxdecimaldigits argument may be used to limit the number of digits after the decimal point in output ordinates (defaults to 15).

To perform the inverse conversion of WKT representation to PostGIS geometry use ST_GeomFromText.

[Note]

The standard OGC WKT representation does not include the SRID. To include the SRID as part of the output representation, use the non-standard PostGIS function ST_AsEWKT

[Warning]

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 maxdecimaldigits).

[Warning]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

1.5.0 버전부터 지리형을 지원합니다.

Enhanced: 2.5 - optional parameter precision introduced.

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))

Full precision output is the default.

SELECT ST_AsText('POINT(111.1111111 1.1111111)'));
    st_astext
------------------------------
 POINT(111.1111111 1.1111111)

The maxdecimaldigits argument can be used to limit output precision.

SELECT ST_AsText('POINT(111.1111111 1.1111111)'), 2);
    st_astext
--------------------
 POINT(111.11 1.11)

8.9.2. Well-Known Binary (WKB)

ST_AsBinary — Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
ST_AsEWKB — Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
ST_AsHEXEWKB — 도형을 소 엔디안(NDR) 또는 대 엔디안(XDR) 인코딩을 통해 HEXEWKB (텍스트) 형식으로 반환합니다.

Name

ST_AsBinary — Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.

Synopsis

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);

설명

Returns the OGC/ISO Well-Known Binary (WKB) representation of the geometry. The first function variant defaults to encoding using server machine endian. The second function variant takes a text argument specifying the endian encoding, either little-endian ('NDR') or big-endian ('XDR').

WKB format is useful to read geometry data from the database and maintaining full numeric precision. This avoids